Install Java on AWS instance and use Java
First we launch an AWS instance using Amazon Linux AMI
.
Then, login to the instance.
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.
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:
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
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:
By typing i
, you enter to the editing model. Now type the following codes:1
2
3
4
5public 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.
Now we are ready to compile the java file and run it:1
2javac Hello.java
java Hello
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:
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:
Then we need to change it by using following command:1
sudo update-alternatives --config 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.