First we launch an AWS instance using Amazon Linux AMI.
Choosing Amazon Machine Image
Then, login to the instance.
SSH
As is shown on the terminal, we can run sudo yum update to apply all updates. If we enter this command, a sort of updates will be listed.
Update
Then enter “y” to continue and complete the update.

Check Java using java and javac

When we enter java and javac respectively we got two messages returned:
java & javac
For most AWS instances, there are JRE installed on them, that means we can run java program on them. However, some AWS instances do not have JDK, so that we need to install JDK manually by running:

1
yum install java-devel

Install JDK
Now we can use javac to compile our java classes.

Edit Java class using vim and execute Java program

We can use vim to create a java file on the instance. For example, we want to create a java class named “Hello.java” to print “Hello World!” on the screen. We can run the following command:

1
vim Hello.java

It will create a file named “Hello.java” under the current directory, and swith to the viewing model:
What you will see after running "vim Hello.java"
By typing i, you enter to the editing model. Now type the following codes:

1
2
3
4
5
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

Then type Esc to escape the editing model and input :w to save the content and input :q to quit.
Edit, escape, write and quite
Now we are ready to compile the java file and run it:

1
2
javac Hello.java
java Hello

Execute the Java program

Upgrade Java version on the AWS instance

In some situation we always edit the java files and compile them on our local machine, then we export them as .jar files or .war files and deploy them on the AWS instance. But if the version of Java on our local machine is higher than the instance’s, then an issure of uncompatible can be occured, which means we need to upgrade the Java version on the AWS instance. There are two things to do:

  • install the same version of Java to the AWS instance as we use on our local machine;
  • update the current Java to the new installed version;

First, if your local Java version is 1.8.0 whereas the Java version on the instance is 1.7.0:
Check Java version before installation
Run the following command:

1
sudo yum install java-1.8.0-openjdk

After install the higher version of Java, the current version is still the old one:
Check Java version after installation
Then we need to change it by using following command:

1
sudo update-alternatives --config java

Change current selection of Java
As we can see from the terminal, it asks us to enter the selection:

Enter to keep the current selection[+], or type selection number:

In this case we enter: 2, and the version of Java on the instance is switched to 1.8.0.
Check Java version after configuration