Assignment operators (most popular):  =   +=   -=   *=   /=   %=

Although we discuss them not the first, these are the most often used operators, especially the = simple assignment operator, which just assigns a value to a variable (also phrased as assigns a variable a value). We have seen examples of simple assignment usage many times already.

The only possible caveat in using simple assignment is when the type of the variable on the left is not the same as the value or variable type on the right. The difference in types can lead to the narrowing or widening of the value in the case of primitive types, or to boxing or unboxing when one type is a primitive type and another type is a reference type. We will discuss such assignments in the Widening and narrowing conversion of primitive types and Boxing and unboxing between a primitive and reference types sections later.

The rest of the assignment operators (+=  -=  *=  /=  %=are called compound assignment operators: 

The operation x = x + x % 2; is based on the operator precedence rules, which we are going to discuss in the Operator precedence and evaluation order of operands section later. According to these rules, the % operator (modulus) is executed first, then the + operator (addition), and then the result is assigned to the left-hand operand variable x. Here is the demonstration code:

int x = 1;
x += 2;
System.out.println(x); //prints: 3
x -= 1;
System.out.println(x); //prints: 2
x *= 2;
System.out.println(x); //prints: 4
x /= 2;
System.out.println(x); //prints: 2
x %= 2;
System.out.println(x); //prints: 0

Again, every time we encounter integer division, we had better convert it to a float or double division, then round it if necessary or just cast it to an integer. In our example, we do not have any loss of the fractional part. But if we do not know the value of x, the code may look as follows:

x = 11;
double y = x;
y /= 3; //That's the operation we wanted to do on x
       
System.out.println(y); //prints: 3.6666666666666665
x = (int)y;
System.out.println(x); //prints: 3

//or, if we need to round up the result:
double
d = Math.round(y); //prints: 4.0
System.out.println(d);
x = (int) d;
System.out.println(x); //prints: 4

In this code, we have assumed that we do not know the value of x, so we switched to the double type to avoid the loss of the fractional part. After the result is calculated, we either cast it to int (and the fractional part is lost) or round it to the nearest integer.

In this simple division, we could lose the fractional part and get 3, even without converting to the double type. But in real-life calculations, the formula is usually not that simple, so one might never know exactly where the integer division might happen. That's why it is a good practice just to convert the values to float and double before starting the calculations.