Site Search:

Import other Java packages to make them accessible in your code

Back OCAJP
A java program can use lots of classes, these classed came from different sources.

java -cp ".:/tmp/my.jar:/tmp/httpcore-4.4.3.jar" Myclass

In the above example, -cp is classpath, which tells java program where to load classes. java loads classes from current directory ., my.jar (a jar made by yourselves), httpcore-4.4.3.jar (a jar made by others) and JDK.

Java uses packages to logically group these classes.


java packages
java packages


In a class, the import keyword tells the compiler which package to look in to find a needed class.

(The following hints won't be tested in OCA, but it is good to know a package name hints where the package came from. For example, if package name starts with java or javax, they came from JDK; if package name starts with org.apache, they might come from a jar file created by apache software foundation, you google the package name, find the containing jar file and download it to run your program.)

Classes in the same package are often imported together with wildcards *. 

import java.util.Locale; //import Locale class
import java.util.Date; //import Date class
import java.util.* //import Locale class and Date class and all classes in the same package

If a class came from the same package of your class or came from java default package java.lang, you don't need to import them.


package com.mypro;
import com.mypro.*; //redundant, classes is in the same package.
import java.lang.*; //redundant, java imported them by default.
class test{
  public static void main(String... args) {
    System.gc(); //System came from java.lang.System
    test2 t = new test2(); //test2 came from com.mypro.test2
  }
}


Package allow classes in different packages to have the same name. For example, java.util.Date and java.sql.Date are different classes with the same class name Date. When importing classes with the same name, we need to prevent name conflict.

The following code won't compile, because compiler can not tell if Date refers to java.util.Date or java.sql.Date.


OCAJP>cat test.java 
import java.util.Date;
import java.sql.Date;
class test {
  Date t = new Date();
}
OCAJP>javac test.java 
test.java:2: error: a type with the same simple name is already defined by the single-type-import of Date
import java.sql.Date;
^

1 error


Explicit import have precedence over wildcards import for compiler, so the following code compiles.


OCAJP>cat test.java 
import java.util.Date;
import java.sql.*;
class test {
  Date t = new Date();
}
OCAJP>javac test.java 
OCAJP>


The following code compiles, because import is not needed if we use the full class names.


OCAJP>cat test.java 
class test {
  java.util.Date t = new java.util.Date();
}
OCAJP>javac test.java
OCAJP>


Back OCAJP