For old ubuntu distribution
If you have ubuntu with distribution 8.10 or below, you can install it only by typing
$sudo apt-get install sun-java6-jdk sun-java6-jre sun-java6-bin
After hardy distribution, Sun (Oracle) Java JDK is no longer distributed in default repositories. So if you do apt-cache search sun-java6-jdk it would return nothing. Maybe they decided to put openjdk as default replacement. But for some reason, i prefer sun-jdk which is faster and more mature than openjdk.
Check another java jdk installation
Please check it first, if you have openjdk installed please remove it or alternate it with default sun-jdk.
$ sudo dpkg -l | grep openjdk
Download java jdk from oracle site
Download java-jdk from Java SE Downloads page and pick your java version. For example i choose java 6 update 30, and you’ll be redirected to download link. Click “Accept License Agreement” radio button like in the picture and then click on java distribution for your machine.
Install the JDK
Move downloaded file to /usr/local/jvm and give execution permission.
$ sudo mkdir /usr/local/jvm
$ sudo mv /home/user/Downloads/jdk-6u30-linux-i586.bin /usr/local/jvm
$ cd /usr/local/jvm
$ sudo chmod +x jdk-6u30-linux-i586.bin
$ sudo ./jdk-6u30-linux-i586.bin
Then create symbolic link for the folder into latest folder so you only have to update the symbolic link if a newer JDK coming.
$ sudo ln -s jdk1.6.0_30 /usr/local/jvm/latest
You can delete installation binary after installation done
$ sudo rm jdk-6u30-linux-i586.bin
Setup environment variable
Add two variables of JAVA_HOME and JRE_HOME into /etc/environment matching your previous setup folder. Extend path by adding bin folder in the java setup folder (/usr/local/jvm/latest/bin). Notice that each folder path separated by colon.
JAVA_HOME="/usr/local/jvm/latest"
JRE_HOME="/usr/local/jvm/latest/jre"
PATH="/usr/local/jvm/latest/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
save and close the file, logout and login again to update your system. Or you can type this without logout
$ source /etc/environment
Test your java jdk
Type this to check your environment path
$ echo $JAVA_HOME
and it should display your current java folder. Type this command to check java version
$ java -version
it will display
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) Server VM (build 20.5-b03, mixed mode)
If you cannot run this command, then you probably have some problem on installation file or environment setup.
Test your java program
$ vi HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!!");
}
}
Save and close the editor. compile it with javac and run it
$ javac HelloWorld.java
$ java HelloWorld
It will display
Hello World!!