Java -classpath option

59,634

Solution 1

Using the classpath variable it overrides the CLASSPATH of Environment variable but only for that session. If you restart the application you need to again set the classpath variable.

Solution 2

Yes. Quoted from the java(1) man page:

   -classpath classpath
   -cp classpath
          Specifies a list of directories, JAR archives, and ZIP archives to search  for  class  files.   Class
          path  entries  are separated by colons (:). Specifying -classpath or -cp overrides any setting of the
          CLASSPATH environment variable.

          If -classpath and -cp are not used and CLASSPATH is not set, the user class path consists of the cur-
          rent directory (.).

Solution 3

Either one of the options is used, not both.

Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.

...

The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

...

Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

Solution 4

The usage of -cp option will not affect the CLASSPATH environment variable.

You can try this small code snippet to check this:

public class CPTest {
    public static void main (final String[] args) {
        String cp = System.getenv("CLASSPATH");
        System.out.println(cp);
    }
}
%echo $CLASSPATH  
/home/test/:.

The output without -cp option:

%java CPTest  
/home/test/:.

The output with -cp option:

%java -cp /home/xanadu:. CPTest  
/home/test/:.

The output is same for both invocations (one with -cp and one without).

Also either the path specified in the CLASSPATH environment variable is
used or the path specified with -cp option is used. It is not a mix of both it is one of them.

This is evident from the below invocation. If the CWD (current working directory ".")
is excluded from -cp option, the JVM launcher (i.e. java) cannot find the
class file despite the CLASSPATH environment variable containing CWD (".") in it.

%java -cp /home/test CPTest
Exception in thread "main" java.lang.NoClassDefFoundError: CPTest
Share:
59,634
Zacky112
Author by

Zacky112

Updated on September 02, 2020

Comments

  • Zacky112
    Zacky112 over 3 years

    Will the use of -classpath option with java, add to or replace the contents of the CLASSPATH env variable?