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.

Tutorials dojo strip



Syntax

JAVA




Example: Traditional If…Else Statement

Instead of writing:

JAVA

You can simply write:

JAVA




Example: Using Ternary Operator with Vehicles

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

JAVA

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:

JAVA

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.

Tutorials dojo strip