12

What is the difference in calling the -classpath option from javac and from java

for example:

javac -classpath MyJar.jar GetJar.java
java -classpath MyJar.jar:. GetJar

it works as well as:

javac -classpath MyJar.jar GetJar.java
java GetJar

So basically where the first -classpath related to javac needs to be there, on the other hand in the java command line it might be optional. Why? Do you know in which circumstance it would be mandatory. And more in general what is the effect of -classpath called by javac and what is the effect of -classpath called by java.

Thanks in advance.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Rollerball
  • 12,618
  • 23
  • 92
  • 161

2 Answers2

11

One is the classpath used for compiling. The other is the classpath used for running. And they do not have to be the same thing. The set of classes needed for the compilation processes are all those referred to by every class being compiled. Whereas your runtime JAR could be invoking a standalone class with an empty main method and no dependencies.

Just remember that at runtime class dependencies are resolved dynamically, aka a class is only loaded when it is needed (this is a generalization, boot and system classes are always loaded).

Perception
  • 79,279
  • 19
  • 185
  • 195
  • Got it, thus if I declare a piece of code like: if (scan.nextInt()>10) new OtherClass(); only if scan.nextInt() is greater than 10, OtherClass will be loaded – Rollerball Feb 27 '13 at 20:32
  • Actually no, any reference to a class `B` within another class `A` will automatically cause class `B` to be loaded (even if it is not directly used due to conditional logic). – Perception Feb 27 '13 at 20:37
1

This document contains answers for your questions

http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/javac.html

using -classpath every time is a very time consuming work. Instead, use environment variables (if you are dealing with a package such as Java Mail)

classpath is used for compiling. Javac is the Java Compiler, where it converts your code into byte code.

When it comes to java it is used to run your Java source file/jar.

PeakGen
  • 21,894
  • 86
  • 261
  • 463