Java Language The Java Command - 'java' and 'javaw' Running a Java applications via a "main" class


When an application has not been packaged as an executable JAR, you need to provide the name of an entry-point class on the java command line.

Running the HelloWorld class

The "HelloWorld" example is described in Creating a new Java program . It consists of a single class called HelloWorld which satisfies the requirements for an entry-point.

Assuming that the (compiled) "HelloWorld.class" file is in the current directory, it can be launched as follows:

java HelloWorld

Some important things to note are:

  • We must provide the name of the class: not the pathname for the ".class" file or the ".java" file.
  • If the class is declared in a package (as most Java classes are), then the class name we supply to the java command must be the full classname. For instance if SomeClass is declared in the com.example package, then the full classname will be com.example.SomeClass.

Specifying a classpath

Unless we are using in the java -jar command syntax, the java command looks for the class to be loaded by searching the classpath; see The Classpath. The above command is relying on the default classpath being (or including) the current directory. We can be more explicit about this by specifying the classpath to be used using the -cp option.

java -cp . HelloWorld

This says to make the current directory (which is what "." refers to) the sole entry on the classpath.

The -cp is an option that is processed by the java command. All options that are intended for the java command should be before the classname. Anything after the class will be treated as an command line argument for the Java application, and will be passed to application in the String[] that is passed to the main method.

(If no -cp option is provided, the java will use the classpath that is given by the CLASSPATH environment variable. If that variable is unset or empty, java uses "." as the default classpath.)