<< Flash Player 9 for 64-Bit Debian 4.0: Here's The Link | Home | Alexander Stepanov: Notes On Programming >>

Friday Java Quiz: What Does -source 1.4 Really Mean?

Today's quiz has to do with the -source and -target command line switches of the javac command. We are all familiar with these switches.

But do we really know how they work?

Suppose I have just built a new Debian 4.0 box, and installed Sun Java 5 on it. There are no other versions of Java installed on the box. Without actually invoking the compiler, answer the following question.

Will the following Foo.java:

public class Foo {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append("Hello, world.\n");
    System.out.println(sb.toString());
  }
}

compile successfully with the following command line:

javac -source 1.4 Foo.java

?

What about the following command line:

javac -source 1.4 -target 1.4 Foo.java

?

Explain why.

[Update] I should have mentioned that this is a two part question. And here is the second part. Answer the same questions for this class:

public class Bar {
  public static void main(String[] args) {
    System.out.printf("Hello, world.");
  }
}
Tags :


Re: Friday Java Quiz: What Does -source 1.4 Really Mean?

It's sort of simple. Both will compile successfully on Java 5. Source ensures the code fits within language constructs. So, for example, -source 1.4 will ensure the code doesn't use generics, but can use assertions. Target ensures that the class file generated will be compatible with the appropriate version.
Neither ensures API compatibility. So although it will compile and run successfully on Java 5 and later, it will not run correctly on Java 1.4. The reason is, the StringBuilder class won't be on the 1.4 classpath.

Re: Friday Java Quiz: What Does -source 1.4 Really Mean?

That's what I thought. But then I saw something else. See the second part of the quiz.

Re: Friday Java Quiz: What Does -source 1.4 Really Mean?

The answer is in the method signature of printf in the PrintStream class:

printf(String format, Object... args)

printf uses varargs, which is a Java 5 feature, not a Java 4 feature. That's why it fails.

Re: Friday Java Quiz: What Does -source 1.4 Really Mean?

A-ha.

Since varargs are translated into arrays in the class file, the method signature is really

printf(String format, Object[] args);

So if I change the printf line into

System.out.printf("Hello, world.", null);

It should compile.


Add a comment Send a TrackBack