Java Short Hand If…Else

In Java, you can use the shorthand if...else, known as the ternary operator, which consists of three operands. It can be used to replace multiple lines of code with a single line, making the code more concise and readable. The ternary operator is most often used to replace simple if...else statements.



Syntax

variable = (condition) ? expressionTrue : expressionFalse;




Example: Traditional If…Else Statement

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);




Example: Using Ternary Operator with Vehicles

Let’s apply the concept of vehicles to the ternary operator:

// Example
int carSpeed = 120;
int speedLimit = 70;
String speedStatus = (carSpeed <= speedLimit) ? "Within speed limit" : "Over speed limit";
System.out.println(speedStatus);
// Outputs "Over speed limit"

In the example above, we use the ternary operator to evaluate whether the carSpeed is within the speedLimit. If the condition carSpeed <= speedLimit is true, the variable speedStatus is assigned the value “Within speed limit”. If the condition is false, speedStatus is assigned the value “Over speed limit”. The result is then printed to the console.




Another Example: Motorcycle Speed Check

Let’s consider another example with motorcycles:

// Example
int motorcycleSpeed = 90;
int speedLimit = 80;
String speedCheck = (motorcycleSpeed <= speedLimit) ? "Motorcycle is within the speed limit" : "Motorcycle is over the speed limit";
System.out.println(speedCheck);
// Outputs "Motorcycle is over the speed limit"

In this example, the ternary operator checks if the motorcycleSpeed is within the speedLimit. If the condition motorcycleSpeed <= speedLimit is true, the variable speedCheck is assigned the value “Motorcycle is within the speed limit”. If the condition is false, speedCheck is assigned the value “Motorcycle is over the speed limit”. The result is then printed to the console.

Scroll to Top