aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes differences??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "differences???" Watch "differences???" New topic
Author

differences???

Helen Yu
Greenhorn

Joined: Jul 13, 2000
Posts: 29

Hi,there:
Could someone give some advise on these similar small programs?
I seemed to understand the second but not first one.
Thanks in advance.
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
Answer is a. why??

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
Answer is d.


hyby2000@yahoo.com
Nirmala
Ranch Hand

Joined: Jun 28, 2000
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
Answer is a. why??

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

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

Joined: Jul 13, 2000
Posts: 29
Thanks a lot.
 
jQuery in Action, 2nd edition
 
subject: differences???