Monica
Monica

Reputation: 1599

Changing boolean value inside if-statement?

I'm studying for the OCA Java SE7 Associate exam. One of my practice exam questions had the following code snippets:

boolean flag = true;
if (flag = false) {
    System.out.println("1");
}
else if (flag) {
    System.out.println("2");
}
else if (!flag) {
    System.out.println("3");
}
else
    System.out.println("4");

Notice the if (flag = false) conditional. The question asked what the output of this snippet would be. All the numbers were provided as answer choices and then there was a choice that said "compiler error," which is what I selected. I was wrong. The output would be 3. I tested in Eclipse and it also came back with 3.

I then tested with

int x = 3;
int y = 1;
if (x = y) {
   // whatever
}

and, of course, got an error.

Why can the flag be changed from true to false inside the if-statement, but the value of x can't be changed in the similar scenario? Is it because flag is a boolean type and x is type int? I Googled this, but was unable to find anything.

Upvotes: 2

Views: 4010

Answers (4)

Bully WiiPlaza
Bully WiiPlaza

Reputation: 472

It would print 3 because the boolean variable is assigned false (and checked for true) then checked for false and finally for !false which is true.

Upvotes: 0

Halvor Holsten Strand
Halvor Holsten Strand

Reputation: 20536

if (flag = false) will set the flag variable to false, then check if(flag).

You are suggesting doing if(x = 1) which could set x to 1, but if(x) is not valid.

Upvotes: 0

steviesama
steviesama

Reputation: 337

flag = false is an assignment, so it is carried out. After the assignment on the first if, it evaluates to false because it was just set to it. For equality it should have been flag == false, but since it was an assignment, the top if was evaluated to false, and since it was changed to false, when you get to !flag, that passes because flag is no longer true, and it prints 3.

You got an error with if(x = y) because after the assignment, the value couldn't be evaluated as a boolean outcome whereas if(flag = false) can evaluate to boolean after the assignment.

The big thing to remember about high-level languages is that it takes more than one low-level statement to perform the logic of even a simple if, and with the assignment case, there is a minimum of 2 operations going on, first the assignment, then the equality.

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347184

Because the assignment of x = y doesn't equate to a boolean evaluation.

if is expecting the result of the operation to give either a true or false return.

Something like if ((x = y) == y) would work (the evaluation would return true)

Upvotes: 7

Related Questions