Basics:
Here I have two JDK locations in my system.
1) Default Jdk (1.6) is located in $JAVA_HOME (/usr/lib/jdk1.6.0_45)
2) Lower version Jdk (1.5) is located in ~/jdk_5/jdk1.5.0_22/
Now take a sample class
public class Test{
public static void main(String nag[]){
System.out.println("Hello Nagarjuna");
}
}//end class
now I am compiling using jdk 1.6 like
$ $JAVA_HOME/bin/javac Test.java
It will be compile and generate Test.class
And now try to run this Test.class file using jdk 1.6
$ $JAVA_HOME/bin/java Test
o/p : Hello Nagarjuna
lly, Now try to run with jdk 1.5
$ ~/jdk_5/jdk1.5.0_22/bin/java Test
o/p:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
It is because of higher version compilation and lower version execution.
But we can compile the above Test.java using jdk 1.5 and can run the generated Test.class file in both jdk1.6 and jdk1.5 . Because lower version compilation can support higher (Latest) version execution.
Now, let us try cross compilation in jdk 1.6
Cross compilation:
Here we use javac arguments ( only 'target')
Use 'taget' argument to javac while compiling with jdk1.6.
compilation:
$ $JAVA_HOME/bin/javac -target 1.5 Test.java
And now, Let us try to run the generated Test.class file in both jdk 1.6 and jdk 1.5
first in jdk 1.6 -
$ $JAVA_HOME/bin/java Test
o/p: Hello Nagarjuna
in jdk 1.5 -
$ ~/jdk_5/jdk1.5.0_22/bin/java Test
o/p: Hello Nagarjuna
So, we can do cross compilation using any higher version JDK.
Try on your own
No comments:
Post a Comment