12

Lets say , there are some import statements in a class. When the byte code is generated for that class, what happens to these import statements.

If the import statements are ignored during runtime, how are the dependencies on that classes methods resolved during runtime.

java_geek
  • 17,585
  • 30
  • 91
  • 113
  • 4
    Why not find out for yourself? Write a few variants of a class: one with reliance on outside classes, one that relies on (for instance) `java.util.List` via import, and one that relies on `List` but uses it fully qualified (without an import). Then use `javap -c` on each, and see what comes out. – yshavit Mar 13 '12 at 08:09
  • 2
    Complementary to @yshavit comment, during the compilation use `javac -g:none Foo.java` for not generating debug info (e.g. line numbers) at all in the `.class` files, then compare the generated `.class`es and they will be identical at byte level and this can be tested getting the hash for each of them. – Jaime Hablutzel Jun 01 '15 at 18:36

3 Answers3

11

The purpose of import statements is just to make life easier for the human readers (and authors) of the code. Thus they are replaced by references to the fully qualified class/method names in the bytecode. And unused import statements are ignored.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
2

import statements are only there for the compiler so it knows what class names (or static method names) you can access unqualified in your code (i.e. MyClass instead of foo.bar.MyClass). Behind the scenes this is just used to resolve to the fully-qualified class names which are then used in the bytecode as well.

Joey
  • 344,408
  • 85
  • 689
  • 683
1

import in Java is just a shorthand

so that if you import java.util.* you don't have to write java.util.ArrayList in your code but can write ArrayList

user207421
  • 305,947
  • 44
  • 307
  • 483
Hachi
  • 3,237
  • 1
  • 21
  • 29