Problems compiling “Hello World” in java on ubuntu
At some point in the future I am going to need to do some Java programing for work-related purposes and so I thought I should set up my Ubuntu based laptop for Java development. Everything you need to do this are in the Ubuntu repositories so the installation went without incident but I hit a brick wall when I tried to compile and run this very simple program
class myfirstjavaprog { public static void main(String args[]) { System.out.println("Hello World"); } }
I compiled this with the command
javac myfirstjavaprog.java
The .class file was produced without any problems but when I tried to run it with
java myfirstjavaprog
I got a hideous looking error message that started off like this
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:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
All that for a Hello World program! This was not a good start but it turns out that there is an easy fix. The version of Java being used by my java command was different from that being used by my javac command and they need to be the same. The commands that allow you to configure Java versions on Ubuntu are
sudo update-alternatives –config java
sudo update-alternatives –config javac
Ensure that they are set to use the same version and you should be good to go.
The JVM that compiled your code and the that ran your code are different version. Check your PATH.
Hi Ajay – thanks for your comment but I already knew that. I guess you didn’t read until the end of the post where I explained the problem and posted a fix :) I do that sometimes so nevermind ;)
You can also convince new compilers to make class files that work with older JVMs by using the -target option. Something like “javac -target 1.1 blah blah blah”. You _need_ to do this if targetting J2ME or web applets, because the JVM version has been frozen solid for years. Obviously -target some-early-version may be incompatible with newer language features, but that’s not an issue for hello world.