This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 11170
    
  16

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question on Operators
 
Similar Threads
Unary Operators
What is this statement doing?
precedence question
ternary operator
Bitwise Operators