We get 4 after compiling this program. I can not understand what is happening on line 1 and the following one. Can some one explain plz. public class test { public static void main(String args[]) { boolean x = true; int a; if(x) a = x ? 1: 2;// Line 1 else a = x ? 3: 4; System.out.println(a); } }
I got an output of 1. Since x is true, this executes: a = x ? 1: 2; Since x is already true, the first value will have to be assigned to a. Thus, a = 1.
Originally posted by ZEESHAN AZIZ: We get 4 after compiling this program. I can not understand what is happening on line 1 and the following one. Can some one explain plz. public class test { public static void main(String args[]) { boolean x = true; int a; if(x) a = x ? 1: 2;// Line 1 else a = x ? 3: 4; System.out.println(a); } }
It equals: If(x) { if (x) a=1; else a=2; } else { if (x) a=3; else a=4; }
hi friends plz someone explain that why is a=x not assigning the value of x to a.see the code below boolean x = true; int a; if(x) a = x ? 1: 2;// Line 1 else a = x ? 3: 4; System.out.println(a); } } originaly posted by zeeeshan aziz. the answer is 4.
hi zeeshan.. that is because first the ternary is operator is applied and the following expr is evaluated: x?1:2 and since x is true it returns 1 which gets assigned to a, hence a=1.. my output also comes out to be 1. hope this helps..
------------------ Hima
Hima<BR>Sun Certified Java Programmer
You showed up just in time for the waffles! And this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!