Wednesday, July 25, 2012

import package.* vs. import package.class_name

  1. import java.util.*;
  2. public class ReadArgs {
  3.     public static void main(String[] args) {
  4.         Scanner input = new Scanner(System.in);
  5.         String text = input.next();
  6.         System.out.println(text);
  7.     }
  8. }
Code 1
  1. import java.util.Scanner;
  2. public class ReadArgs {
  3.     public static void main(String[] args) {
  4.         Scanner input = new Scanner(System.in);
  5.         String text = input.next();
  6.         System.out.println(text);
  7.     }
  8. }
Code 2

When you see two codes above, you will see 1 different in the first line. What is the difference with import java.util.* and import java.util.Scanner?
  1. import java.util.* will make all classes inside the java.util package visible and can be used in the class that import the package (in this case ReadArgs class). import.java.util.Scanner will make only Scanner class will be visible in the class that import the package.
  2. There is no different performance or size after the class compiled.
  3. Better to use import package.class_name for documentation and don't forget to order by class name for readability. There are drawback for this if you don't use tools or IDE such as Netbeans or Eclipse for build the code. You will get some difficulties when delete the unused class when the application get bigger. 
So, there is no different whether you use the import package.* and import package.class_name if we see on performance, and you can use the import package.class_name for readability and documentation purpose.


References:
Packages and Import

No comments:

Post a Comment