Meet
Meet

Reputation: 242

Why Java needs classpath at runtime

In Java we set the classpath at compile time to compile Java files, but why do we need to set the classpath at runtime? Any specific reason why the JVM needs the classpath to run .class files?

Upvotes: 4

Views: 2805

Answers (5)

WineGoddess
WineGoddess

Reputation: 421

Often people think compiling makes for a stand-alone application without the need to point at dependencies. But it does not.

If your code has no dependencies, then you do not need to set a classpath.

You may need/want to include -cp at runtime:

  1. To specify where to look for third-party and user-defined files your class requires at runtime (*.jar, *.class, *.properties, etc).

  2. To override what the CLASSPATH environment variable is set to.

Upvotes: 0

The files on the classpath provide the actual executable code (in Java .class files) that the JVM needs to run.

Upvotes: 5

Morfic
Morfic

Reputation: 15518

One of the reasons that I see, is that if I need for some reasons to have the libraries required by my app scattered across multiple mountpoints/drives/partitions or even folders, I would not be able to specify to the JVM where my code is. As a workaround, the JVM could look throughout the whole file-system and index stuff, but how efficient/fast would that be?

Cheers

Upvotes: 0

user207421
user207421

Reputation: 310909

In Java we set the classpath at compile time to compile Java files

Do we? I don't.

but why do we need to set the classpath at runtime?

So the JVM knows where it can find the classes.

Upvotes: 0

Arunprasad Rajkumar
Arunprasad Rajkumar

Reputation: 1444

CLASSPATH is an environmental variable used by Java Virtual Machine to locate the class files(including main class).

Alternatively you can pass -cp or -class-path as a argument to JVM to specify the class paths where your main class depends on.

For example,

export CLASSPATH=/opt/javatv:/opt/mhp:/opt/main-class;
java MainClass

(or)

java -cp /opt/javatv;/opt/mhp;/opt/main-class MainClass;

(or)

java -class-path /opt/javatv;/opt/mhp;/opt/main-class MainClass;

Upvotes: -1

Related Questions