1. Expressions vs statements
All constructs in Java fall into two categories: statements and expressions. A statement is said to execute, while an expression is said to evaluate. But that’s not the main point.
The key difference between a statement and an expression is that an expression has a result. That result, first, has a type, and second, it can be assigned somewhere or used in some other expression.
Examples:
| Code | Notes |
|---|---|
|
Statement |
|
Expression, type boolean |
|
Expression; type matches the type of variable i |
|
Expression; type matches the type of variable x |
So what does this give us?
First, we can take advantage of the fact that many statements are actually expressions (they have a result). For example, this code will work:
int x, y, z;
x = y = z = 1; // x = (y = (z = 1));
Second, we can ignore the result of an expression if we want.
console.nextLine(); //ignore the input result
Ignoring the result of an expression is useful when the expression does something else useful besides producing a value, and we care about that action but not the value itself.
2. Ternary operator
This tip is a bit more interesting than the previous one. Java has a special ternary (three-operand) operator. It’s somewhat similar to a shorthand for the if–else operator:
Condition ? Expression1 : Expression2;
If the condition is true, then Expression1 executes; otherwise, Expression2 executes. The condition is followed by a question mark, and the two expressions are separated by a colon.
The main difference between the ternary operator and if-else is that the ternary operator is an expression, which means its result can be assigned to something.
For example, we want to compute the minimum of two numbers. Using the ternary operator, the code looks like this:
int a = 2;
int b = 3;
int min = a < b ? a : b;
Or suppose you need to assign different values to a variable depending on some condition. How do you do that?
The first option is to use if-else:
int age = 25;
int money;
if (age > 30)
money = 100;
else
money = 50;
The second option is to use the ternary operator, i.e., the shorthand for if-else:
int age = 25;
int money = age > 30 ? 100 : 50;
So which is better to use: if-else or the ternary operator? In terms of execution speed, there’s little difference. It’s more a question of code readability. And that’s very important: code should not only work correctly but also be easy for other developers to read.
A simple rule of thumb could be: if the code fits on one line—use the ternary operator; if it no longer fits on one line—prefer if-else.
3. Usage nuances
Value types
It’s important to remember: both branches of the ternary operator (<value_if_true> and <value_if_false>) must be of the same type or compatible (e.g., both String, or both int).
Works:
int a = 10, b = 20;
int max = (a > b) ? a : b; // both branches — int
Compilation error:
int a = 10, b = 20;
// String and int are incompatible
String result = (a > b) ? "greater" : 0; // Compilation error: cannot assign int to a variable of type String
Correct version:
int a = 10, b = 20;
String result = (a > b) ? "greater" : "less than or equal";
Example: working with numbers
Let’s compute an absolute value using the ternary operator:
int number = -5;
int abs = (number >= 0) ? number : -number;
System.out.println(abs); // 5
4. Embedding the ternary operator into an application
Let’s write a small interactive application: besides greeting the user, the program will say how old they will be next year and indicate whether they will be an adult.
System.out.print("Enter your name: ");
String name = console.nextLine();
System.out.print("Enter your age: ");
int age = console.nextInt();
int nextYear = age + 1;
String status = (nextYear >= 18) ? "an adult" : "a minor";
System.out.println("Hello, " + name + "! Next year you will be " + nextYear + ". You will be " + status + ".");
Let’s explain the details:
The status variable is computed via the ternary operator: if the age next year is at least 18, the user will be an adult (or remain one).
5. Nested ternary operators — use with care!
You can nest ternary operators (each branch can contain another ternary). But… this usually gives readers a headache, especially whoever has to read the code after you (even if that’s you in two days).
Example: determining an age category
String category = (age < 7) ? "preschooler" :
(age < 18) ? "school student" :
(age < 65) ? "adult" : "senior";
Decision table:
| Age | Condition | Result |
|---|---|---|
| < 7 | |
preschooler |
| 7–17 | |
school student |
| 18–64 | |
adult |
| 65 and above | else | senior |
This code is still readable, but if the logic gets more complex—prefer if-else if-else.
6. Pro tip: the ternary operator and type boolean
Sometimes you might write an expression like:
boolean adult = (age >= 18) ? true : false;
But that’s redundant. The expression (age >= 18) already returns boolean. So you can shorten it to:
boolean adult = (age >= 18);
GO TO FULL VERSION