abhinav pandey
abhinav pandey

Reputation: 584

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

// 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?

Upvotes: 18

Views: 11807

Answers (2)

arshajii
arshajii

Reputation: 129537

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.

Upvotes: 18

ktm5124
ktm5124

Reputation: 12123

The asterisk after the classname imports public nested classes.

From the Java Tutorials:

Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.

import graphics.Rectangle; 
import graphics.Rectangle.*; 

Be aware that the second import statement will not import Rectangle.

Upvotes: 16

Related Questions