How to Compile and Run Java program and Classpath directory

How to Compile and Run

Java class files must be compiled before running them.

To compile a Java source file , use the Java compiler (javac).

  • You can use the CLASSPATH environment variable to the directory above the location of the package hierarchy.
  • After compiling the source .java file, a .class file is generated.
  • To run the Java application, run it using the Java interpreter (java):


The default value of the classpath is the current working directory (.), however, specifying the CLASSPATH variable or the -cp command line switch overrides this value.

The CLASSPATH variable is used by both the Java compiler and the Java interpreter(runtime).

The classpath can include:

  • A list of directory names (separated by semicolons in Windows and colons in UNIX).
-The classes are in the package tree relative to any of the directories on the list.
  • A .zip or .jar filename that is fully qualified with its path name.
- The classes in these files must be zipped with the path names that are derived from the directories  formed by their package names.

Note: The directory contain the root name of the package tree must be added to the classpath. Consider putting classpath information in the command window or even in the Java command, rather than hard-coding it in the environment.

Compiling and Running : Example
  • Assume that the class shown in the notes is in the directory D:\test\com\example:

The advantage of the IDE like NetBeans is that management of the class path, compilation, and running the Java application are handled through the tools.


Consider the following simple class in a file named  in the D:\test\com\example directory:

package com.example;

public class HelloWorld{

public static void main( String args[]){


System.out.println("Hello World!");


System.out.println("Hello "+args[0]+ "!");




About Codingwelove

Recommended Posts × +


Post a Comment