• 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

Question on Operators

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the value displayed by the following program?
class Question {
public static void main(String[] args) {
int x = 0;
boolean b1, b2, b3, b4;
b1 = b2 = b3 = b4 = true;
x = (b1 | b2 & b3 ^ b4) ? x++ : --x;
System.out.println(x);
}
}
A. -1
B. 0
C. 1
D. 2

Ans : B (0)
I think Ans is C (1). I think its evaluated as
( b1 |(( b2 & b3) ^ b4 ) ) ? x++ : --x
Could some one make me this clear.

Thanks in advance

Rgds,
Benz.
 
lowercase baba
Posts: 13073
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it is evaluated how you think. but the problem is (probably) in how you're thinking of the

x = x++;

note we are using the post-fix version. so, what happens is, the compiler says ok, i need to evaluate the right, THEN increment x. so, the rhs evaluates to 0. now increment x. so, x is now 1. NOW i need to assign the value of the RHS to x. the value was 0. so, assign 0 to x.

so, we end up printint out 0.

if you change it to ++x, you'll get 1.
[ August 26, 2004: Message edited by: fred rosenberger ]
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"Benz" please take time out to read our JavaRanch Naming Policy and change your displayed name accordingly.
Thankyou,
-Barry
 
Hey cool! They got a blimp! But I have a tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic