Classes/Objects  «Prev  Next»


Lesson 7Assignment operators
ObjectiveDescribe important points about assignment operators.

Java SE Assignment Operators

When using assignment operators in Java SE 22, a Java developer should pay close attention to the following important points, especially to avoid subtle bugs and ensure code clarity:
  1. Understand the Difference Between = and ==
    • = is the assignment operator: int x = 5;
    • == is the equality comparison operator: if (x == 5) { ... }
    • Common mistake: Accidentally using = in a conditional:
                if (x = 5) // COMPILE ERROR: incompatible types
              
  2. Compound Assignment Operators Modify and Assign
    Java provides compound assignment operators that combine arithmetic or bitwise operations with assignment:
    x += y;  // equivalent to x = x + y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x &= y;
    x |= y;
    x ^= y;
    x <<= y;
    x >>= y;
    x >>>= y;
    
    • These are type-safe (handle implicit casting), but still require caution.
  3. Be Mindful of Type Conversion
    • Compound assignment operators perform implicit casting:
      byte a = 10;
      a += 5;  // OK, implicit cast to byte
      a = a + 5;  // ERROR: Type mismatch, needs explicit cast to byte
      
    • With simple = assignments, the right-hand expression must match or be explicitly cast.
  4. Assignment is an Expression with a Return Value
    • You can chain assignments, but do so with care:
                int x, y, z;
                x = y = z = 10;  // all variables now equal 10
              
    • While valid, this can hurt readability.

  5. Assignments Inside Conditions Are Risky
    • Assignments return a value, so it's syntactically legal to write:
                if ((x = computeValue()) > 0) { ... }
              
    • But this may be confusing to readers; prefer separating assignment from the condition unless clarity is ensured.
  6. Assignment vs Reference Copy
    • For objects, assignment copies the reference, not the object itself:
                MyObject a = new MyObject();
                MyObject b = a;  // b refers to the same object
              
    • Changes via b will reflect in a—understand reference semantics.
  7. Order of Evaluation in Assignments
    • In compound or nested assignments, evaluation follows right-to-left:
                int x, y;
                x = y = 20; // y is assigned 20, then x is assigned y's value
              
  8. Avoid Obfuscation
    • Assignment within expressions (especially ternaries or loops) may obscure logic:
                while ((line = reader.readLine()) != null) { ... }  // common and acceptable
              
    • This is idiomatic but should be used only when clarity is maintained.

What is an Assignment Operator in Java

An assignment operator is a binary operator that modifies, or assigns, the variable on the left-hand side of the operator, with the result of the value on the right-hand side of the equation. The simplest assignment operator is the = assignment, which you have seen already:
int x = 1;

This statement assigns x the value of 1. Java will automatically promote from smaller to larger data types, as we saw in the previous section on arithmetic operators, but it will throw a compiler exception if it detects you are trying to convert from larger to smaller data types. Let us return to some examples similar to what you saw in Chapter 1 in order to show how casting can resolve these issues:
int x = 1.0; // DOES NOT COMPILE
short y = 1921222; // DOES NOT COMPILE
int z = 9f; // DOES NOT COMPILE
long t = 192301398193810323; // DOES NOT COMPILE

The first statement does not compile because you are trying to assign a double 1.0 to an integer value. Even though the value is a mathematic integer, by adding .0, you are instructing the compiler to treat it as a double. The second statement does not compile because the literal value 1921222 is outside the range of short and the compiler detects this. The third statement does not compile because of the f added to the end of the number that instructs the compiler to treat the number as floating-point value. Finally, the last statement does not compile because Java interprets the literal as an int and notices that the value is larger than int allows. The literal would need a postfix L to be considered a long.


Casting and Assignment of Java Operators

Java provides the simple assignment operator = and operators that combine binary operations with the assignment operator. Examples of the latter are += and *=. The assignment operators that perform binary arithmetic cast their result to the type of the left operand.
For example, if ch is of type char,
 
ch += 8
,
assigns (char) (ch+8) to ch. However, the simple assignment = operator does not perform an implicit cast when used with primitive numeric types.[1] When the simple assignment operator is used with object references, a few conditions must be met to avoid compilation errors:
  1. If the type of the left operand is a class C, then the type of the right operand must be a subclass of C or the null value.
  2. If the type of the left operand is an interface I, then the type of the right operand must be a subinterface of I, a class that implements I, or the null value.

If the above conditions do not hold, you should use an explicit cast to avoid compilation errors.
  • The value returned by an assignment
    The assignment operator, like other Java operators, returns a value. This value is the value assigned to the left operand.
    However, unlike other operators, the assignment operator is right associative. This means that operations of the form a=b=c are evaluated as a=(b=c) instead of the left associative (a=b)=c.

The assignment program provides an example of using associativity and the value returned by the assignment operator.

Java Assignment Program Example

The Assignment program illustrates the right associativity of the assignment operator. This program results in the values 8, 7, and 5 being assigned to the i, j, and k variables. The heart of the program's processing is the evaluation of the statement:
i += j += k = ++i + ++j;

Since += and = are right-associative, this statement is evaluated as follows:
i += (j += (k = (++i + ++j))); 
This results in 5 being assigned to k. The value of 5 is then added to j giving it a value of 7. Finally 7 is added to i resulting in a value of 8.

Java Class Assignment
public class Assignment {

  public static void main(String[] args) {
    int i = 1;
    int j = 2;
    int k = 3;
    i += j += k = ++i + ++j;    
    System.out.println(i);
    System.out.println(j);
    System.out.println(k);
  }
}


Java Assignment Operators

The assignment operators that you need to know for the exam are =, +=, -=, *=, and /=. The simple assignment operator, =, is the most frequently used operator. It is used to initialize variables with values and to reassign new values to them. The +=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication and division with assignment. The += operator can be read as "first add and then assign," and -= can be read as "first subtract and then assign."
Similarly, *= can be read as "first multiply and then assign" and /= can be read as "first divide and then assign."
If you apply these operators to two operands, a and b, they can be represented as follows:
a -= b is equal to a = a - b
a += b is equal to a = a + b
a *= b is equal to a = a * b
a /= b is equal to a = a / b

  1. Right associative: Operations that are right associative are performed in a right to left manner. That is, x op y op z is evaluated as x op (y op z).
  2. Left associative: Operations that are left associative are performed in a left to right manner. That is, x op y op z is evaluated as (x op y) op z.

[1]Primitive types: Primitive types are the most basic data types available within the Java language. There are 8: boolean, byte, char, short, int, long, float and double. These types serve as the building blocks of data manipulation in Java.

SEMrush Software