-1

After I run the following code, the output prints: false. So I am assuming i1==i2 was evaluated before b1 = i1. But isn't the order is from left to right?

public static void main(String[] args) {
    boolean b1;
    int i1 = 2;
    int i2 = 3;

    if(b1 = i1==i2) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}
4
  • First it puts a value inside b1 and then it checks if the value if true or false. In this case the 2!=3 so 'b1' value is 'false'
    – roeygol
    Jan 3, 2015 at 22:25
  • looks like it checks i1==i2 is false and then checks b1 and (i1==i2) which means b1 = false so it prints"false"
    – OPK
    Jan 3, 2015 at 22:27
  • if you do not put an assignment inside an if you never need to remeber its precendence. and if you cannot remeber the precedence of an operator it is probably best to put it in braces.
    – eckes
    Jan 3, 2015 at 22:29
  • 1
    What would be, anyway, the assigned value if the = was evaluated before the value expected to be assigned. The answer of this question is obvious by simple logic
    – Dici
    Jan 3, 2015 at 22:34

4 Answers 4

8

Check out operator precedence: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

== is evaluated before =

1
  • yeah that seems right and could be explained also as b1 will be assigned the value of the condition (i1 equals i2), so the == operator has to be evaluated first before the assignment.
    – hasan
    Jan 3, 2015 at 22:28
2

You can view the order of precedence here:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

0

The simplest explanation is this:

When dealing with assignment, the right side of the equals side is evaluated and then assigned to the left side.

Of course, typically assignment in boolean expressions limits readability. A better practice would be to assign b1 = i1 == i2 before the if and put if (b1) {...} OR get rid of b1 altogether in if (i1 == i2) {...}

0

No, it is evaluated according to operator precedence, which puts == before =.

The statement about 'left to right' applies to operands of binary operators: the left-hand operand is evaluated before the right-hand operand. Also to argument lists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.