🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #39

Short Hand If...Else


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;

Instead of writing:

Example

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

You can simply write:

Example

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

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.

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Short Hand If...Else – FAQs

Quick answers about learning Short Hand If...Else in Java.

This free note from CodingNow 2.0 explains Short Hand If...Else in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Short Hand If...Else, is 100% free with no signup required.
With focused practice, most students grasp Short Hand If...Else in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now