System.out.println("foo" + s != null ? s : ""); precedence
Mark J Roberts
mjr@anarcast.net
Mon Aug 13 17:14:00 GMT 2001
With today's trunk, the ternary operator's precedence is wrong:
public class Test {
public static void main(String[] args) {
String s = null;
System.out.println("foo" + s != null ? s : "");
}
}
$ ./test
null
When enclosed in parentheses, it behaves normally:
System.out.println("foo" + (s != null ? s : ""));
$ ./test
foo
A core dump happens when this is done in a toString method:
public class Test {
public static void main(String[] args) {
System.out.println(new Test());
}
public String toString() {
String s = null;
return "foo" + s != null ? s : "";
}
}
$ ./test
Aborted (core dumped)
If the code's more complex it can fail in other strange ways: gdb reported
SIGSEGVs, etc.
More information about the Java
mailing list