Java Programming Tutorial Index

Java Fundamentals

Java provides some special Compound Assignment Operators, also known as Shorthand Assignment Operators. It's called shorthand because it provides a short way to assign an expression to a variable.



This operator can be used to connect Arithmetic operator with an Assignment operator.

For example, you write a statement:

a = a+6;

In Java, you can also write the above statement like this:

a += 6;

There are various compound assignment operators used in Java:

Operator Meaning
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns
<<= Binary Left Shift  and assigns
>>= Binary Right Shift and assigns
>>>= Shift right zero fill and assigns
&= Binary AND assigns
^= Binary exclusive OR and assigns
|= Binary inclusive OR and assigns

While writing a program, Shorthand Operators saves some time by changing the large forms into shorts; Also, these operators are implemented efficiently by Java runtime system compared to their equivalent large forms.

Programs to Show How Assignment Operators Works

Example:

//Programs to Show How Assignment and Compound Assignment Operators Works
public class assignmntop {
 public static void main(String[] args) {

  //Simple assigns
  byte bt = 24;
  System.out.println("bt: " + bt);
  
  //Increments then assigns
  bt += 10;
  System.out.println("bt: " + bt);
  
  //Decrements then assigns
  bt -= 2;
  System.out.println("bt: " + bt);
  
  //Multiplies then assigns
  bt *= 2;
  System.out.println("bt: " + bt);
  
  //Divides then assigns
  bt /= 2;
  System.out.println("bt: " + bt);
  
  //Modulus then assigns
  bt %= 7;
  System.out.println("bt: " + bt);
  
  //Binary Left Shift  and assigns
  bt <<= 3;
  System.out.println("bt: " + bt);

  //Binary Right Shift and assigns
  bt >>= 4;
  System.out.println("bt: " + bt);
  
  //Shift right zero fill and assigns
  bt >>>= 1;
  System.out.println("bt: " + bt);
  
  //Binary AND assigns
  bt &= 4;
  System.out.println("bt: " + bt);
  
  //Binary exclusive OR and assigns
  bt ^= 4;
  System.out.println("bt: " + bt);
  
  //Binary inclusive OR and assigns
  bt |= 4;
  System.out.println("bt: " + bt);
 }
}

Output:

bt: 24
bt: 34
bt: 32
bt: 64
bt: 32
bt: 4
bt: 32
bt: 2
bt: 1
bt: 0
bt: 4
bt: 4


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram