What is the difference between " import java. util.* "and" import java.util. Scanner"

Instead of Scanner, it can be anything - the point is clear. Namely: why use the second option, if the first one is shorter and will be useful when you need something else from java.util? I study Java and in many examples from books and articles on the Internet, the second import option is used, but I have never seen an explanation of why this is so. Perhaps it has some advantages over the first one?

3 answers

Because in Java, imports are needed to separate classes. It will be clearer with an example. Let's say there is a class com.blabla.Scanner and you wrote import com.blabla.*;. And then you wanted to add an import from java.util.Scanner and you wrote import java.util.*; again. In this case, if you write Scanner in the code, the compiler will not understand which Scanner you need. Full import record is not allowed

I remember once adding imports from android.support.v7.widget.* and android.widget.*;. When I wrote Toolbar the IDE just swore, since it is in both packages. Added to v7.widget.Toolbar and that's it.

 6
Author: , 2017-04-24 04:07:56

Arguments for and against both options are found in the answers to this question. There, in the comments to the answers, there is a continuous holivar about the fact that "this is not a reason to do this, but to do the opposite-there is a reason".

You can highlight such moments from there.

For importing the entire package:

  • You don't have to write a huge number of imports, and the reader can scroll through them
  • In terms of performance, there is no difference
  • Name conflicts are not common and quite simply resolved
  • "This is what the books advise you to do." As an example, is an excerpt from the book "Clean Code" by Robert C. Martin. I can't guarantee the accuracy of the passage.

For listing specific classes:

  • There are no name conflicts when importing a class from just one package. And we are talking not only about the initial development of the code, but also about the transition to a newer version of Java. The crowning example is the transition from JDK 1.1 on 1.2 and import java.util.*; with import java.awt.*; when using List.
  • Ability to understand which package a class belongs to when reading code without an IDE
  • If a class has a lot of imports, then this class probably does more than it should
  • In modern IDEs, you can hide the import block so that you don't have to scroll through them

In the end, it all comes down to the fact that everyone decides for themselves what approach to use. There is no better solution, about what, including, the endless debate on this topic testifies.

 8
Author: Regent, 2017-05-23 12:39:04

Java.util.* - import everything that is in the library import java.util. Scanner - import specifically Scanner

 1
Author: Free True, 2017-04-23 14:33:09