-7

我有產生不同的輸出下面的兩段代碼:爲什麼這個布爾變量被賦值爲真?

boolean a = false, b = false, c = false, d = false; 
if (a = false | (b = false) || (c = true) | (d = true)){ 

} 
System.out.println("if (a = false | (b = false) || (c = true) | (d = true))"); 
System.out.printf("a=%b\nb=%b\nc=%b\nd=%b\n\n", a, b, c, d); 


if ((a = false) | (b = false) || (c = true) | (d = true)){ 

} 
System.out.println("if ((a = false) | (b = false) || (c = true) | (d = true))"); 
System.out.printf("a=%b\nb=%b\nc=%b\nd=%b\n", a, b, c, d); 

當運行上面的代碼中,我得到以下輸出:

if (a = false | (b = false) || (c = true) | (d = true)) 
a=true 
b=false 
c=true 
d=true 

if ((a = false) | (b = false) || (c = true) | (d = true)) 
a=false 
b=false 
c=true 
d=true 

請注意,a在第一個片段分配true ,但不在第二個。

爲什麼用圓括號包裝a會產生這樣的差異?

請注意,我正在使用賦值運算符(=)和而不是比較運算符(==)故意使用

+0

@Eran我不想比較,我把它設置爲false。但爲什麼它變成了現實? –

+0

@JohnE .:那你爲什麼要用if語句? – Stultuske

+0

@Stultuske在if語句中賦值沒有任何問題。 –

回答

4

正如您所見,here|運算符具有比賦值運算符=更高的優先級。因此,當你不小括號括(a = false)

if (a = false | (b = false) || (c = true) | (d = true)) 

相當於

if (a = (false | (b = false) || (c = true) | (d = true))) 

所以你要分配給truea

在另一方面,在

if ((a = false) | (b = false) || (c = true) | (d = true)) 

要分配給falsea

3

區別在於,在第二種情況下,您直接指定(a = false) - 因此a將爲false。

在第一種情況下,你實際上分配到的值不是false

false | (b = false) || (c = true) | (d = true) 

這相當於

false | false || true | true 

這是true

看看在operator precedence,看看究竟是什麼打算在這裏:

  • 首先將|被視爲
  • 那麼||
  • 那麼=

因此聲明計算方法如下:

a = false | (b = false) || (c = true) | (d = true) 
a = false | false || true | true 
a = true || false 
a = true