3

I tried to understand how exactly the return value of assignment operation works. followed by this post "Java returns the assigned value".

    boolean b1 = false, b2 = false;
    if (b2 = b1 == false) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

b2 is true because of (b1 == false) return true, then the return of b2 assignment b2 = true

Or is it because of some other reason?

Graham
  • 7,431
  • 18
  • 59
  • 84
Pauwelyn
  • 199
  • 1
  • 10

1 Answers1

4

You've got it right. The operator precedence rules make sure that first the == operator is evaluated. That's b1==false, yielding true. After that, the assigned is executed, setting b2 to true. Finally, the assignment operator returns the value as b2, which is evaluated by the if statement.

Stephan Rauh
  • 3,069
  • 2
  • 18
  • 37
  • `int i = doIt() / (j = 2);` , why the method execution comes before the grouping & accessing operators ? they are in the top level of [Operator Precedence and Parentheses](http://stackoverflow.com/documentation/java/176/operators/9207/operator-precedence-and-parentheses#t=201701111907181800707) .thanks – Pauwelyn Jan 11 '17 at 19:09
  • Java usually evaluates the terms from the left to the right (pretty much like we humans do, at least in the western hemisphere). So we start with `doIt`. Next thing we see is a `()`. That's top priority, so we call the function. After that we encounter the `/`, priority 13. It's followed by another `(`, priority 16. So we evaluate `j=2` first. Having done that, we return to the division. That happens to be the last step in the evaluation. – Stephan Rauh Jan 12 '17 at 22:16
  • Another possible explanation is that `doIt()` is a singular term. In Java, you can't do anything with the name of a method. Other programming languages may treat it as an useful entity of its own (function pointers, lambda expression etc.). Java doesn't do such a thing. If it finds a method name in an expression, the only sensible thing to do is to execute it. From this point of view, `doIt` and `()` belong together and can't be separated. They are a single, atomar term of the expression. Little wonder the method is evaluated first, no matter what comes next. – Stephan Rauh Jan 12 '17 at 22:21