-7

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);
lambda.xy.x
  • 4,918
  • 24
  • 35
lucky
  • 57
  • 1
  • 8

6 Answers6

5

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?

Community
  • 1
  • 1
apals
  • 291
  • 1
  • 3
3

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;
}
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

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.

siddhant
  • 258
  • 1
  • 3
  • 7
1

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.

Würgspaß
  • 4,660
  • 2
  • 25
  • 41
1

If 'a' is greater than 'b' you'll get a = a, otherwise if 'b' is greater than 'a' you'll get a = b.

hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
1

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.

moffeltje
  • 4,521
  • 4
  • 33
  • 57