File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on Operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on Operators" Watch "Question on Operators" New topic
Author

Question on Operators

Benz
Greenhorn

Joined: Aug 05, 2004
Posts: 2
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

Joined: Oct 02, 2003
Posts: 10916
    
  12

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 ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
"Benz" please take time out to read our JavaRanch Naming Policy and change your displayed name accordingly.
Thankyou,
-Barry


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on Operators
 
Similar Threads
precedence question
Unary Operators
What is this statement doing?
ternary operator
Bitwise Operators