Compiling and running a java program

In this tutorial we will write our first java program and learn how to compile and run it.

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

Type the above java program in notepad and save with name “” in the bin folder of JDK installation directory. File name should be same as class name and extension should be .java.

Open the Command Prompt and navigate to bin folder of JDK installation directory. (In my system, it is C:\Program Files\Java\jdk1.8.0_241\bin)

Use CD command to go to bin folder of JDK installation directory.

>CD C:\Program Files\Java\jdk1.8.0_241\bin

Compiling java program

Then type javac command on command prompt. javac command is used to compile any java files. Also, add file name as an argument to the javac command. Adding .java extension to the file name is mandatory. your command will look something like below command.

C:\Program Files\Java\jdk1.8.0_241\bin>javac

After that, press enter on keyboard. If your java file contains any compilation errors, compilation will be failed and list of errors will be displayed on the console. If  your java file does not contain any compile time errors, compilation will be successful and .class file will be generated in the same folder.

Running java program

Now you need to run this generated .class file to get the desired output. You can run this .class files in command prompt. Now type below command for running you java application.

C:\Program Files\Java\jdk1.8.0_241\bin>java Hello

Just pass name of generated .class file as an argument to java command.

If you notice one thing here, you are running commands javac and java from bin folder of JDK installation directory. And both our .java file and .class file are in same folder. Now, it us easy to compile and run your program from the same folder as that of javac and java command.

But how to compile and run the java files which are saved in another folder other than bin folder of JDK installation directory? We will see that in our next topic.

Leave a Reply