• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Mock question

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
I don�t understand this question:
10. Select the equivalent answer for the code given below?
boolean b = true;
if ( b ) {
x = y;
} else {
x = z;
}
A) x = b ? x = y : x = z ;
B) x = b ? y : z ;
C) b = x ? y : z ;
D) b = x ? x = y : x = z ;
The answer is B but why x = b??? I think that the correct answer will be (x == true) ? y : z;
Thank you in advance.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi jordi,
The ternary operator x=(a?b:c) allows to replace an if-else statement of this form:
if(a)
x=b
else
x=c
Thus, a has to be a boolean expression.
B is the correct answer because b is a boolean expression and x gets assigned y if b is true and z otherwise.
In this example b is true since it is declared and initialized as such at the top of the code...
Hope that helps
Val
 
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jordi,
x = b ? y : z ;
consider only this:
b ? y : z
means if b is true - y
else - z
now
x = b ? y : z ;
means if b is true - x=y
else - x=z
I think i have not made it very clear.
Ask if u still have doubt.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you, I understand now
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic