• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

justify answer on ternary operator

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

for this code answer is 1
can anyone justify the answer


thanks
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you indent the body of the if statement, it becomes easy to see what happens.



Since x is true, a=x? 1:2; is executed. Since x is true, the value of the ternary expression is 1 which is assigned to a.
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public static void main(String[] args){//1
boolean x = true;//2
int a;//3
if(x) a=x? 1:2;//4
else a=x? 3:4;//5
System.out.println(a);} //6

In line no one s is assigned the value true.
At line no 4 the if statement is excuted since x is true.
so at line 4 true is returned and thus one is assignes to the int a.
Thus at line 6 the value of a thai is one due to line 4 is printed on the screen.
 
madhu v pe
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Keith. you confirmed me what I saw was the correct aswer.
srikanth sorry I didn't understnd your explanation.

Thanks
 
Goodbye moon men. Hello tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic