4

Many times I'm writing my java code, import statements be like

import java.util.Scanner;
import java.util.ArrayList;

But when it is required to import more classes from java.util (or any other package), is there a way to import all the required classes in one line.

Like the code below

import java.util.Scanner,ArrayList;     OR
import java.util.{Scanner,ArrayList};

Anyhow the above two lines didn't work. Is there a way to do so ?

  • You can use import all statment, like `import java.util.*;` – Programmer Jun 23 '21 at 14:35
  • Use `import java.packageName.*`; It will import all the classes in that particular package. – GURU Shreyansh Jun 23 '21 at 14:35
  • 2
    No, there is no way to do so. Actually, the import statements are designed that way in Java. However, as many people stated, you can do a wildcard import, but [I am not a big fan of these due to reasons](https://stackoverflow.com/questions/147454). Since IDEs like Eclipse automatically reduce the import block and allow you to add a dependency in a quick way, it doesn't matter bothering with it. – maio290 Jun 23 '21 at 14:38
  • 1
    Most people program with IDEs such as Eclipse or Intellij. Those IDEs do imports automatically for you. So this is not really a problem in practice. Maybe just get started using an IDE and this issue will be gone for you as well. – Zabuzard Jun 23 '21 at 14:45

2 Answers2

1

Java language does not support that.

As far as importing top level classes is concerned, you have two options:

import package.path.ExactClass

or

import package.path.*

First one imports one and only one class, second one is wildcard import that imports all classes in that package.

SadClown
  • 648
  • 8
  • 16
0
import package.name.Class;   // Import a single class, 
                             // "its called Importing a Package Member"

import package.name.*;       // Import the whole package,
                             // its called "Importing an Entire Package"

For your case,

import java.util.*;

Learn more at official doc

VedantK
  • 9,728
  • 7
  • 66
  • 71
  • If one were to be dogmatic, it's not was OP was asking. Also, doing Wildcard imports is bad. Especially if you do these for various packages. Neither of the answers is actually stating the implications, which I'd find downvoteworthy in this case, since it's a bad practice. – maio290 Jun 23 '21 at 14:41
  • Sorry @maio290, but facts dont change because of personal choice. – VedantK Jun 23 '21 at 14:44