What does Java do when we import packages several times into one class?

Try this piece of code. It compiles.

import java.io.*; import java.io.*; import java.io.*; import java.util.*; import java.util.*; import java.util.*; import javax.swing.*; import javax.swing.*; import javax.swing.*; public class ImportMultipleTimes { public static void main(String[] args) { System.out.println("3 packages imported multiples times in the same class."); } } 

Does the compiler just ignore additional import statements?

+4
source share
1 answer

Yes, it will be considered a redundant compiler, as indicated by JLS 7.5.2 :

Two or more on-demand import-type declarations in the same compilation unit can name the same type or package. All but one of these statements are considered redundant; the effect is as if this type was imported only once.

Note:

  • "type-import-on-demand" is the package import somepackage.*; : import somepackage.*;
  • the same applies for import of the same type : "If two declarations with the same type of import [...] try to import the same type [...], the duplicate declaration is ignored."
+12
source

All Articles