Install Java JDK 7 or 8 on Ubuntu 14.04 or later

Here is a summarised guide on installing Java JDK on Ubuntu. This guide is applicable for installing JDK 7 or 8 on Ubuntu 14.04 or later(tested till 16.04).
Download the tar file from oracle website. And in the directory containing the tar create a script file say, java_install.sh.
#!/bin/sh

tar -xvf jdk-8u121-linux-x64.tar.gz

sudo mkdir -p /usr/lib/jvm
sudo mkdir -p /usr/lib/jvm/jdk1.8.0

sudo mv ./jdk*/* /usr/lib/jvm/jdk1.8.0
sudo rmdir jdk1.8.0_121

sudo chmod -R 755 /usr/lib/jvm/jdk1.8.0

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.8.0/bin/javaws" 1

sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws

sudo mkdir -p ~/.mozilla/plugins/
ln -s /usr/lib/jvm/jdk1.8.0/jre/lib/amd64/libnpjp2.so ~/.mozilla/plugins/
sudo /etc/init.d/apparmor restart

Now run the shell script using root priviledge as follows:
sudo sh java_install.sh
This will install the Java JDK on your system and also install browser plugin for firefox. To check if this worked, run the version check command:
java -version
Note: You need to change the script file content based on the tar file version that you downloaded.

Same script modified for say, Java 7 tar file would be:
#!/bin/sh

tar -xvf jdk-7u40-linux-x64.tar.gz

sudo mkdir -p /usr/lib/jvm
sudo mkdir -p /usr/lib/jvm/jdk1.7.0

sudo mv ./jdk*/* /usr/lib/jvm/jdk1.7.0
sudo rmdir jdk1.7.0_40

sudo chmod -R 755 /usr/lib/jvm/jdk1.7.0

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1

sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws

sudo mkdir -p ~/.mozilla/plugins/
ln -s /usr/lib/jvm/jdk1.7.0/jre/lib/amd64/libnpjp2.so ~/.mozilla/plugins/
sudo /etc/init.d/apparmor restart