Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an unused import declaration eat memory, in Java?

Does an unused import like so - import android.widget.RelativeLayout; eat memory? Just want to know about how much or just is it valuable? Maybe this is stupid question, but I haven't found answer.

like image 310
Ken Shiro Avatar asked Aug 09 '13 18:08

Ken Shiro


People also ask

What is the impact of unused imports in Java?

Unused imports have no performance impact at runtime.

Do imports slow down Java?

No. Imports are purely a compile time construct ... syntactic sugar. The imports tell the Java compiler how to map identifiers in the source code to fully qualified class names.

What is unused import statement Java?

The import statement is unused when you enter it, because you haven't yet entered the code that uses the import. This is correct and you should not worry about it. Once you enter the code that uses the import, it will no longer be highlighted as unused.

How do you fix an unused import in Java?

1) Go to the line of unused import, press Ctrl + 1, which is an Eclipse shortcut of a quick fix. This will show a drop-down menu to fix this error and one of them will be "remove unused imports." It will remove that import statement from Java file.


2 Answers

No they don't take any memory. Imports are just used by compiler to resolve class names at compile time.

Compiler changes each class name to fully qualified name. And removes the import statement. So, the import statement doesn't make it to byte code.

The only issue that can come up with wildcard import is namespace conflict, i.e., when two types with the same name is defined in two different packages, then importing those packages with wildcards will cause name conflict for that type used.


To see how compiler replaces the import statement, you can generate the byte code of your class using javap command. Consider the below code:

import java.util.*; import java.util.regex.*;  public class Test {     public static void main(String[] args) {      } } 

Just compile the above code, and check the byte code using the following command:

javap Test 

It gives out following output:

public class Test {   public Test();   public static void main(java.lang.String[]); } 

So, you can see that String type is replaced with it's fully qualified name java.lang.String, and there is no import statement in byte code.

like image 163
Rohit Jain Avatar answered Sep 24 '22 23:09

Rohit Jain


No, compiler removes them after compilation. But two issue you may face

  1. code clutter
  2. If you import some classes from jar and later removed jar but not imports, then you may get compile time error
like image 35
kosa Avatar answered Sep 25 '22 23:09

kosa