Note that there are some explanatory texts on larger screens.

plurals
  1. POI found a bug in Java Puzzlers VI - can someone explain it?
    primarykey
    data
    text
    <p>Take a look at this <a href="http://code.google.com/edu/languages/index.html#_java_puzzlers" rel="noreferrer">java puzzles vid</a> by Josh Bloch and William Pugh, around time index 0:25:00-0:33:00.</p> <p>One of the speakers says that if you use lowercase <code>boolean</code> instead of <code>Boolean</code>, then <code>LIVING</code> will be treated as a true "compile time constant", and it no longer matters when it is initialized.</p> <p>Well, this is all fine and dandy, but, take a look at what happens when you revert to the original order between the static init and the constructor, and then follow it up by a simple "Extract Method" operation. These two programs print different outputs:</p> <pre><code>public class Elvis { private static final Elvis ELVIS = new Elvis(); private Elvis () {} private static final boolean LIVING = true; private final boolean alive = LIVING; private final boolean lives () {return alive;} public static void main(String[] args) { System.out.println(ELVIS.lives()); // prints true } } </code></pre> <p>And with the refactored <code>returnTrue()</code> method</p> <pre><code>public class Elvis { private static final Elvis ELVIS = new Elvis(); private Elvis () {} private static final boolean LIVING = returnTrue(); private static boolean returnTrue() { return true; } private final boolean alive = LIVING; private final boolean lives () {return alive;} public static void main(String[] args) { System.out.println(ELVIS.lives()); // prints false } } </code></pre> <p>Why does extracting the returnTrue() method change the program output in this case?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload