Java is built using the “Write Once Run Anywhere” (WORM) principle. Which mean that a java program once compiled can run on any system which has the Java Virtual Machine (JVM). This allows for the development of cross-platform applications that can run on Windows, Linux, Mac etc. This is one of the major reason why Java is considered to run on more than 3 billion devices worldwide.

In this article we are going to learn how to compile a Java program.

You need the java development kit installed to compile Java. You can check whether you have Java installed by the following command.

java -version

it should give the following output, ensuring that java is installed.

This is a simple hello world program in Java

Type the code in any editor such as notepad or sublime text and save it with the name “Hello.java”.

The name of the file should be same as the public class name that’s why the file name is “Hello.java”.

Open the command prompt or windows PowerShell in the directory of the “Hello.java” file.

Type the following command to compile the java program.

If it compiles successfully, there would be no errors and the cursor will appear.

If you get the following error

‘javac’ is not recognized as an internal or external command, operable program or batch file.

It means that either you don’t have java installed or your path variable is not set for the java installation.

If the compilation completed successfully, it will produce a ‘class’(byte code) file with the name ‘Hello.class’.

We can now run our java program using the java command followed by the name of the class.

// Output: Hello World

How a Java program is compiled and run?

In Java, programs are not compiled into executable files; they are compiled into bytecode (as discussed earlier), which the JVM (Java Virtual Machine) then executes at runtime. Java source code is compiled into bytecode when we use the javac compiler. When the bytecode is run, it needs to be converted to machine code.

How do I run a Java class file?

  1. Replace path by typing cmd and press enter.
  2. Command Prompt Directory will pop up containing the path file like C:/blah/blah/foldercontainJava.
  3. Enter javac javafile.java.
  4. Press Enter. It will automatically generate java class file.