Java Assignment Operators

The Java assignment operators are used to assign a new value to the variables, properties or events. Assignment operators can also be used for logical operations like bitwise logical operations or operations on integral and Boolean operands.


A list of assignment operators used in Java language:

S.No. Operators Example Description
1. = c = a + b will assign value of a + b into c The simple assignment operator is used to take values from right side operands and set to left side operand.
2. += c += a is equivalent to c = c + a The add AND assignnment operator is used to add right operand to the left operand and assign the result to left operand.
3. -= c -= a is equivalent to c = c - a The subtract AND assignment operator is used to subtract right operand from the left operand and assign the result to left operand.
4. *= c *= a is equivalent to c = c * a The multiple AND assignment operator is used to multiply right operand with the left operand and assign the result to left operand.
5. /= c /= a is equivalent to c = c / a The divide AND assignment operator is used to divide left operand with the right operand and assign the result to left operand.
6. %= c %= a is equivalent to c = c % a The modulus AND assignment operator is used to take modulus using two operands and assign the result to left operand.
7. <<= c <<= 2 is same as c = c << 2 It is Left shift AND assignment operator.
8. >>= c &= 2 is same as c = c & 2 It is Bitwise AND assignment operator.
9. &= c >>= 2 is same as c = c >> 2 It is Right shift AND assignment operator.
10. ^= c ^= 2 is same as c = c ^ 2 It is Bitwise exclusive OR and assignment operator.
11. |= c |= 2 is same as c = c | 2 It is Bitwise inclusive OR and assignment operator.

Assignment Operators Example

The following program is a simple example that demonstrates the assignment operators.


 /**
 * 
 * @author JavaTportal Corporation
 *
 */
public class AssignmentOperatorsExample {

		public static void main(String args[]) {
		int a = 20;
		int b = 30;
		int c = 0;

		c = a + b;
		System.out.println("c = a + b = " + c);

		c += a;
		System.out.println("c += a  = " + c);

		c -= a;
		System.out.println("c -= a = " + c);

		c *= a;
		System.out.println("c *= a = " + c);

		a = 10;
		c = 15;
		c /= a;
		System.out.println("c /= a = " + c);

		a = 10;
		c = 15;
		c %= a;
		System.out.println("c %= a  = " + c);

		c <<= 2;
		System.out.println("c <<= 2 = " + c);

		c >>= 2;
		System.out.println("c >>= 2 = " + c);

		c >>= 2;
		System.out.println("c >>= 2 = " + c);

		c &= a;
		System.out.println("c &= a  = " + c);

		c ^= a;
		System.out.println("c ^= a   = " + c);

		c |= a;
		System.out.println("c |= a   = " + c);
	}
}

Output

c = a + b = 50
c += a  = 70
c -= a = 50
c *= a = 1000
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10