Raspberry Pi

How to get started with Java on Raspberry Pi operating system

Many applications and games are designed in a programming language known as Java and the Java development software is supported by different platforms like Windows, macOS, and all distributions of Linux.

In Raspberry Pi, the package Java is already installed, but if it is not installed, then it can be installed using simple commands. There are two types of packages in the Raspberry Pi operating system repository which are JDK (Java Development Kit) and JRE (Java Runtime Environment). The JDK includes the JRE and the JRE includes the JVM (Java Virtual Machine) which includes the classes and binaries which are required to run the Java programs.

In this write-up, we will learn the installation and usage of Java on the Raspberry Pi operating system.

How to install Java on Raspberry Pi

To compile and run Java code we need to install Java first, for this purpose, the java package can be installed on the Raspberry Pi operating system (if it is not installed) by using the command of apt package manager:

$ sudo apt install default-jdk -y

To confirm the installation of the Java package, we will check out the version of the installed Java:

$ java --version

How to write a Java program on the Raspberry Pi

To write the script of the Java program, we will open a file with the nano editor of a name of “myfile.java” with the extension of “.java” using the command:

$ nano myfile.java

We will type the following script for simply printing the “Welcome to the LinuxHint”:

class myfile{

public static void main(String args[])

{

 System.out.println(“Welcome to the LinuxHint”);

}

}

Use the shortcut key of CTRL+S to save the file and CTRL+X to exit the editor.

How to compile the Java program on Raspberry Pi

To compile the Java code, we need a Java compiler known as the Javac and is pre-installed with the JDK package, to make sure the compiler has been installed, we use the command:

$ javac --version

After confirmation of the installation of the compiler, use the compiler javac to compile the file, myfile.java using a command:

$ javac myfile.java

After the compilation, the human-readable code is converted into the machine language which can be understandable for the CPU and it creates a file with “myfile”, so now use the java command to run the Java compiled file:

$ java myfile

Conclusion

Java is the widely used programming language in the world of the development of applications or games. Java can be used in the Raspberry Pi with the JDK package which is available in the default repository of the Raspberry Pi. In this write-up, we have installed the JDK package which includes all the tools and binaries of Java, and then learn to use the Java program by compilation and running it in the terminal.

About the author

Hammad Zahid

I'm an Engineering graduate and my passion for IT has brought me to Linux. Now here I'm learning and sharing my knowledge with the world.