Interesting Java Language Puzzle
We ran into an unexpected result as part of Java's auto boxing feature. At least I think it is related to auto boxing. See the following code snippet
package com.foo;
public class AutoBoxTest {
public static void main(String[] args) {
Boolean abc = new Boolean(false);
setMe(getThisValue() || abc == null? false: abc);
}
static public Boolean getThisValue() {
return new Boolean(true);
}
static public void setMe(Boolean pValue) {
System.out.println("Value is : " + pValue);
}
}
The result? Value is : false
Huh? It turns out changing the call to setMe() as follows "fixes" the issue, I'd just like to know if anyone can explain why?
Boolean abc = new Boolean(false); setMe(getThisValue() || (abc == null? false: abc));
The result is: Value is : true Strange.
(3 votes)
- Login or register to post comments
- 4643 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)




Comments
Mirosław Pluta replied on Fri, 2010/08/27 - 5:16am
Well, it's quite obvious. It's about operators precedence: http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html || binds stronger than the ternary operator, so what you're executing is :
(getThisValues() || abc == null ) ? false : abc
Philipp Neumann replied on Fri, 2010/08/27 - 5:16am
Look up operator precedence:
is similar to
and is always false.
Mustafa Dasgin replied on Fri, 2010/08/27 - 5:25am
Jim Frohnhofer replied on Fri, 2010/08/27 - 8:13am
While you're at it, check the Javadocs on Boolean:
Tyler Van Gorder replied on Fri, 2010/08/27 - 10:58am
Vassil Stoyanov replied on Fri, 2010/08/27 - 11:38am
Claude Lalyre replied on Fri, 2010/08/27 - 7:13pm
1) First case, we have
(getThisValue() || abc == null? false: abc);
i.e (getThisValue() || abc == null) ? false: abc;
i.e (True || abc == null) ? false : abc
i.e True ? false : abc
i.e false
2) Second case, we have
getThisValue() || (abc == null? false: abc)
i.e True || (abc == null ? false : abc)
i.e True || (whatever)
i.e True
Peter Karich replied on Mon, 2010/08/30 - 2:36am