aspose file tools*
The moose likes Beginning Java and the fly likes Different ways to import? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Different ways to import?" Watch "Different ways to import?" New topic
Author

Different ways to import?

J Burns
Greenhorn

Joined: Oct 08, 2011
Posts: 6
In the book I am using, all of the code examples have the Import statement at the top of the file before the class statement.

import java.util.Scanner;

Then inside a method in the class:

Scanner input = new Scanner(System.in);

But after doing the programing exercises and looking at the book's answers, I see this:

java.util.Scanner input = new java.util.Scanner(System.in);

I realize that they both work. I was wondering if one is more the norm than the other or maybe in some cases one is better than the other?

Thanks
Tim Moores
Rancher

Joined: Sep 21, 2011
Posts: 2408
Performance-wise and functionality-wise they're identical: they compile to the same code.

I like having the imports at the beginning, so you can see at one glance what parts of the Java API (or 3rd party libraries) a class needs. It also gets repetitious: note how in the second example you have to type the package name twice. Having the imports up front also helps the IDE help you type class names (assuming you're using an IDE).

The most common case where I don't import a class up front is if a class uses two other classes of the same name, like java.awt.List and java.util.List. That confuses the compiler, and you need to take a bit of care to get things straight. Usually I end up importing the one used more often, and fully qualify the other one each time I use it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Look in the Java Language Specification, but it isn’t easy to read.
J Burns
Greenhorn

Joined: Oct 08, 2011
Posts: 6
Thanks for the clarification, I was wondering about the different use cases.

Yes the reference was a bit of a dense read.

Thanks, Tim

As a side note. I'm sure glad I found this forum. Learning from books is fine, but sometimes a little interaction does wonders, at least for me. Thanks, again.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You’re welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Different ways to import?