Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

differences???

 
Helen Yu
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

 
Nirmala
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Nirmala, I'm clear now.
 
Helen Yu
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic