bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Tutorial
Java•Java Tutorial

Java Short Hand If...Else (Ternary Operator)

Short Hand if...else

There is also a short-hand if else , which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

Syntax

variable = ( condition ) ? expressionTrue
: expressionFalse ;

Example

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}

Example

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

You can simply write

You can also use the ternary operator directly inside System.out.println() without a temporary variable:

Example

int time = 20;
System.out.println((time < 18) ? "Good day." : "Good evening.");

Nested Ternary (Optional)

You can nest ternary operators to handle more than two possible outcomes, but this can make your code harder to read:

Example

int time = 22;
String message = (time < 12) ? "Good morning."
: (time < 18) ? "Good afternoon."
: "Good evening.";
System.out.println(message);

Tip

Use the ternary operator for short, simple choices. For longer or more complex logic, the regular if...else is easier to read.

Previous

Java Else If

Next

Java Nested If

This chapter

Overview
49

Lessons

110m

Read time

1. Java Tutorial2. Java Introduction3. Java Getting Started4. Java Syntax5. Java Statements6. Java Output / Print7. Java Output Numbers8. Java Comments9. Java Variables10. Java Print Variables11. Java Declare Multiple Variables12. Java Identifiers13. Java Constants (final)14. Java Data Types15. Java Numbers16. Java Boolean Data Types17. Java Characters18. Java Data Types Example19. Java Non-Primitive Data Types20. Java var Keyword21. Java Type Casting22. Java Operators23. Java Arithmetic Operators24. Java Assignment Operators25. Java Comparison Operators26. Java Logical Operators27. Java Operator Precedence28. Java Strings29. Java String Concatenation30. Java Numbers and Strings31. Java Special Characters32. Java Math33. Java Booleans34. Java If ... Else35. Java Else36. Java Else If37. Java Short Hand If...Else (Ternary Operator)38. Java Nested If39. Java Logical Operators in Conditions40. Java Switch41. Java While Loop42. Java Do/While Loop43. Java For Loop44. Java Nested Loops45. Java For Each Loop46. Java Break and Continue47. Java Arrays48. Java Arrays Loop49. Java Multi-Dimensional Arrays

On this page

Short Hand if...elseNested Ternary (Optional)