This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Different ways to import?

 
J Burns
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 2683
36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48394
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look in the Java Language Specification, but it isn’t easy to read.
 
J Burns
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48394
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You’re welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic