Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# differences???

Helen Yu
Greenhorn
Posts: 29

Hi,there:
Could someone give some advise on these similar small programs?
I seemed to understand the second but not first one.
Acturally, this is the Q15 & Q16 of www.javaprepare.com's second Exercises, topic is Assignment and Operator.
What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
Q15
public class test {
public static void main(String args[]) {
boolean x = true;
int a;
if(x) a = x ? 1: 2;
else a = x ? 3: 4;
System.out.println(a);
}
}

a.1
b.2
c.3
d.4

Q16.
What gets displayed on the screen when the following program is compiled and run. Select the one correct answer.
public class test {
public static void main(String args[]) {
boolean x = false;
int a;
if(x) a = x ? 1: 2;
else a = x ? 3: 4;
System.out.println(a);
}
}

a.1
b.2
c.3
d.4

Nirmala
Ranch Hand
Posts: 93
Hi Helen,
Originally posted by Helen
Q15
public class test {
public static void main(String args[]) {
boolean x = true;
int a;
if(x) a = x ? 1: 2;
else a = x ? 3: 4;
System.out.println(a);
}
}
a.1
b.2
c.3
d.4

If you understand the second question then the first one is more easier than second one. How does Ternary Operator works:
a = x ? 1: 2;
if x is true then a=1. If x is false the a=2;
If this is the case ,in the first case the x is true and so
a = x ? 1: 2;,this part(true part) of if statement is executed. Apply ternary statement rules ie,x is true,so a=1.
In the second case x is false and so false part of "if" is executed and so the answer is a=4;
Hope this helps.
Regards
Nirmala

Helen Yu
Greenhorn
Posts: 29
Thank you, Nirmala, I'm clear now.

Helen Yu
Greenhorn
Posts: 29
Thanks a lot.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?