JB Header

Java Assignment, Increment/Decrement and Ternary Operators

Introduction This tutorial covers the operators that change a variable's value, and the one operator that chooses between two values - Java's assignment, compound assignment, increment/decrement and ternary operators. We will start with the simple assignment operator and what it returns. We will then look at the compound assignment operators such as +=, including the hidden cast they perform. Next we will learn the difference between the prefix and postfix forms of ++ and --, a favourite topic of Java interview questions. Lastly, we will write short conditional expressions with the ternary operator ? :.

(Note - This tutorial follows Arithmetic, Relational and Logical OperatorsClick to read tutorial: Java Arithmetic, Relational and Logical Operators and Bitwise and Shift OperatorsClick to read tutorial: Java Bitwise and Shift Operators with Examples.) The assignment operator = The assignment operator = evaluates the expression on its right, and stores the result in the variable on its left. The left side must be a variable - 5 = x does not compile.

An assignment is itself an expression, whose value is the value assigned. Assignment is evaluated right to left, which allows chained assignments such as a = b = c = 0 - first c gets 0, then b gets the result of that assignment (0), then a.
The assignment operator
//Assignment.java
public class Assignment {
  public static void main(String[] args) {
    int a, b, c;
    a = b = c = 7;          // chained assignment, evaluated right to left
    System.out.println("a = " + a + ", b = " + b + ", c = " + c);

    int x;
    System.out.println("value of (x = 42) is " + (x = 42));
    System.out.println("x = " + x);
  }
}
 OUTPUT of the above code
a = 7, b = 7, c = 7
value of (x = 42) is 42
x = 42
Note - Using the value of an assignment inside another expression, as in the second println(), is legal but makes code hard to read. Keep each assignment as a statement of its own, except in a few well-known idioms such as reading lines in a loop. Compound assignment operators A compound assignment operator combines an operation with assignment. x += 5 means x = x + 5. Every binary arithmetic, bitwise and shift operator has a compound form -
  • Arithmetic: +=, -=, *=, /=, %=
  • Bitwise: &=, |=, ^=
  • Shift: <<=, >>=, >>>=
Compound assignment operators
//CompoundAssignment.java
public class CompoundAssignment {
  public static void main(String[] args) {
    int total = 100;
    total += 20;   System.out.println("+= 20  -> " + total);
    total -= 5;    System.out.println("-= 5   -> " + total);
    total *= 2;    System.out.println("*= 2   -> " + total);
    total /= 3;    System.out.println("/= 3   -> " + total);
    total %= 7;    System.out.println("%= 7   -> " + total);
    total <<= 4;   System.out.println("<<= 4  -> " + total);

    String greeting = "Hello";
    greeting += ", World";
    System.out.println(greeting);

    byte small = 10;
    small += 5;                   // compiles: includes a hidden cast to byte
    // small = small + 5;         // does not compile: small + 5 is an int
    System.out.println("small = " + small);

    byte wraps = 120;
    wraps += 10;                  // the hidden cast also hides overflow
    System.out.println("wraps = " + wraps);
  }
}
 OUTPUT of the above code
+= 20  -> 120
-= 5   -> 115
*= 2   -> 230
/= 3   -> 76
%= 7   -> 6
<<= 4  -> 96
Hello, World
small = 15
wraps = -126
Explanation of the code
  • /= 3 on an int uses integer division, so 230 becomes 76, not 76.67.
  • += also joins strings, building "Hello, World".
  • x op= y really means x = (type of x) (x op y). That hidden cast is why small += 5 compiles while small = small + 5 does not - small + 5 is promoted to an int. But the cast also hides overflow: 120 + 10 does not fit in a byte, and wraps silently becomes -126.
Increment and decrement operators ++ adds 1 to a variable, and -- subtracts 1. Each comes in two forms -
  • Prefix - ++x: increments x first, and the expression's value is the new value.
  • Postfix - x++: the expression's value is the old value, and x is incremented afterwards.
On a line of its own, x++; and ++x; do exactly the same thing. The difference only shows when the value of the expression is used.
Prefix and postfix increment and decrement
//IncrementDecrement.java
public class IncrementDecrement {
  public static void main(String[] args) {
    int x = 5;
    int a = x++;      // a gets 5, then x becomes 6
    System.out.println("after a = x++ : a = " + a + ", x = " + x);

    int y = 5;
    int b = ++y;      // y becomes 6, then b gets 6
    System.out.println("after b = ++y : b = " + b + ", y = " + y);

    int z = 5;
    System.out.println("z-- prints " + z-- + ", then z = " + z);
    System.out.println("--z prints " + --z + ", then z = " + z);

    double d = 1.5;
    d++;
    char c = 'a';
    c++;
    System.out.println("d = " + d + ", c = " + c);

    int i = 10;
    i = i++;          // a classic trap
    System.out.println("after i = i++ : i = " + i);
  }
}
 OUTPUT of the above code
after a = x++ : a = 5, x = 6
after b = ++y : b = 6, y = 6
z-- prints 5, then z = 4
--z prints 3, then z = 3
d = 2.5, c = b
after i = i++ : i = 10
Explanation of the code
  • a = x++ stored the old value, 5, while b = ++y stored the new value, 6. Both variables were incremented to 6.
  • ++ and -- work on every numeric type, including double and char - 'a' became 'b'.
  • i = i++ leaves i unchanged at 10. The right side's value is the old value, 10; i is incremented to 11; then the assignment stores 10 back into i, overwriting the increment.
  • Best practice: use ++ and -- as statements on their own, or in a loop header such as for (int i = 0; i < n; i++). Never use a variable more than once in an expression which also increments it.
The ternary (conditional) operator The ternary operator is Java's only operator with three operands. It picks one of two values based on a condition -
condition ? valueIfTrue : valueIfFalse
Where,
  • condition is a boolean expression.
  • If it is true, the result is valueIfTrue; otherwise it is valueIfFalse. Only the chosen value is evaluated.
The ternary operator
//Ternary.java
public class Ternary {
  public static void main(String[] args) {
    int age = 20;
    String status = age >= 18 ? "adult" : "minor";
    System.out.println("Status: " + status);

    int a = 14, b = 9;
    int max = a > b ? a : b;
    System.out.println("max = " + max);

    int items = 1;
    System.out.println("You have " + items + " item" + (items == 1 ? "" : "s"));

    int marks = 72;
    String grade = marks >= 90 ? "A" : marks >= 75 ? "B" : marks >= 60 ? "C" : "D";
    System.out.println("Grade: " + grade);

    String name = null;
    System.out.println("Hello, " + (name != null ? name : "guest"));
  }
}
 OUTPUT of the above code
Status: adult
max = 14
You have 1 item
Grade: C
Hello, guest
Explanation of the code Summary In this tutorial we first used the assignment operator, and saw that an assignment is an expression whose value allows chained assignment. We then used the compound assignment operators, and saw the hidden cast which lets byteVar += 5 compile but can also hide overflow. Next we learned the difference between the prefix and postfix forms of ++ and --, and why i = i++ does not change i. Lastly, we chose between values with the ternary operator. In the next tutorial, we will see the order in which Java applies all these operators - operator precedence and associativityClick to read tutorial: Java Operator Precedence and Associativity Explained.