Puzzling Java statement of the day

Some days ago I stumbled across a Java statement which I thought was trivial at first, only to discover that I had no idea. I have a reasonable understanding of what a JVM does and how Java bytecode is executed. But as this example shows once again, that doesn’t necessarily spread to the Java programming language. The snippet below should explain my point.

int lorem = 1, ipsum = 2, dolor = 3;
if (lorem == (lorem = ipsum))
	f();
if ((ipsum = dolor) == ipsum)
	g();

Which of the above two methods f() and g() is actually invoked? Can you tell without compiling the code? Possible answers are:

  • None of the two methods get invoked, both call-sites are dead code.
  • Just f() is invoked and the call-site of g() is dead code.
  • Just g() is invoked and the call-site of f() is dead code.
  • Both methods are invoked, the conditions are pointless.

Ironically, I finally understood what was going on after looking at the generated bytecode (good old javap is your friend). I am not posting the disassembled code because that would spoil the fun. But once you look at it, the answer appears to be quite obvious.

Fantastic beat ! I wish to

Fantastic beat ! I wish to apprentice while you amend your website, how can i subscribe for a blog site?
The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast
provided bright clear concept

Eclipse spoiled the fun for

Eclipse spoiled the fun for me, since it highlights comparisons between equal expressions (since Galileo I believe), and yes, the Eclipse code analyser gets this right. My first guess when reading the post was right, but I wouldn't have put money on it.

Here's the relevant JLS section: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#1...

I like the valuable

I like the valuable information you supply in your articles.
I'll bookmark your weblog and test one more right here regularly.
I'm reasonably sure I'll be told lots of new stuff proper right here!
Good luck for the next!

Pingback

[...] Puzzling Java statement of the day | antforge.org antforge.org/blog/2010/07/30/puzzling-java-statement – view page – cached Some days ago I stumbled across a Java statement which I thought was trivial at first, only to discover that I had no idea. I have a reasonable understanding of what a JVM does and how Java bytecode is executed. But as this example shows once again, that doesn’t necessarily spread to the Java programming language. The snippet below should explain my point. Tweets about this link [...]