False boolean = True?

前端 未结 7 1024
粉色の甜心
粉色の甜心 2020-12-07 02:12

I found this code in a book and I executed it in Netbeans:

boolean b = false;
if(b = true) {
    System.out.println(\"true\");
} else {
    System.out.printl         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 02:56

    This is because the if-statement condition isn't a comparison. It's an assignment:

    if(b = true)
    

    Which will always return true. So it will always print true.

    If you wanted to do a comparison, you need to use ==.

提交回复
热议问题