Problems compiling “Hello World” in java on ubuntu

February 28th, 2008 | Categories: java, programming | Tags:

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


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(

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.

  1. Ajay
    February 29th, 2008 at 03:08
    Reply | Quote | #1

    The JVM that compiled your code and the that ran your code are different version. Check your PATH.

  2. admin
    February 29th, 2008 at 10:18
    Reply | Quote | #2

    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 ;)

  3. May 15th, 2008 at 17:05
    Reply | Quote | #3

    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.