Tenary Operator (?:)

This operator can be used in place of a single if/else expression that assigns a value to a specific variable.

Using If Statement

int number = 10;
boolean isEven;
if( number % 2 == 0){
    isEven = true;
}else {
    isEven = false;

Using Tenary Operator ?:

This will produce the same value as the above expression that uses an if/else expression.

int number = 10;
boolean isEven = ( number % 2 == 0)  ? true : false;

The tenary operator might be hard to grasp initially but it enables you to write less code. As you progress with your coding craftsmanship you enjoy saving a few extra typing keystrokes.

results matching ""

    No results matching ""