# What is this statement doing?

Susan Delph
Ranch Hand
Posts: 34
Can someone please tell me if my guess below is correct?

boolean b1, b2, b3, b4;
b1 = b2 = b3 = b4 = true;
int x = (b1 | b2 & b3 ^ b4)? x++: --x;
System.out.println("Result: " + x);

Result: 0
Since (b1 | b2 & b3 ^ b4) evaulates to true, we postfix increment x, then we prefix decrement x --> which gets us back to x = 0.
BUT if (b1 | b2 & b3 ^ b4) were to evaluate to false, we would SKIP the x++ and jump to to what's beyond the colon: (--x)? If so, then x = -1.
So:
- We only execute what's between ? and : (in this case, x++) if the statement inside the parentheses is TRUE?
- But we execute the code AFTER the : (in this case, --x) no matter what?
In other words:
x = (test)? x++: --x
if test is true do everything after the question mark?
if test is false do everything after the colon?
Thanks! I know this was a long post.
Susan

[This message has been edited by Susan Delph (edited May 01, 2001).]

Manfred Leonhardt
Ranch Hand
Posts: 1492
Hi Susan,
The statement is broken up into the following:
boolean expression ? true choice : false choice
I am not sure what x starts out as because you don't show the initialization. But we can take an example:
String s = (b1 | b2 & b3 ^ b4) ? "True" : "False";
will yield s = "True".
Regards,
Manfred.

Susan Delph
Ranch Hand
Posts: 34
Hi Manfred,
This was a test question from my Java class. Here's the entire question:
What is the value displayed by the following program?

A. -1
B. 0
C. 1
D. 2
According to the instructor, the correct answer is 0.
I verified this by comiling and executing the code. It IS 0. But - I'm not sure why.
When I changed the line to:
b1 = b2 = b3 = b4 = false;
the result was -1.
Susan

Manfred Leonhardt
Ranch Hand
Posts: 1492
Hi Susan,
Now I see the problem, sorry. By your results we can see that we are actually dealing with:
x = x++;
This is the old post increment operator. Since we are starting with 0 this is the compilation steps:
1. Save current value or x (store 0)
2. Increment variable referenced by x (x = 1)
3. Assign saved value to variable referenced by x (x = 0)
Therefore, we get no change in x because the increment happened and then the assignment nullified it!
Regards,
Manfred.

Susan Delph
Ranch Hand
Posts: 34
Hi Manfred,
Thank you, for both explanations!
I understand now....
Susan