Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between java.util.Scanner and java.util.Scanner.*

Tags:

java

// imports all classes of util package    
import java.util.*;

// imports Scanner class of util package
import java.util.Scanner;

// what does this do?
import java.util.Scanner.*;

Is Scanner a package here?

Edit: Ok so import java.util.Scanner.* imports the public nested classes. But what if there was also a package called Scanner? What would the statement import java.util.Scanner.* do then?

like image 211
abhinav pandey Avatar asked Aug 05 '13 16:08

abhinav pandey


People also ask

Does java util * Include Scanner?

Scanner is a class available in the java. util package. It is used to take input from a user for any primitive datatype (int, float, string, and so on).

What does java util * mean?

util. * is a built-in package in Java which encapsulates a similar group of classes, sub-packages and interfaces. The * lets you import a class from existing packages and use it in the program as many times you need. You can find the list of all classes, interfaces, exceptions in the official document.

What is java Util Scanner called?

The Scanner class is used to get user input, and it is found in the java.util package.

When should I use import java Util Scanner?

this means "import the Scanner class which is defined inside util folder inside the java folder". tl;dr; - imports are used to know a class you want to use. the java. util are representing the path and Scanner is the class you want to use.


1 Answers

import java.util.Scanner;

This imports Scanner (as you already know).

import java.util.Scanner.*;

This imports any public nested classes defined within Scanner.

This particular import statement is useless, as Scanner does not define any nested classes (and the import does not import Scanner itself). However, this can be used with something like import java.util.Map.*, in which case Entry (an interface nested in Map that is commonly used when dealing with maps) will be imported. I'm sure there are better examples, this is just the one that came to mind.

All of this is specified in JLS §7.5 (specifically, see §7.5.1: Single-Type-Import Declarations).


In response to the OP's edit:

Ok so import java.util.Scanner.* imports the public nested classes. But what if there was also a package called Scanner? What would the statement import java.util.Scanner.* do then?

In this case there would be a compilation error, since the package java.util.Scanner would collide with the type java.util.Scanner.

like image 62
arshajii Avatar answered Oct 18 '22 16:10

arshajii