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
(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
An assignment is itself an expression, whose value is the value assigned. Assignment is evaluated right to left, which allows chained assignments such as
OUTPUT of the above code
Note - Using the value of an assignment inside another expression, as in the second
OUTPUT of the above code
Explanation of the code
Increment and decrement operators
OUTPUT of the above code
Explanation of the code
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 -
Where,
OUTPUT of the above code
Explanation of the code
+=, 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);
}
}
a = 7, b = 7, c = 7 value of (x = 42) is 42 x = 42
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);
}
}
+= 20 -> 120 -= 5 -> 115 *= 2 -> 230 /= 3 -> 76 %= 7 -> 6 <<= 4 -> 96 Hello, World small = 15 wraps = -126
/= 3on anintuses integer division, so 230 becomes 76, not 76.67.+=also joins strings, building"Hello, World".x op= yreally meansx = (type of x) (x op y). That hidden cast is whysmall += 5compiles whilesmall = small + 5does not -small + 5is promoted to anint. But the cast also hides overflow: 120 + 10 does not fit in abyte, andwrapssilently becomes -126.
++ adds 1 to a variable, and -- subtracts 1. Each comes in two forms -- Prefix -
++x: incrementsxfirst, and the expression's value is the new value. - Postfix -
x++: the expression's value is the old value, andxis incremented afterwards.
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);
}
}
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
a = x++stored the old value, 5, whileb = ++ystored the new value, 6. Both variables were incremented to 6.++and--work on every numeric type, includingdoubleandchar-'a'became'b'.i = i++leavesiunchanged at 10. The right side's value is the old value, 10;iis incremented to 11; then the assignment stores 10 back intoi, overwriting the increment.- Best practice: use
++and--as statements on their own, or in a loop header such asfor (int i = 0; i < n; i++). Never use a variable more than once in an expression which also increments it.
condition ? valueIfTrue : valueIfFalseconditionis abooleanexpression.- If it is
true, the result isvalueIfTrue; otherwise it isvalueIfFalse. 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"));
}
}
Status: adult max = 14 You have 1 item Grade: C Hello, guest
- The ternary operator is an expression - it produces a value - so it can be used where an
ifstatement cannot, such as inside aprintln()or when initializing a variable. - Ternaries can be chained to choose between several values, as in the grade example, but long chains quickly become hard to read. Use an if-else-if ladderClick to read tutorial: Java if, else if and else Statements with Examples or a switch expressionClick to read tutorial: Java Switch Expressions: Arrow Labels and yield instead.
- Wrap a ternary in parentheses when it is part of a larger expression. Without them,
"item" + items == 1 ? ...would compare the joined string with 1, which does not compile. - Both values should have compatible types. Mixing an
intand adouble- as intrue ? 1 : 2.0- promotes the result todouble, giving1.0.
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.Java Fundamentals Tutorials
Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples Java Operator Precedence and Associativity ExplainedClick to read tutorial: Java Operator Precedence and Associativity Explained Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples
Java Bitwise and Shift Operators with ExamplesClick to read tutorial: Java Bitwise and Shift Operators with Examples Java Operator Precedence and Associativity ExplainedClick to read tutorial: Java Operator Precedence and Associativity Explained Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples