Robert Rocha Robert Rocha - 4 months ago 21
Java Question

Difference between java -cp and java when running Java porgrams

This is my first time writing in Java. I copied the typical 'Hello, World!' program:

class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}


The docs say that in order to run it I have to type:
java -cp . HelloWorldApp
.

However I have seen other code samples where you only have to type
java HelloWorldApp
.

What is the difference between
java -cp . HelloWorldApp
and
java HelloWorldApp
?

Answer

-cp is a shorthand for -classpath. It tells Java what directories to search for your .class files. When you run with -cp . you tell Java to search for your classes in the current directory, which is denoted by dot .

This option implies a certain directory structure for classes outside of default package (i.e. compiled with package <something>; at the top). The option is useful when you want to run from a directory other than the current one.

More info: Oracle documentation, good third-party tutorial.

Comments