Updated On: Tutorial updated and rechecked on 12th of July 2022
Views: 2,046
After trying a bit of programming in C++, I have now decided to turn my attention to learning a bit of Java.
Doing just some very basic programming in C++ has helped me get a better understanding of Java.
If you want to start programming in Java on Ubuntu and / or other Ubuntu based distribution you first need to install the correct java packages, these are:
JDK - Java Development Kit
JRE - Java Runtime Environment
To install these packges in your distribution enter the following commands
sudo apt-get install default.jdk
sudo apt-get install default-jre
Once installed enter the following command to check each installed version
java --version
Output
openjdk 11.0.11 2021-04-20
OpenJDK Runtime Environment (build 11.0.11+9-Ubuntu-0ubuntu2.20.10)
OpenJDK 64-Bit Server VM (build 11.0.11+9-Ubuntu-0ubuntu2.20.10, mixed mode, sharing)
javac --version
Output
javac 11.0.11
After that there are a variety of IDE's you can use to start writing Java Code. Some of these include Eclipse, Microsoft Visual Code Editor
I currently use Bluej which is ideal for learning Java. I can also compile and execute the code inside Bluej, but to begin with you can write some java code using a text editor in your linux distribution. Once saved you can then compile and execute your code using the terminal.
Let's create a program in Java that prints Hello Computer to the console window.
Create a new file named HelloComputer.java on your desktop.
Next copy and paste the code below and save the file
public class HelloComputer {
public static void main (String[] args) {
System.out.println("Hello Computer");
}
}
In order to compile your code manually enter the following command
javac HelloComputer.java
If there a no errors in your code, then a .class file will be generated, ie HelloComputer.class
To execute your java enter the following command
java HelloComputer
Output
You should save your .java source file with the same name as the Class Name in your code, this will make it easier to identify your code and also avoid errors when compiling.