Pop Quiz Answers
Adrian Sutton
Brian put forward a Java pop quiz and it happens to be an area I know very well:
Without breaking out a compiler, or BeanShell ;-), what is the output from the following:
System.out.println("**" + foo != null ? foo : "NULL" + "**");
The statement is equivalent to:
System.out.println(foo);
Why?
The left most + operator is the first thing to be evaluated. So the if statement then evaluates whether or not "\*\*" + foo is null which it never is and so the value of foo is always output. Similarly, the "NULL" + "\*\*" may as well have just been "NULL**", in fact the compiler optimizes it to be exactly that as javap shows:
13 ldc #3 <String "NULL**">
The lesson to learn from all this is that + is a very high ranking operator and will probably be evaluated first. The other lesson is that using ?: for if leads to ambiguity and should usually be avoided.