Java Compilation: -sourcepath and -classpath Explained - Quiz
Total: 5 questions
1. Where does java and javac look for the classes?
Where does java and javac look for the classes?
First they look in the directories with standard Java SE (J2SE) classes. Then they look in the directories defined by classpaths.
2. Where classpaths can be declared?
Where classpaths can be declared?
It can be declared as an operating system environment variable or as a command-line option.
3. What is the difference between the -sourcepath and -classpath options?
What is the difference between the -sourcepath and -classpath options?
The -sourcepath option tells the javac compiler where to look for source .java files it needs to compile. The -classpath (or -cp) option tells where to find already compiled .class files and libraries, and it is used by both javac and java.
4. Why does an error such as NoClassDefFoundError or ClassNotFoundException occur, and how can you avoid it?
Why does an error such as NoClassDefFoundError or ClassNotFoundException occur, and how can you avoid it?
It occurs when the JVM or compiler cannot find a required .class file because the directory or JAR that contains it is not listed in the classpath. To avoid it, add the needed directory or JAR to the -cp option. Remember that once you use -cp, the current directory is no longer included by default — add . explicitly if your classes are there, for example -cp .;../projectExample2/classes.
5. How do you list several directories in the -cp or -sourcepath option?
How do you list several directories in the -cp or -sourcepath option?
Put them in a single value separated by the platform path separator: a semicolon (;) on Windows and a colon (:) on Linux and macOS. For example, on Windows: -cp classes;../projectExample2/classes; on Linux/macOS: -cp classes:../projectExample2/classes.