Running a Java applications via a main classsuggest change
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 http://stackoverflow.com/documentation/java/84/java-overview/378/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:
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
javacommand must be the full classname. For instance if
SomeClassis declared in the
com.examplepackage, then the full classname will be
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 http://stackoverflow.com/documentation/java/3720/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
java -cp . HelloWorld
This says to make the current directory (which is what “.” refers to) the sole entry on the classpath.
-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
-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.)