<< Quiz: Default Encoding of Java Source Files | Home | Generics in Java Are Evil? >>

What Does It Print

(This was first posted 902 days ago. Zhicheng thought it's worth a repost.)

Question: What is printed when you run java Main?

// Main.java
class A {
    // A is a singleton.  The getInstance() method is even synchronized.
    private static A instance;
    public synchronized static A getInstance() {
        return (instance == null) ? (instance = new A()) : instance;
    }

    // A uses B
    private B b;
    private A() {
        b = new B();
    }
}

class B {
    // B caches the only instance of A
    public static A a = A.getInstance();
}

class Main {
    public static void main(String[] args) {
        System.out.println(A.getInstance() == B.a);
    }
}


Re: What Does It Print

Uhm what does B look like?

Re: What Does It Print

Nevermind

Re: What Does It Print

Wow, I am stunned!

Re: What Does It Print

Dan Just thinks he knows it all :)

Add a comment Send a TrackBack