Import on Demand

In Java, there are two ways of importing classes: by importing the class directly, or by using what we call import on demand. Import on demand uses the * wildcard:

import java.util.*;
import java.io.*;

A class belonging to a package imported on demand will be loaded only if it is actually referenced in the code, so there is no impact on the size of the resulting app. There is also no impact on the execution performance.

The reason for this is that when compiling a class, all the import-on-demand statements are actually replaced with the class import. This is very obvious when compiling a class, and then decompiling it. Say you have the following class:

import java.util.*;

public class TestImport {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
  }
}

This class only uses java.util.List and java.util.ArrayList in the java.util package. Once decompiled, here is what the class looks like:

import java.util.ArrayList;
import java.util.List;

public class TestImport
{

    public TestImport()
    {
    }

    public static void main(String args[])
    {
        ArrayList arraylist = new ArrayList();
        arraylist.add(Integer.valueOf(1));
        arraylist.add(Integer.valueOf(2));
    }
}

The two classes are now imported directly (we talk about “single type import”). So the class you would execute would be identical to the one written with single type imports, therefore no impact on performance is to be expected. The only impact would potentially be on compilation time, but I must admit (a) I never got the chance to actually measure the delta, which is more than likely negligible anyway, and (B) I don’t really care.

 
---

Comment

your_ip_is_blacklisted_by sbl.spamhaus.org

---