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.");
}
}
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.
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.