Clear the Java mucky muck from Ubuntu

Java on Ubuntu

This article is for Java developers who use Ubuntu as a development platform who wants to install Sun’s range of tools manually, instead of installing it with Synaptic/aptitude/apt-get. The commands in this article were tested on Ubuntu 8.04 “Hardy Heron” and assumes knowledge of the Debian alternatives system.

The benefits of installing it manually are that you choose:

  • which exact version of the JDK you install
  • which tools you enable, e.g. jhat

Cleaning up

Depending on what you’ve installed before, you may be left with a mixture of non-Sun tools, like gcj or the Eclipse Java compiler. We’re going to remove these, install our own, then tell Ubuntu where to find the newly installed tools.

The below is just a sample of things that may or may not be installed on your machine. Use Synaptic Package Manager instead, and search for “java” and remove accordingly.

sudo aptitude remove -y sun-java6-jdk sun-java6-jre sun-java6-bin sun-java6-plugin

You may need to completely remove the historical alternatives:

update-alternatives --remove-all java
!!:gs/java/jar/
!!:gs/jar/javac/
!!:gs/javac/javah/
!!:gs/javah/javap/
!!:gs/javap/javaws/
!!:gs/javaws/jconsole/
!!:gs/jconsole/jhat/
!!:gs/jhat/jinfo/
!!:gs/jinfo/jmap/
!!:gs/jmap/jps/
!!:gs/jps/jvisualvm/

As you can see, not only do I use java and javac, but also jhat, jvisualvm, etc.

I’m going to digress and explain the commands I used in the code snippet above. !!:gs/A/B/ means repeat the previous command, but replace A with B, all occurrences, as opposed to ^A^B which will only replace the first occurrence. You can find more weird and wonderful commands at commandlinefu.com.

Install

Install the JDK. For this discussion, let’s set the JAVA_HOME environment variable to the location where you installed the JDK, e.g. JAVA_HOME=/opt/jdk/jdk1.6.0_14.

Tell the alternatives system where it can find the new utilities:

update-alternatives --install /usr/bin/java java ${JAVA_HOME}/bin/java 50
!!:gs/java/jar/
!!:gs/jar/javac/
!!:gs/javac/javah/
!!:gs/javah/javap/
!!:gs/javap/javaws/
!!:gs/javaws/jconsole/
!!:gs/jconsole/jhat/
!!:gs/jhat/jinfo/
!!:gs/jinfo/jmap/
!!:gs/jmap/jps/
!!:gs/jps/jvisualvm/

And a quick test:

$ java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode)

You can now do the same with your other tools, like Ant and Maven.