First Program & its Explanation

By | August 5, 2017

To create your first Java program, begin by creating a new file in your text editor or IDE, and save the file as HelloWorld.java. Then paste this code in that file, and save the file:

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

Note: In order for Java to recognize this as a public class (and not throw a compile time error), the filename must have the same name as the class name (HelloWorld in this example) with a .java extension and should have the public access modifier before it. Naming conventions recommend that Java classes begin with an uppercase character, and be in camel case format. This means no underscores (_) or dollar signs ($), even though these can both technically be used, and that the first letter of each word is capitalized.

To compile your code, open the directory where HelloWorld.java is located in a terminal window:

cd /path/to/containing/folder/

Note: cd is a terminal command which means change directory

and enter javac followed by the file name and extension as follows:

$ javac HelloWorld.java

Note: The javac command invokes the Java compiler.

The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual Machine (JVM). The Java programming language compiler, javac, reads source files written in the Java programming language and compiles them into bytecode class files. Optionally, the compiler can also process annotations found in source and class files using the Pluggable Annotation Processing API. The compiler is a command line tool but can also be invoked using the Java Compiler API.

To run your program, enter java followed by the name of the class which contains the main method (HelloWorld in our example). Note how the .class is omitted:

$ java HelloWorld

Note: The java command runs a Java application.

This will output to your console:

Hello, World!

You have successfully coded and built your very first Java program!

Note: In order for Java commands (java, javac, etc) to be recognized, you will need to make sure:

  • A JDK is installed (e.g. Oracle, OpenJDK and other sources)
  • Your environment variables are properly set up

You will need to use a compiler (javac) and an executor (java) provided by your JVM. To find out which versions you have installed, enter java -version and javac -version on the command line. The version number of your program will be printed in the terminal (e.g. 1.8.0_73).