Java Tutorial
Java methods, java classes, java file handling, java how to's, java reference, java examples, java operators.
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Try it Yourself »
Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:
Java divides the operators into the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
+ | Addition | Adds together two values | x + y | |
- | Subtraction | Subtracts one value from another | x - y | |
* | Multiplication | Multiplies two values | x * y | |
/ | Division | Divides one value by another | x / y | |
% | Modulus | Returns the division remainder | x % y | |
++ | Increment | Increases the value of a variable by 1 | ++x | |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Advertisement
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :
The addition assignment operator ( += ) adds a value to a variable:
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.
The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.
In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:
Operator | Name | Example | Try it |
---|---|---|---|
== | Equal to | x == y | |
!= | Not equal | x != y | |
> | Greater than | x > y | |
< | Less than | x < y | |
>= | Greater than or equal to | x >= y | |
<= | Less than or equal to | x <= y |
Java Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 | |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 | |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
Java Bitwise Operators
Bitwise operators are used to perform binary logic with the bits of an integer or long integer.
Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND - Sets each bit to 1 if both bits are 1 | 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR - Sets each bit to 1 if any of the two bits is 1 | 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT - Inverts all the bits | ~ 5 | ~0101 | 1010 | 10 |
^ | XOR - Sets each bit to 1 if only one of the two bits is 1 | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off | 9 << 1 | 1001 << 1 | 0010 | 2 |
>> | Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off | 9 >> 1 | 1001 >> 1 | 1100 | 12 |
>>> | Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off | 9 >>> 1 | 1001 >>> 1 | 0100 | 4 |
Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010
In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100
Test Yourself With Exercises
Multiply 10 with 5 , and print the result.
Start the Exercise
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
Learn Java practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn java interactively, java introduction.
- Get Started With Java
- Your First Java Program
- Java Comments
Java Fundamentals
- Java Variables and Literals
- Java Data Types (Primitive)
Java Operators
- Java Basic Input and Output
- Java Expressions, Statements and Blocks
Java Flow Control
- Java if...else Statement
Java Ternary Operator
- Java for Loop
- Java for-each Loop
- Java while and do...while Loop
- Java break Statement
- Java continue Statement
- Java switch Statement
- Java Arrays
- Java Multidimensional Arrays
- Java Copy Arrays
Java OOP(I)
- Java Class and Objects
- Java Methods
- Java Method Overloading
- Java Constructors
- Java Static Keyword
- Java Strings
- Java Access Modifiers
- Java this Keyword
- Java final keyword
- Java Recursion
Java instanceof Operator
Java OOP(II)
- Java Inheritance
- Java Method Overriding
- Java Abstract Class and Abstract Methods
- Java Interface
- Java Polymorphism
- Java Encapsulation
Java OOP(III)
- Java Nested and Inner Class
- Java Nested Static Class
- Java Anonymous Class
- Java Singleton Class
- Java enum Constructor
- Java enum Strings
- Java Reflection
- Java Package
- Java Exception Handling
- Java Exceptions
- Java try...catch
- Java throw and throws
- Java catch Multiple Exceptions
- Java try-with-resources
- Java Annotations
- Java Annotation Types
- Java Logging
- Java Assertions
- Java Collections Framework
- Java Collection Interface
- Java ArrayList
- Java Vector
- Java Stack Class
- Java Queue Interface
- Java PriorityQueue
- Java Deque Interface
- Java LinkedList
- Java ArrayDeque
- Java BlockingQueue
- Java ArrayBlockingQueue
- Java LinkedBlockingQueue
- Java Map Interface
- Java HashMap
- Java LinkedHashMap
- Java WeakHashMap
- Java EnumMap
- Java SortedMap Interface
- Java NavigableMap Interface
- Java TreeMap
- Java ConcurrentMap Interface
- Java ConcurrentHashMap
- Java Set Interface
- Java HashSet Class
- Java EnumSet
- Java LinkedHashSet
- Java SortedSet Interface
- Java NavigableSet Interface
- Java TreeSet
- Java Algorithms
- Java Iterator Interface
- Java ListIterator Interface
Java I/o Streams
- Java I/O Streams
- Java InputStream Class
- Java OutputStream Class
- Java FileInputStream Class
- Java FileOutputStream Class
- Java ByteArrayInputStream Class
- Java ByteArrayOutputStream Class
- Java ObjectInputStream Class
- Java ObjectOutputStream Class
- Java BufferedInputStream Class
- Java BufferedOutputStream Class
- Java PrintStream Class
Java Reader/Writer
- Java File Class
- Java Reader Class
- Java Writer Class
- Java InputStreamReader Class
- Java OutputStreamWriter Class
- Java FileReader Class
- Java FileWriter Class
- Java BufferedReader
- Java BufferedWriter Class
- Java StringReader Class
- Java StringWriter Class
- Java PrintWriter Class
Additional Topics
- Java Keywords and Identifiers
Java Operator Precedence
Java Bitwise and Shift Operators
- Java Scanner Class
- Java Type Casting
- Java Wrapper Class
- Java autoboxing and unboxing
- Java Lambda Expressions
- Java Generics
- Nested Loop in Java
- Java Command-Line Arguments
Java Tutorials
- Java Math IEEEremainder()
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
- Arithmetic Operators
- Assignment Operators
- Relational Operators
- Logical Operators
- Unary Operators
- Bitwise Operators
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
Here, the + operator is used to add two variables a and b . Similarly, there are various other arithmetic operators in Java.
Operator | Operation |
Addition | |
Subtraction | |
Multiplication | |
Division | |
Modulo Operation (Remainder after division) |
Example 1: Arithmetic Operators
In the above example, we have used + , - , and * operators to compute addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a / b in our program. The / operator is the division operator.
If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.
% Modulo Operator
The modulo operator % computes the remainder. When a = 7 is divided by b = 4 , the remainder is 3 .
Note : The % operator is mainly used with integers.
2. Java Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age .
Let's see some more assignment operators available in Java.
Operator | Example | Equivalent to |
---|---|---|
Example 2: Assignment Operators
3. java relational operators.
Relational operators are used to check the relationship between two operands. For example,
Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false .
Operator | Description | Example |
---|---|---|
Is Equal To | returns | |
Not Equal To | returns | |
Greater Than | returns | |
Less Than | returns | |
Greater Than or Equal To | returns | |
Less Than or Equal To | returns |
Example 3: Relational Operators
Note : Relational operators are used in decision making and loops.
4. Java Logical Operators
Logical operators are used to check whether an expression is true or false . They are used in decision making.
Operator | Example | Meaning |
---|---|---|
(Logical AND) | expression1 expression2 | only if both and are |
(Logical OR) | expression1 expression2 | if either or is |
(Logical NOT) | expression | if is and vice versa |
Example 4: Logical Operators
Working of Program
- (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .
- (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .
- (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .
- (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .
- (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .
- !(5 == 3) returns true because 5 == 3 is false .
- !(5 > 3) returns false because 5 > 3 is true .
5. Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1 . That is, ++5 will return 6 .
Different types of unary operators are:
Operator | Meaning |
---|---|
: not necessary to use since numbers are positive without using it | |
: inverts the sign of an expression | |
: increments value by 1 | |
: decrements value by 1 | |
: inverts the value of a boolean |
- Increment and Decrement Operators
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1 , while -- decrease it by 1 . For example,
Here, the value of num gets increased to 6 from its initial value of 5 .
Example 5: Increment and Decrement Operators
In the above program, we have used the ++ and -- operator as prefixes (++a, --b) . We can also use these operators as postfix (a++, b++) .
There is a slight difference when these operators are used as prefix versus when they are used as a postfix.
To learn more about these operators, visit increment and decrement operators .
6. Java Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits. For example,
Here, ~ is a bitwise operator. It inverts the value of each bit ( 0 to 1 and 1 to 0 ).
The various bitwise operators present in Java are:
Operator | Description |
---|---|
Bitwise Complement | |
Left Shift | |
Right Shift | |
Unsigned Right Shift | |
Bitwise AND | |
Bitwise exclusive OR |
These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators .
Other operators
Besides these operators, there are other additional operators in Java.
The instanceof operator checks whether an object is an instanceof a particular class. For example,
Here, str is an instance of the String class. Hence, the instanceof operator returns true . To learn more, visit Java instanceof .
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,
Here's how it works.
- If the Expression is true , expression1 is assigned to the variable .
- If the Expression is false , expression2 is assigned to the variable .
Let's see an example of a ternary operator.
In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator .
Now that you know about Java operators, it's time to know about the order in which operators are evaluated. To learn more, visit Java Operator Precedence .
Table of Contents
- Introduction
- Java Arithmetic Operators
- Java Assignment Operators
- Java Relational Operators
- Java Logical Operators
- Java Unary Operators
- Java Bitwise Operators
Sorry about that.
Related Tutorials
Java Tutorial
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.
Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands , and then return a result.
As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
Operators | Precedence |
---|---|
postfix | ++ -- |
unary | -- + - ~ ! |
multiplicative | |
additive | |
shift | |
relational | |
equality | |
bitwise AND | |
bitwise exclusive OR | |
bitwise inclusive OR | |
logical AND | |
logical OR | |
ternary | |
assignment |
In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator " = " is far more common than the unsigned right shift operator " >>> ". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights
Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.
01 Career Opportunities
02 beginner, 03 intermediate, 04 questions, 05 training programs, assignment operator in java, java online course free with certificate (2024), assignment operators in java: an overview, what are the assignment operators in java, types of assignment operators in java, 1. simple assignment operator (=):, explanation, 2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):, 5. division operator (/=):, 6. modulus assignment operator (%=):, example of assignment operator in java, q1. can i use multiple assignment operators in a single statement, q2. are there any other compound assignment operators in java, q3. how many types of assignment operators, live classes schedule.
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast |
About Author
Java Assignment Operators
Java programming tutorial index.
The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign = .
In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:
Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables.
- TutorialKart
- SAP Tutorials
- Salesforce Admin
- Salesforce Developer
- Visualforce
- Informatica
- Kafka Tutorial
- Spark Tutorial
- Tomcat Tutorial
- Python Tkinter
Programming
- Bash Script
- Julia Tutorial
- CouchDB Tutorial
- MongoDB Tutorial
- PostgreSQL Tutorial
- Android Compose
- Flutter Tutorial
- Kotlin Android
Web & Server
- Selenium Java
- Java Basics
- Java Tutorial
- Java HelloWorld Program
- Java Program Structure
- Java Datatypes
- Java Variable Types
- Java Access Modifiers
- Java Operators
- Java Decision Making
- Print array
- Initialize array
- Array of integers
- Array of strings
- Array of objects
- Array of arrays
- Iterate over array
- Array For loop
- Array while loop
- Append element to array
- Check if array is empty
- Array average
- Check if array contains
- Array ForEach
- Array - Find Index of Item
- Concatenate arrays
- Find smallest number in array
- Find largest number in array
- Array reverse
- Classes and Objects
- Inheritance
- Polymorphism
- Method Overloading
- Method Overriding/
- Abstraction
- Abstract methods and classes
- Encapsulation
- Print string
- Read string from console
- Create string from Char array
- Create string from Byte array
- Concatenate two strings
- Get index of the first Occurrence of substring
- Get index of nth occurrence of substring
- Check if two strings are equal
- Check if string ends with specific suffix
- Check if string starts with specific prefix
- Check if string is blank
- Check if string is empty
- Check if string contains search substring
- Validate if string is a Phone Number
- Character Level
- Get character at specific index in string
- Get first character in string
- Get last character from string
- Transformations
- Replace first occurrence of string
- Replace all occurrences of a string
- Join strings
- Join strings in string array
- Join strings in ArrayList
- Reverse a string
- Trim string
- Split string
- Remove whitespaces in string
- Replace multiple spaces with single space
- Comparisons
- Compare strings lexicographically
- Compare String and CharSequence
- Compare String and StringBuffer
- Java Exception Handling StringIndexOutOfBoundsException
- Convert string to int
- Convert string to float
- Convert string to double
- Convert string to long
- Convert string to boolean
- Convert int to string
- Convert int to float
- Convert int to double
- Convert int to long
- Convert int to char
- Convert float to string
- Convert float to int
- Convert float to double
- Convert float to long
- Convert long to string
- Convert long to float
- Convert long to double
- Convert long to int
- Convert double to string
- Convert double to float
- Convert double to int
- Convert double to long
- Convert char to int
- Convert boolean to string
- Create a file
- Read file as string
- Write string to file
- Delete File
- Rename File
- Download File from URL
- Replace a String in File
- Filter list of files or directories
- Check if file is readable
- Check if file is writable
- Check if file is executable
- Read contents of a file line by line using BufferedReader
- Read contents of a File line by line using Stream
- Check if n is positive or negative
- Read integer from console
- Add two integers
- Count digits in number
- Largest of three numbers
- Smallest of three numbers
- Even numbers
- Odd numbers
- Reverse a number
- Prime Number
- Print All Prime Numbers
- Factors of a Number
- Check Palindrome number
- Check Palindrome string
- Swap two numbers
- Even or Odd number
- Java Classes
- ArrayList add()
- ArrayList addAll()
- ArrayList clear()
- ArrayList clone()
- ArrayList contains()
- ArrayList ensureCapacity()
- ArrayList forEach()
- ArrayList get()
- ArrayList indexOf()
- ArrayList isEmpty()
- ArrayList iterator()
- ArrayList lastIndexOf()
- ArrayList listIterator()
- ArrayList remove()
- ArrayList removeAll()
- ArrayList removeIf()
- ArrayList removeRange()
- ArrayList retainAll()
- ArrayList set()
- ArrayList size()
- ArrayList spliterator()
- ArrayList subList()
- ArrayList toArray()
- ArrayList trimToSize()
- HashMap clear()
- HashMap clone()
- HashMap compute()
- HashMap computeIfAbsent()
- HashMap computeIfPresent()
- HashMap containsKey()
- HashMap containsValue()
- HashMap entrySet()
- HashMap get()
- HashMap isEmpty()
- HashMap keySet()
- HashMap merge()
- HashMap put()
- HashMap putAll()
- HashMap remove()
- HashMap size()
- HashMap values()
- HashSet add()
- HashSet clear()
- HashSet clone()
- HashSet contains()
- HashSet isEmpty()
- HashSet iterator()
- HashSet remove()
- HashSet size()
- HashSet spliterator()
- Integer bitCount()
- Integer byteValue()
- Integer compare()
- Integer compareTo()
- Integer compareUnsigned()
- Integer decode()
- Integer divideUnsigned()
- Integer doubleValue()
- Integer equals()
- Integer floatValue()
- Integer getInteger()
- Integer hashCode()
- Integer highestOneBit()
- Integer intValue()
- Integer longValue()
- Integer lowestOneBit()
- Integer max()
- Integer min()
- Integer numberOfLeadingZeros()
- Integer numberOfTrailingZeros()
- Integer parseInt()
- Integer parseUnsignedInt()
- Integer remainderUnsigned()
- Integer reverse()
- Integer reverseBytes()
- Integer rotateLeft()
- Integer rotateRight()
- Integer shortValue()
- Integer signum()
- Integer sum()
- Integer toBinaryString()
- Integer toHexString()
- Integer toOctalString()
- Integer toString()
- Integer toUnsignedLong()
- Integer toUnsignedString()
- Integer valueOf()
- StringBuilder append()
- StringBuilder appendCodePoint()
- StringBuilder capacity()
- StringBuilder charAt()
- StringBuilder chars()
- StringBuilder codePointAt()
- StringBuilder codePointBefore()
- StringBuilder codePointCount()
- StringBuilder codePoints()
- StringBuilder delete()
- StringBuilder deleteCharAt()
- StringBuilder ensureCapacity()
- StringBuilder getChars()
- StringBuilder indexOf()
- StringBuilder insert()
- StringBuilder lastIndexOf()
- StringBuilder length()
- StringBuilder offsetByCodePoints()
- StringBuilder replace()
- StringBuilder reverse()
- StringBuilder setCharAt()
- StringBuilder setLength()
- StringBuilder subSequence()
- StringBuilder substring()
- StringBuilder toString()
- StringBuilder trimToSize()
- Arrays.asList()
- Arrays.binarySearch()
- Arrays.copyOf()
- Arrays.copyOfRange()
- Arrays.deepEquals()
- Arrays.deepToString()
- Arrays.equals()
- Arrays.fill()
- Arrays.hashCode()
- Arrays.sort()
- Arrays.toString()
- Random doubles()
- Random ints()
- Random longs()
- Random next()
- Random nextBoolean()
- Random nextBytes()
- Random nextDouble()
- Random nextFloat()
- Random nextGaussian()
- Random nextInt()
- Random nextLong()
- Random setSeed()
- Math random
- Math signum
- Math toDegrees
- Math toRadians
- Java Date & Time
- ❯ Java Tutorial
Java Assignment Operators
Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand).
The syntax of any Assignment Operator with operands is
In this tutorial, we will learn about different Assignment Operators available in Java programming language and go through each of these Assignment Operations in detail, with the help of examples.
Operator Symbol – Example – Description
The following table specifies symbol, example, and description for each of the Assignment Operator in Java.
AssignmentOperation | Operator Symbol | Example | Description |
---|---|---|---|
Simple Assignment | = | x = 2 | Assign x with 2. |
Addition Assignment | += | x += 3 | Add 3 to the value of x and assign the result to x. |
Subtraction Assignment | -= | x -= 3 | Subtract 3 from x and assign the result to x. |
Multiplication Assignment | *= | x *= 3 | Multiply x with 3 and assign the result to x. |
Division Assignment | /= | x /= 3 | Divide x with 3 and assign the quotient to x. |
Remainder Assignment | %= | x %= 3 | Divide x with 3 and assign the remainder to x. |
Bitwise AND Assignment | &= | x &= 3 | Perform x & 3 and assign the result to x. |
Bitwise OR Assignment | |= | x |= 3 | Perform x | 3 and assign the result to x. |
Bitwise-exclusive-OR Assignment | ^= | x ^= 3 | Perform x ^ 3 and assign the result to x. |
Left-shift Assignment | <<= | x <<= 3 | Left-shift the value of x by 3 places and assign the result to x. |
Right-shift Assignment | >>= | x >>= 3 | Right-shift the value of x by 3 places and assign the result to x. |
Simple Assignment
In the following example, we assign a value of 2 to x using Simple Assignment Operator.
Addition Assignment
In the following example, we add 3 to x and assign the result to x using Addition Assignment Operator.
Subtraction Assignment
In the following example, we subtract 3 from x and assign the result to x using Subtraction Assignment Operator.
Multiplication Assignment
In the following example, we multiply 3 to x and assign the result to x using Multiplication Assignment Operator.
Division Assignment
In the following example, we divide x by 3 and assign the quotient to x using Division Assignment Operator.
Remainder Assignment
In the following example, we divide x by 3 and assign the remainder to x using Remainder Assignment Operator.
Bitwise AND Assignment
In the following example, we do bitwise AND operation between x and 3 and assign the result to x using Bitwise AND Assignment Operator.
Bitwise OR Assignment
In the following example, we do bitwise OR operation between x and 3 and assign the result to x using Bitwise OR Assignment Operator.
Bitwise XOR Assignment
In the following example, we do bitwise XOR operation between x and 3 and assign the result to x using Bitwise XOR Assignment Operator.
Left-shift Assignment
In the following example, we left-shift x by 3 places and assign the result to x using Left-shift Assignment Operator.
Right-shift Assignment
In the following example, we right-shift x by 3 places and assign the result to x using Right-shift Assignment Operator.
In this Java Tutorial , we learned what Assignment Operators are, and how to use them in Java programs, with the help of examples.
Popular Courses by TutorialKart
App developement, web development, online tools.
- Java Operators
Last updated: January 8, 2024
Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.
Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.
Write code that works the way you meant it to:
>> CodiumAI. Meaningful Code Tests for Busy Devs
Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.
To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).
These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:
Improve Java application performance with CRaC support
Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.
Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.
Try a 14-Day Free Trial of Orkes Conductor today.
Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.
Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.
To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .
And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .
Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.
Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.
Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.
The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:
>> Become an efficient full-stack developer with Jmix
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .
The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
>> Take a look at DBSchema
Do JSON right with Jackson
Download the E-book
Get the most out of the Apache HTTP Client
Get Started with Apache Maven:
Working on getting your persistence layer right with Spring?
Explore the eBook
Building a REST API with Spring?
We’ve opened a new Java/Spring Course Team Lead position. Part-time and entirely remote, of course: Read More
Get started with Spring and Spring Boot, through the Learn Spring course:
Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
>> The New “REST With Spring Boot”
Get started with Spring and Spring Boot, through the reference Learn Spring course:
>> LEARN SPRING
The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .
AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.
Simplify Your Coding Journey with Machinet AI :
>> Install Machinet AI in your IntelliJ
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .
You can explore the course here:
>> Learn Spring Security
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .
Get started with Spring Data JPA through the guided reference course:
>> CHECK OUT THE COURSE
1. Overview
Operators are a fundamental building block of any programming language. We use operators to perform operations on values and variables.
Java provides many groups of operators. They are categorized by their functionalities.
In this tutorial, we’ll walk through all Java operators to understand their functionalities and how to use them.
2. Arithmetic Operators
We use arithmetic operators to perform simple mathematical operations. We should note that arithmetic operators only work with primitive number types and their boxed types , such as int and Integer .
Next, let’s see what operators we have in the arithmetic operator group.
2.1. The Addition Operator
The addition operator (+) allows us to add two values or concatenate two strings:
2.2. The Subtraction Operator
Usually, we use the subtraction operator (-) to subtract one value from another:
2.3. The Multiplication Operator
The multiplication operator (*) is used to multiply two values or variables:
2.4. The Division Operator
The division operator (/) allows us to divide the left-hand value by the right-hand one:
When we use the division operator on two integer values ( byte , short , int , and long ), we should note that the result is the quotient value. The remainder is not included .
As the example above shows, if we calculate 15 / 2 , the quotient is 7, and the remainder is 1 . Therefore, we have 15 / 2 = 7 .
2.5. The Modulo Operator
We can get the quotient using the division operator. However, if we just want to get the remainder of a division calculation, we can use the modulo operator (%):
3. Unary Operators
As the name implies, unary operators only require one single operand . For example, we usually use unary operators to increment, decrement, or negate a variable or value.
Now, let’s see the details of unary operators in Java.
3.1. The Unary Plus Operator
The unary plus operator (+) indicates a positive value. If the number is positive, we can omit the ‘+’ operator:
3.2. The Unary Minus Operator
Opposite to the unary plus operator, the unary minus operator (-) negates a value or an expression:
3.3. The Logical Complement Operator
The logical complement operator (!) is also known as the “NOT” operator . We can use it to invert the value of a boolean variable or value:
3.4. The Increment Operator
The increment operator (++) allows us to increase the value of a variable by 1:
3.5. The Decrement Opeartor
The decrement operator (–) does the opposite of the increment operator. It decreases the value of a variable by 1:
We should keep in mind that the increment and decrement operators can only be used on a variable . For example, “ int a = 5; a++; ” is fine. However, the expression “ 5++ ” won’t be compiled.
4. Relational Operators
Relational operators can be called “comparison operators” as well. Basically, we use these operators to compare two values or variables.
4.1. The “Equal To” Operator
We use the “equal to” operator (==) to compare the values on both sides. If they’re equal, the operation returns true :
The “equal to” operator is pretty straightforward. On the other hand, the Object class has provided the equals() method. As the Object class is the superclass of all Java classes, all Java objects can use the equals() method to compare each other.
When we want to compare two objects – for instance, when we compare Long objects or compare String s – we should choose between the comparison method from the equals() method and that of the “equal to” operator wisely .
4.2. The “Not Equal To” Operator
The “not equal to” operator (!=) does the opposite of the ‘==’ operator. If the values on both sides are not equal, the operation returns true :
4.3. The “Greater Than” Operator
When we compare two values with the “greater than” operator (>), it returns true if the value on the left-hand side is greater than the value on the right-hand side:
4.4. The “Greater Than or Equal To” Operator
The “greater than or equal to” operator (>=) compares the values on both sides and returns true if the left-hand side operand is greater than or equal to the right-hand side operand:
4.5. The “Less Than” Operator
The “less than” operator (<) compares two values on both sides and returns true if the value on the left-hand side is less than the value on the right-hand side:
4.6. The “Less Than or Equal To” Operator
Similarly, the “less than or equal to” operator (<=) compares the values on both sides and returns true if the left-hand side operand is less than or equal to the right-hand side:
5. Logical Operators
We have two logical operators in Java: the logical AND and OR operators. Basically, their function is pretty similar to the AND gate and the OR gate in digital electronics.
Usually, we use a logical operator with two operands, which are variables or expressions that can be evaluated as boolean .
Next, let’s take a closer look at them.
5.1. The Logical AND Operator
The logical AND operator ( && ) returns true only if both operands are true :
5.2. The Logical OR Operator
Unlike the ‘ && ‘ operator, the logical OR operator ( || ) returns true if at least one operand is true :
We should note that the logical OR operator has the short-circuiting effect : It returns true as soon as one of the operands is evaluated as true, without evaluating the remaining operands.
6. Ternary Operator
A ternary operator is a short form of the if-then-else statement. It has the name ternary as it has three operands. First, let’s have a look at the standard if-then-else statement syntax:
We can convert the above if-then-else statement into a compact version using the ternary operator:
Let’s look at its syntax:
Next, let’s understand how the ternary operator works through a simple example:
7. Bitwise and Bit Shift Operators
As the article “ Java bitwise operators ” covers the details of bitwise and bit shift operators, we’ll briefly summarize these operators in this tutorial.
7.1. The Bitwise AND Operator
The bitwise AND operator (&) returns the bit-by-bit AND of input values:
7.2. The Bitwise OR Operator
The bitwise OR operator (|) returns the bit-by-bit OR of input values:
7.3. The Bitwise XOR Operator
The bitwise XOR (exclusive OR) operator (^) returns the bit-by-bit XOR of input values:
7.4. The Bitwise Complement Operator
The bitwise complement operator (~) is a unary operator. It returns the value’s complement representation, which inverts all bits from the input value:
7.5. The Left Shift Operator
Shift operators shift the bits to the left or right by the given number of times.
The left shift operator (<<) shifts the bits to the left by the number of times defined by the right-hand side operand. After the left shift, the empty space in the right is filled with 0.
Next, let’s left shift the number 12 twice:
n << x has the same effect of multiplying the number n with x power of two.
7.6. The Signed Right Shift Operator
The signed right shift operator (>>) shifts the bits to the right by the number of times defined by the right-hand side operand and fills 0 on voids left as a result.
We should note that the leftmost position after the shifting depends on the sign extension .
Next, let’s do “signed right shift” twice on the numbers 12 and -12 to see the difference:
As the second example above shows, if the number is negative, the leftmost position after each shift will be set by the sign extension.
n >> x has the same effect of dividing the number n by x power of two.
7.7. The Unsigned Right Shift Operator
The unsigned right shift operator (>>>) works in a similar way as the ‘>>’ operator. The only difference is that after a shift, the leftmost bit is set to 0 .
Next, let’s unsigned right shift twice on the numbers 12 and -12 to see the difference:
As we can see in the second example above, the >>> operator fills voids on the left with 0 irrespective of whether the number is positive or negative .
8. The “ instanceof ” Operator
Sometimes, when we have an object, we would like to test if it’s an instance of a given type . The “ instanceof ” operator can help us to do it:
9. Assignment Operators
We use assignment operators to assign values to variables. Next, let’s see which assignment operators we can use in Java.
9.1. The Simple Assignment Operator
The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we’ve used it many times in previous examples. It assigns the value on its right to the operand on its left:
9.2. Compound Assignments
We’ve learned arithmetic operators. We can combine the arithmetic operators with the simple assignment operator to create compound assignments.
For example, we can write “ a = a + 5 ” in a compound way: “ a += 5 “.
Finally, let’s walk through all supported compound assignments in Java through examples:
10. Conclusion
Java provides many groups of operators for different functionalities. In this article, we’ve passed through the operators in Java.
Looking for the ideal Linux distro for running modern Spring apps in the cloud?
Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.
This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.
Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:
>> Try Alpaquita Containers now.
Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:
Basically, write code that works the way you meant it to.
AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.
- Change Password
Java Assignment Operators
lorem ipsum is dolor sit amet lorem ipsum is dolor sit ametlorem ipsum is dolor sit amet lorem ipsum is dolor sit amet lorem ipsum is dolor sit amet lorem ipsum is dolor sit amet
You might be interested in
- Basics of Java
- ➤ Java Introduction
- ➤ History of Java
- ➤ Getting started with Java
- ➤ What is Path and Classpath
- ➤ Checking Java installation and Version
- ➤ Syntax in Java
- ➤ My First Java Program
- ➤ Basic terms in Java Program
- ➤ Runtime and Compile time
- ➤ What is Bytecode
- ➤ Features of Java
- ➤ What is JDK JRE and JVM
- ➤ Basic Program Examples
- Variables and Data Types
- ➤ What is Variable
- ➤ Types of Java Variables
- ➤ Naming conventions for Identifiers
- ➤ Data Type in Java
- ➤ Mathematical operators in Java
- ➤ Assignment operator in Java
- ➤ Arithmetic operators in Java
- ➤ Unary operators in Java
- ➤ Conditional and Relational Operators
- ➤ Bitwise and Bit Shift Operators
- ➤ Operator Precedence
- ➤ Overflow Underflow Widening Narrowing
- ➤ Variable and Data Type Programs
- Control flow Statements
- ➤ Java if and if else Statement
- ➤ else if and nested if else Statement
- ➤ Java for Loop
- ➤ Java while and do-while Loop
- ➤ Nested loops
- ➤ Java break Statement
- ➤ Java continue and return Statement
- ➤ Java switch Statement
- ➤ Control Flow Program Examples
- Array and String in Java
- ➤ Array in Java
- ➤ Multi-Dimensional Arrays
- ➤ for-each loop in java
- ➤ Java String
- ➤ Useful Methods of String Class
- ➤ StringBuffer and StringBuilder
- ➤ Array and String Program Examples
- Classes and Objects
- ➤ Classes in Java
- ➤ Objects in Java
- ➤ Methods in Java
- ➤ Constructors in Java
- ➤ static keyword in Java
- ➤ Call By Value
- ➤ Inner/nested classes in Java
- ➤ Wrapper Classes
- ➤ Enum in Java
- ➤ Initializer blocks
- ➤ Method Chaining and Recursion
- Packages and Interfaces
- ➤ What is package
- ➤ Sub packages in java
- ➤ built-in packages in java
- ➤ Import packages
- ➤ Access modifiers
- ➤ Interfaces in Java
- ➤ Key points about Interfaces
- ➤ New features in Interfaces
- ➤ Nested Interfaces
- ➤ Structure of Java Program
- OOPS Concepts
- ➤ What is OOPS
- ➤ Inheritance in Java
- ➤ Inheritance types in Java
- ➤ Abstraction in Java
- ➤ Encapsulation in Java
- ➤ Polymorphism in Java
- ➤ Runtime and Compile-time Polymorphism
- ➤ Method Overloading
- ➤ Method Overriding
- ➤ Overloading and Overriding Differences
- ➤ Overriding using Covariant Return Type
- ➤ this keyword in Java
- ➤ super keyword in Java
- ➤ final keyword in Java
Assignment Operator in Java with Example
Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types :
- Assignment operator or simple assignment operator
- Compound assignment operators
What is assignment operator in java
The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand(variable) on its left side. For example :
The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be in the form of a constant value, a variable name, an expression, a method call returning a compatible value or a combination of these.
The value at right side of assignment operator must be compatible with the data type of left side variable, otherwise compiler will throw compilation error. Following are incorrect assignment :
Another important thing about assignment operator is that, it is evaluated from right to left . If there is an expression at right side of assignment operator, it is evaluated first then the resulted value is assigned in left side variable.
Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted value( 60 ) is assigned into x . Similarly in statement a = b = c , first the value of c which is 30 is assigned into b and then the value of b which is now 30 is assigned into a .
The variable at left side of an assignment operator can also be a non-primitive variable. For example if we have a class MyFirstProgram , we can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.
Is == an assignment operator ?
No , it's not an assignment operator, it's a relational operator used to compare two values.
Is assignment operator a binary operator
Yes , as it requires two operands.
Assignment operator program in Java
a = 2 b = 2 c = 4 d = 4 e = false
Java compound assignment operators
The assignment operator can be mixed or compound with other operators like addition, subtraction, multiplication etc. We call such assignment operators as compound assignment operator. For example :
Here the statement a += 10; is the short version of a = a + 10; the operator += is basically addition compound assignment operator. Similarly b *= 5; is short version of b = b * 5; the operator *= is multiplication compound assignment operator. The compound assignment can be in more complex form as well, like below :
List of all assignment operators in Java
The table below shows the list of all possible assignment(simple and compound) operators in java. Consider a is an integer variable for this table.
Operator | Example | Same As |
---|---|---|
= | a = 10 | a = 10 |
+= | a += 5 | a = a + 5 |
-= | a -= 3 | a = a - 3 |
*= | a *= 6 | a = a * 6 |
/= | a /= 5 | a = a / 5 |
%= | a %= 7 | a = a % 7 |
&= | a &= 3 | a = a & 3 |
|= | a |= 3 | a = a | 3 |
^= | a ^= 2 | a = a ^ 2 |
>>= | a >>= 3 | a = a >> 3 |
>>>= | a >>>= 3 | a = a >>> 3 |
<<= | a <<= 2 | a = a << 2 |
How many assignment operators are there in Java ?
Including simple and compound assignment we have total 12 assignment operators in java as given in above table.
What is shorthand operator in Java ?
Shorthand operators are nothing new they are just a shorter way to write something that is already available in java language. For example the code a += 5 is shorter way to write a = a + 5 , so += is a shorthand operator. In java all the compound assignment operator(given above) and the increment/decrement operators are basically shorthand operators.
Compound assignment operator program in Java
a = 20 b = 80 c = 30 s = 64 s2 = 110 b2 = 15
What is the difference between += and =+ in Java?
An expression a += 1 will result as a = a + 1 while the expression a =+ 1 will result as a = +1 . The correct compound statement is += , not =+ , so do not use the later one.
Java Tutorial
Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.
IMAGES
COMMENTS
Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.
Java Comparison Operators. Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If ...
To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side. Example: int x = 10; int x = 10; In the above example, the variable x is assigned the value 10.
The Simple Assignment Operator. One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left: ... The Java programming language provides operators that perform addition, subtraction, multiplication, and ...
Java Assignment Operators. Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Here, = is the assignment operator. It assigns the value on its right to the variable on its left. ... 6. Java Bitwise Operators. Bitwise operators in Java are used to perform operations on individual bits. For example,
Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest ...
Assignment Operators in Java: An Overview. We already discussed the Types of Operators in the previous tutorial Java. In this Java tutorial, we will delve into the different types of assignment operators in Java, and their syntax, and provide examples for better understanding.Because Java is a flexible and widely used programming language. Assignment operators play a crucial role in ...
As you can see, In the above example, we are using assignment operator in if statement. We did a comparison of value 10 to an assignment operator which resulted in a 'true' output because the return of assignment operator is the value of left operand. Recommended Posts. Arithmetic Operators in Java with Examples; Unary Operators in Java ...
Java Assignment Operators. The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =. In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to ...
Java assignment operators are classified into two types: simple and compound. The Simple assignment operator is the equals ( =) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...
Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand). The syntax of any Assignment Operator with operands is. operand1 operator_symbol operand2. In this tutorial, we will learn about different Assignment Operators available in Java programming language ...
There are mainly two types of assignment operators in Java, which are as follows: Simple Assignment Operator ; We use the simple assignment operator with the "=" sign, where the left side consists of an operand and the right side is a value. The value of the operand on the right side must be of the same data type defined on the left side.
Assignment Operators. Assignment operators help you set or change the value of a variable. Think of them as shortcuts for common operations. The basic assignment operator is =. For example: int length = 15; This sets the value of length to 15. But there are also compound assignment operators that combine an operation with assignment: +=: Add ...
The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples. It assigns the value on its right to the operand on its left: int seven = 7; 9.2. Compound Assignments
Java Assignment operator (=) The assignment operator in java is used to assign (or to store) a value to a variable. Example of assignment operator. a = 18; It assigns the value 18 to the variable a. b = 8; It assigns the value 8 to the variable b. a =b; It assigns the value of variable b to variable a.
The general format of the assignment operator is: variable = value;. In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement.For example, instead of a = a+5, we can write a += 5. +=, for adding the left operand with the right operand and then assigning it to the variable on the left.
The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example : int a = 10; // value 10 is assigned in variable a double d = 20.25; // value 20.25 is assigned in variable d char c = 'A'; // Character A is assigned in variable c. a = 20 ...
Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...
5. Because your sec statement will be evaluated as x = x * (2+5); x = 10; x *= 2+5; x = x * (2+5); While in the first case, its normal left to right precedence.Java guarantees that all operands of an operator are fully evaluated before the operator is applied. A compound assignment operator has the following syntax: <variable> <op>= <expression>.
The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results ...
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2.
a |= b; is the same as. a = (a | b); It calculates the bitwise OR of the two operands, and assigns the result to the left operand. To explain your example code: for (String search : textSearch.getValue()) matches |= field.contains(search); I presume matches is a boolean; this means that the bitwise operators behave the same as logical operators.
The |= is a compound assignment operator ( JLS 15.26.2) for the boolean logical operator | ( JLS 15.22.2 ); not to be confused with the conditional-or || ( JLS 15.24 ). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively. In other words, for boolean b1, b2, these two are ...
Operator 6: Less than or equal to (<=) ... Java Assignment Operators with Examples. Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. ...
The overloaded assignment operator would behave differently from the built-in assignment operator, which could confuse others of our class. Conclusion In C++, when overloading the assignment operator, we must return a reference to the current object ( *this ) as it allows for assignment chaining, maintains consistency with built-in types, and ...