Complile & Run Java Program

Let's write our first java program and learn how to compile and run a java program. Before you proceed make sure following two points are fulfilled. If not then check our java installation page.

  1. Java Development Kit(JDK) is installed in your system
  2. Path environment variable is correctly set pointing to JDK's bin directory.

Sample Java Code

To write your first java code, follow below instructions.

  • Open notepad and write below code as it is.
  • Save the code with file name
//sample java code									
public class HelloWorld{         
	public static void main(String[] args){      
		System.out.println("Hello World");

Now your first java code is ready to be compiled & executed.

Linux or Unix users create a file named using command touch. Then open the file in vi editor and write the code and save it

Compiling Java Code

To compile your java program follow below instructions.

  • Open command prompt.
  • Go to directory where java code file is saved using cd command ex. cd C:\myjavaprograms\
  • Run command javac

That's it. Your java program is compiled now. No message will be displayed if the program compiled successfully otherwise you will get to see the error or warning message

Now you can see a .class file would have been generated in the same directory where your source code (.java) file exists ex. HelloWorld.class, This .class file is nothing but java bytecode. This bytecode will be used to run the code.

Running Java Code

Once you have compiled your code. Run it as below.

  • java HelloWorld

Note that here we did not use any extension to file name because it's not the filename what we are passing as argument to java command, it is class name which contains main method.

Online Java Compiler

There are lot of online java compilers present, where you can compile and execute your java program online. To find an online compiler search on google online java compiler. Online compilers are convenient when you are working on some other system (office, college or friend's machine). Normally for better learning we recommend to set up your own environment and write your codes on editor instead of pasting it.

Next Chapter

In next chapter you will learn your first java program