In this tutorial you will learn about the Java Assignment Operators and its application with practical example.
Java Assignment Operators
Assignment operators are used to assigning value to a variable, you can assign a variable value or the result of an arithmetical expression. In many cases, the assignment operators can be combined with other operators to build a shorthand version of an assignment statement known as a Compound Statement. For example, instead of a = a+5, we can write a += 5.
Operator | Description | Expression |
---|---|---|
= |
Assignment Operator |
a=b |
+= |
add and assign |
a+=b is equivalent to a=a+b |
-= |
subtract and assign |
a-=b is equivalent to a=a-b |
*= |
multiply and assign |
a*=b is equivalent to a=a*b |
/= |
divide and assign |
a/=b is equivalent to a=a/b |
%= |
mod and assign |
a%=b is equivalent to a=a%b |
<<= |
Left shift AND assign |
a<<=5 is equivalent to a=a<<5 |
>>= |
Right shift AND assign |
a>>=5 is equivalent to a=a>>5 |
&= |
Bitwise AND assign |
a&=5 is equivalent to a=a&5 |
^= |
Bitwise exclusive OR and assign |
a^=5 is equivalent to a=a^5 |
|= |
Bitwise inclusive OR and assign |
a|=5 is equivalent to a=a|5 |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Main { public static void main(String[] args) { int a= 30; int b= 5; System.out.println("W3Adda - Java Assignment Operators"); a+=b; System.out.println("a+=b :"+a); a-=b; System.out.println("a-=b :"+a); a*=b; System.out.println("a*=b :"+a); a/=b; System.out.println("a/=b :"+a); a%=b; System.out.println("a%=b :"+a); } } |
Output:-