Java Assignment Operators and Examples

In Java (like other programming languages) assignment operators are used to assign values to a variable. In this tutorial, all of the assignment operators are described with examples.

Java Assignment Operators and Examples

Example 1: = Assignment Operator

int a = 5;
char c = 'v';
String text = "Hello";

 

Example 2: "+=", "-=", "*=", "/=" and "%=" Assignment Operators

int a = 10;
System.out.println(a); //10

a+=1; //a=a+1
System.out.println(a); //11

a-=5; //a=a-5
System.out.println(a); //6

a*=3; //a=a*3
System.out.println(a); //18

a/=3; //a=a/3
System.out.println(a); //6

a%=5; //a=a%3
System.out.println(a); //1

 

Example 3: Let's mix it up

int a = 10;
int b = 5;
int c = 3;

a *= 2; //a=20
System.out.println(a);

b = a % c; //b=2
System.out.println(b);

c = a; //c=20;
System.out.println(c);

 

Example 4: "<<=",  ">>=",  "&=",  "^=" and "|=" Assignment Operators.

int someInteger = 8;
int someOtherInteger = 2;

someInteger <<= 3;
System.out.println(someInteger ); //64

someInteger >>= 2;
System.out.println(someInteger ); //16

someInteger >>= 3;
System.out.println(someInteger ); //2

someInteger &= someOtherInteger;
System.out.println(someInteger ); //2

someInteger ^= someOtherInteger;
System.out.println(someInteger ); //0

someInteger |= someOtherInteger;
System.out.println(someInteger ); //2