Ternary operator

Ternary operator makes our lifes more comfortable and code more easier.

For example we have logic in our task: if int a bigger than 100, int b=a otherwise b=-500.

How we can realize it with if/else operators:

int a=99;
int b;
if (a>100){
b=a;
}
else
b=-500;
System.out.println(b);
//------------------------------------------------------------------
-500
Process finished with exit code 0

other condition:

int a=101;
int b;
if (a>100){
b=a;
}
else
b=-500;
System.out.println(b);
//------------------------------------------------------------------
101
Process finished with exit code 0

All right, our code is working, we realized our logic, but we can do it more gracefully with Ternary operator:

int a = 99;
int b;
b = a > 100 ? a : - 500;
System.out.println(b);
//------------------------------------------------------------------
-500
Process finished with exit code 0

and other condition

int a = 101;
int b;
b = a > 100 ? a : - 500;
System.out.println(b);
//------------------------------------------------------------------
101
Process finished with exit code 0

As we see Ternary operator has structure: if-then-else

Syntax of java ternary operator is:

result = testStatement ? value1 : value2;

So our code with Ternary operator’s looking more neat and readable.