First Java Program

The following program is a basic "Hello World" program. The "Hello World" program is a famous first program that most programmers would have written as their first program. To write our first program, we will use any text editor such as Vim, Emacs, Nano, Notepad++ to write the following program:

import java.lang.*;

class MyFirst {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

There are multiple ways to compile the program, in this case, the terminal will be used to compile and run the program.

To compile the program, the "javac" (javac means Java compiler) command is used:

javac MyFirst.java

If the program is error free, then it will be compiled. After compilation, a new file called "MyFirst.class" is created. This file is generated by the compiler, it is called byte-code. Byte-code is a compiled file (error free file). it is not machine code, it is just byte-code.

The ls command can be used to see this file:

ls
drwxr-xr-x 2 eric users 4.0K Sep 15 15:47 .
drwxr-xr-x 4 eric users 4.0K Sep 15 15:51 ..
-rw-r--r-- 1 eric users  419 Sep 15 15:47 MyFirst.class
-rw-r--r-- 1 eric users  136 Sep 14 15:13 MyFirst.java

To run the program, the JVM has to be called, the "java" command is used to achieve this (note: only filename is required here, the ".java" or ".class" extension is omitted):

java MyFirst
Hello World

The JVM is an interpreter, so it will convert the byte-code into machine code and it will execute the program.

Worth noting that in newer versions of Java, there's no need compile and run the program separately, the java command alone will do both.

In Java 11, the source file can be executed directly without compiling it with the javac command. However, this only works for single-file programs without external dependencies. Also, the ".class" file is not saved to disk as the compilation happens in memory; and the first class must contain the public static void main(String[] args) method.

In Java 22, the feature was extended to support multi-file programs, allowing multiple ".java" files together without pre-compilation.

java MainFile.java DependencyFile.java