+ 1
What is the output and how?
public class Program { public static void main(String[] args) { int x=1, y=2,z=3; z = x<y?x++:y++; System.out.println(z); System.out.println(y); System.out.println(x); } } Please explain the step by step procedure also considering that the ternary operator has right to left associativity
3 Answers
+ 2
the sintax ? : it's similar a if.
condition ? if true : if false
x<y
1<2 = true
then
x++
1+1 = 2
so Z = x
Z = 1
print(z)
>> 1
print(y)
>> 2
print(x)
>> 2
+ 1
But increment and decrement has the highest priority compared to conditional operator, so why isn't y++ executed??
0
o/p:- 1
2
2
Here ternary operator is used.
Syntax :- condition if true : if false
So for this example according to the condition z = x++; So first the value of x i.e 1 will be assigned to z and then x will be incremented as the ++ operator is after the operand. If it would have been ++x then first x would be incremented then assigned to z variable. Hence z = 1, x=2, y = 2 will be the output.