Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Language Fundamentals - Import Declarations

Syntax

    import packageName.*;               // type-import-on-demand
    import packageName.ClassName;       // single-type-import
    import packageName.InterfaceName;   // single-type-import
  • the import statement is used to reference classes and interfaces declared in other packages
  • the type-import-on-demand import statement will cause the package to be searched when a type is declared for a class which has not been declared within the source file
  • duplicate type-import-on-demand statements are ignored (JLS §7.5.2)
  • the java.lang package is automatically imported in every compilation unit, it does not have to be specifically imported
  • you can access classes and interfaces from other packages without first importing them but you must use their fully qualified names For example:
    If you import the java.awt.Button class by using:
        import java.awt.*;      ,or,
        import java.awt.Button;
    
    You can create a Button by coding:
        
        Button myButton = new Button();

    Without the package import you'd need to code:

        java.awt.Button myButton = new  java.awt.Button();       
  • imported types are available to all classes and interfaces within the same compilation unit (JLS §7.5)
  • it is legal to import a single-type and a package having the same names (JLS §7.5.4)
    i.e.
        import java.util.Vector;
        import Vector.pest;         // no compile error
    

Also see

Tips

  • a single-type import will take precedence over an import-on-demand
  • import-on-demand types do not increase the size of the compiled code ie only the types actually used are added to the code
  • I've read that while import-on-demand adds no overhead to the compiled code, they can slow down the speed of the compile; however, Peter van der Linden, in Just Java 2, 4th Edition says it ain't so and my guess is he knows ... he's a kernel programmer for Sun

Traps

  • single-type imports for two classes in different packages but with the same simple name
  • single-type import with the same simple name as a class defined in the source file
  • attempting to import a package vs a type ie import java.util vs import java.util.*


Source Package Import Class Interface Constructors
  Methods main() Identifiers Keywords Defaults Arrays
  Primitives # Literals char Literal String Literals Class Literals