This post continues from the previous post on the if else statement at

Explaining if else statement in Java.

Consider the following Java statements.

int a=10,b=15;
**int max;
if(a>b)
max=a;
else
max=b;
**

The highlighted statements can be condensed into a single ternary statement.

int a=10,b=15;
**int max=(a>b)?a:b;
**

The if else statement has been condensed into a single line. **int max=(a>b)?a:b; **The ternary statement evaluates the condition and returns the value of the expression after the **? **if the condition is true and the value after the **: **if it is false.

The ternary statement can be nested as well. Consider the problem

of finding the max of three numbers.

int a=10,b=12,c=14;
int max;
if(a>b && a>c)
max=a;
else
if(b>c)
max=b;
else
max=c;

This will be nested as:

int a=10,b=12,c=14;
int max=(a>b && a>c)?a:(b>c)?b:c;

Another example.

int a=10,b=15,c=12;
int max;
if(a>b)
if(a>c)
max=a;
else
max=c;
else
if(b>c)
max=b;
else
max=c;

translates into

int a=10,b=15,c=12;
**int max=(a>b)?(a>c)?a:c:(b>c)?b:c;
**

The ternary statement can return other data types besides the integer type.

int a=19;
String result=(a % 2==0)?"Even":"Odd";

Questions.

1. Given three sides of a triangle check if it is equilateral, isosceles or scalene.

2. Given a year check if it is a leap year or not.

### Like this:

Like Loading...

*Related*