I'm currently refreshing my Java knowledge and came across a question I couldn't answer yet:
How does the Java compiler know where the (possibly custom) packages are located on disk? I'd assume that using built-in libraries it looks up the java library folder – but how does it find the custom ones?
Here's the file's locations for the following example:
// part of the package
com/usuallyNot/example.java
// not part of the package
com/example2.java
Is the naming convention to be seen as relative path? If it's this, why do we need to write "import package com.usuallyNot.example;" (instead of "import package "usuallyNot.example;") even if the file we write it in resides in the "com" folder?
Best Answer
The answer is the classpath:
There are instructions from Oracle how to set your classpath.
The classpath is searched in order of the folders that appear for a class matching the import. There are lots of details in how multiple classes of the same name can co-exist.
The
classpath
is set either by%CLASSPATH%
(Windows DOS shell,$env:CLASSPATH
in PowerShell) or$CLASSPATH
in Unix or in the manifest of a Jar file.You can see the future of
classpath
from the 2015 JavaOne keynot (starting @ 17 minutes).