Can anybody tell me how the snippet below will be executed?
Code:-
int a = 3, b = 4;
a = (a > b) ? a : b;
System.out.print(a);
Can anybody tell me how the snippet below will be executed?
Code:-
int a = 3, b = 4;
a = (a > b) ? a : b;
System.out.print(a);
It is the same as
int a = 3;
int b = 4;
if(a > b) {
a = a;
} else {
a = b;
}
System.out.print(a);
Also see What is the Java ?: operator called and what does it do?
This is a ternary operator (note: not particular to Java but it's widespread and implemented in many languages), and returns either the 2nd or 3rd argument depending on the result of the initial condition.
result = condition ? result if true : result if false
and as such it's shorthand for
if (condition) {
return a;
}
else {
return b;
}
The value of a variable often depends on whether a particular boolean expression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the maximum of two quantities. In Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
line 1: a and b are defined.
line 2: a is set to the value of b (because 3 is not bigger than 4).
line 3: a is printed to current std out.
If 'a' is greater than 'b' you'll get a = a, otherwise if 'b' is greater than 'a' you'll get a = b.
It is the same as the following:
int a = 3, b = 4;
if(a > b){
a = a;
}else{
a = b;
}
System.out.print(a);
And that could be rewritten as:
int a = 3, b = 4;
if(a <= b){
a = b;
}
System.out.print(a);
The ?
is the ternary operator, which considers the code before as condition and evaluates the code before the :
is it is true, and the code after :
if it is false.