Java - Assignment Operators With Examples
Java - Assignment Operators With Examples
Example 1
In this example, we're creating three variables a,b and c and using assignment operators. We've
performed simple assignment, addition AND assignment, subtraction AND assignment and
multiplication AND assignment operations and printed the results.
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 );
}
}
Output
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
Example 2
In this example, we're creating two variables a and c and using assignment operators. We've
performed Divide AND assignment, Multiply AND assignment, Modulus AND assignment, bitwise
exclusive OR AND assignment, OR AND assignment operations and printed the results.
c /= a ;
System.out.println("c /= a = " + c );
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
c = 15;
c &= a ;
System.out.println("c &= a = " + c );
c = 15;
c ^= a ;
System.out.println("c ^= a = " + c );
c = 15;
c |= a ;
System.out.println("c |= a = " + c );
}
}
Output
c /= a = 1
c %= a = 5
c &= a = 10
c ^= a = 5
c |= a = 15
Example 3
In this example, we're creating two variables a and c and using assignment operators. We've
performed Left shift AND assignment, Right shift AND assignment, operations and printed the
results.
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c = 15;
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
}
}
Output
c <<= 2 = 0
c >>= 2 = 3