This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv 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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on Operators" Watch "Question on Operators" New topic

Question on Operators


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;
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

fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11923

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.

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
It's not a secret anymore!