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 compile the run the program.
To compile 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, JVM has to be called, the "java" command is used to acheive this (note: only filename is required here, the ".java" extension is not required):
java MyFirst
Hello World
JVM is an interpreter, so it will convert the byte-code into machine code and it will execute the program.