How to install Java using terminal?

Solution 1:

To entirely use a (bash) shell to install e.g. Java 8u112 JRE do the following:

Download:

cd ~/Downloads
curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u112-b15/jre-8u112-macosx-x64.dmg > jre-8u112-macosx-x64.dmg

Mount:

hdiutil attach jre-8u112-macosx-x64.dmg

Install:

sudo installer -pkg /Volumes/Java\ 8\ Update\ 112/Java\ 8\ Update\ 112.app/Contents/Resources/JavaAppletPlugin.pkg -target /

Clean-up:

diskutil umount /Volumes/Java\ 8\ Update\ 112 
rm jre-8u112-macosx-x64.dmg

To install the latest Oracle JDK (at the time of writing this answer it's Java 8u121 JDK) the various paths (besides the version number) are slightly different compared to the older JRE version. The URL contains an additional directory (i.e. /e9e7ea248e2c4826b92b3f075a80e441) and the dmg file contains a .pkg file instead of an installer app:

cd ~/Downloads
curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u121-b13/e9e7ea248e2c4826b92b3f075a80e441/jdk-8u121-macosx-x64.dmg > jdk-8u121-macosx-x64.dmg
hdiutil attach jdk-8u121-macosx-x64.dmg
sudo installer -pkg /Volumes/JDK\ 8\ Update\ 121/JDK\ 8\ Update\ 121.pkg -target /
diskutil umount /Volumes/JDK\ 8\ Update\ 121
rm jdk-8u121-macosx-x64.dmg

Solution 2:

The best/safest way to install Java on macOS is with Homebrew; just type this:

brew cask install java

Or if you don’t have Homebrew installed already, just type this command first:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew cask install java