Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

java - How is if/while condition evaluated when we use assignments instead of comparison?

I discovered this surprising thing while learning OCA/OCP for Java.

Below is the first piece of code of which the if(test condition) part surprises me.

public class BooleanIf {
public static void main(String[] args) {
    boolean b = false;
    System.out.println(Boolean.valueOf(b = true));
    if (b = true)
        System.out.println("true");
    else
        System.out.println("false");
}

Now the output of this surprisingly is "true".

I learnt that there has to be a relational condition that returns true or false like if (a > b) or if (a != b) likewise.

I want to know how it is returning true for this case. Does it call Boolean.valueOf()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

= is assignment operator, == is comparison operator.

But

x = y

not only assigns value from y to variable x, but it also returns that value.

Thanks to that we can do things like x=(y=1) (we can even drop parenthesis here) which will assign 1 to variable y, then will return that 1 and also assign it to x.

Because of that it is also possible to write code like if (b = true) where true will be assigned to b and then be returned and used by if(..). In other words you end up with something like if(true){b=true; ..} so it will always execute code from true branch.


How to avoid this typo?

  • omit ==true and ==false parts.

    • In case of if(b==true) we can write if(b) since (b == true) will always give same result as aleady stored in b.
    • In case of if(b==false) we can write if(!b).
  • use value instead of variable on left side of ==.
    In other words use Yoda conditions if(true == b){..}. Even if by mistake we will write = instead of == we will end up with true=b which will end up as compilation error since we can't assign anything to value like true. We can only assign values to variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...