4

I am new to java. I want to know when I write

import {SOME_PACKAGE_NAME}

where does it search for the folder? Is there any general folder or mapping file where it search for given package?

ZINDA ROBOT
  • 280
  • 2
  • 15
  • It searches in the classpath – BackSlash Sep 04 '15 at 14:23
  • 1
    It searches directories specified in classpath (argument you passed with `java` command), or `yourJavaRuntimeEnvironment/lib/rt.jar` (for standard classes like `java.util.List`). – Pshemo Sep 04 '15 at 14:23
  • 1
    @Pshemo not `java` but `javac`. Runtime knows nothing about imports. – Marko Topolnik Sep 04 '15 at 14:32
  • Wiki page of interest to read: https://en.wikipedia.org/wiki/Classpath_%28Java%29 . Be careful with "I'm new to Java" type of questions though; the chance is immensely high that whatever question you have to ask is already asked before. – Gimby Sep 04 '15 at 14:39
  • thanks for the suggestion.. but i tried to search it but may be i did not know the exact words to search.. @Gimby – ZINDA ROBOT Sep 07 '15 at 07:41

2 Answers2

5

All the directories of your project and from Jar's will be added to class path. From there classes being imported from the classpath.

You will see errors if compiler doesn't found them at compile time.

If they are not found at runtime ClassNotFoundException's/NoClassDefFoundError's based on the case occurs.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

Imports in Java don't have the same semantics as require or similar in dynamic languages. They do not point to folders or modules; they are just used for type name resolution: to convert a simple name into a fully qualified name. It is equivalent to use the full name in code:

new java.util.ArrayList<>();

Where the compiler will locate the definition of java.util.ArrayList or any other class is not specified and in practice it will be either in the JRE library, a JAR added to the compiler's classpath, or inside the same source code project as a .java file.

Note particularly that the location of the class during compilation may be completely different than at runtime: when you compile code for a Java EE container, locally you'll have an archive of the Java EE interfaces to refer to, but at runtime these will be classes provided by the container.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436