Running a Java applications via a main class

suggest 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:

java HelloWorld

Some important things to note are:

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 -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.)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Java command: java and javaw:
* Running a Java applications via a main class

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
125 Java command: java and javaw
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap