Thursday, June 28, 2007

Friday Java Quiz

My friend, Weiqi Gao, frequently posts a Friday Java Quiz . I ran into a situation today that seems like a good one.

Suppose you have the following two classes:

public class Test {
public static void main(String[] args) {
System.err.println( Foo.class.getName() );
System.err.println( "Testing, 1, 2, 3..." );
new Foo();
}
}

public class Foo {
static {
System.err.println( "Foo here." );
}
public Foo() {
System.err.println( "New Foo!" );
}
}


Without running this program, do you know what the output will be?

8 comments:

konberg said...

So I'll say that there was a Java Puzzler at J1 very similar to this one, so that gave me a hint. Note that I got it right! :)

Eugene Kuleshov said...

Actually it depends. It should give different results between Java 5 and earlier VMs.

Dean said...

I thought this might be a trick question, but it isn't. I got it right. One just has to understand a little about class loading.

Brian Gilstrap said...

Thanks for the information Eugene. The answer does indeed depend upon whether you're using Java 5 or an earlier version of Java.

This explains why the behavior I saw yesterday (under Java 5) surprised me.

So, the quiz is now a two-parter: how does this code behave when run with Java 5 (or later, I presume) and how does it behave with earlier versions of Java?

Unknown said...

Got me. I guessed the 1.4.2 (and earlier -- I hope) behavior.

Thanks for the heads up.

Weiqi Gao said...

It gets more interesting as you consider the compiler/VM combinations: how will it behave when compiled with a Java 4 compiler but ran with a Java 5 VM?

Lakshmi said...

Answer is
FOO
Testing,1,2,3...
Foo here
New Foo!

is it correct?

Brian Gilstrap said...

The correct answer depends upon your Java version. For Java 5 and later:

Foo
Testing, 1, 2, 3...
Foo here.
New Foo!

This represents this order of execution:
1 name of class
2 print from 'main'
3 static class initializer
4 constructor

For 1.4.2 and earlier, the act of asking for the name of the class causes the class to be loaded and you get:

Foo here.
Foo
Testing, 1, 2, 3...
New Foo!

This represents this order of execution:
1 static class initializer
2 name of class
3 print from 'main'
4 constructor