Brian's Waste of Time

Tue, 01 Feb 2005

Java Pop Quiz

Without breaking out a compiler, or BeanShell ;-), what is the output from the following:

System.out.println("**" + foo != null ? foo : "NULL" + "**");

If foo is the String "wombats!"? What if foo is null?

;-)

writebacks...

Rob


Heh, tough one...reminds me of the questions on the SCJP exam. I'm guessing the output would be: *** NULL *** if foo is "wombats" or null...but I can't quite remember the precedence of the ternary operator. Now I'll need to break out eclipse to try it out...

Janek Schwarz


Yes, that's a nice one. I've seen stuff like int a = 1; int b = 2; System.out.println("** " + a + b); in production code.

Samith


nice one. System.out.println((("**" + foo) != null) ? foo : ("NULL" + "**"));

Samith


nice one. System.out.println((("**" + foo) != null) ? foo : ("NULL" + "**"));

wombat

fools
fools

Denis


Yes, Samith got it right. Addition has higher precedence than the relational '!=' operator, which in turn has higher precedence than the ternary operator. Output should be "wombats!" or "null" (whatever foo is set to). Going to check, just in case!

Luca


But it behave differently from: new StringBuffer().append("**").append(foo != null ? foo : "NULL").append("**"); I hate Java guys for this !!!!

comment...

 
Name:
URL/Email: [http://... or mailto:you@wherever] (optional)
Title: (optional)
Spam Guard, translate l33t to English: (hint, it's an Australian animal, plural form)
Comments:
Save my Name and URL/Email for next time