• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Operators

 
Benz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12149
31
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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 ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Benz" please take time out to read our JavaRanch Naming Policy and change your displayed name accordingly.
Thankyou,
-Barry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic