Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding import statements

 
Chandra Sekhar
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Which is the best practice while writting import statements?

Ex. I need only one class say File from package java.io.

Most of the time I do ...

import java.io.*; //Line 1

Is this a bad practise...Do I need to do like this always..??

import java.io.File; //Line 2

What is the difference between Line 1 & Line 2..

Thanks
Chandrasekhar S.
 
Purushoth Thambu
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Obviously Line 2 approach is the best. JVM will be easily able to resolve the references avoid ambiguous references.
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does JVM has to do with this? The compiler will throw error in case of any ambiguity.
Personally I prefer to import individual classes. But if I need to import more than 4 classes from the same package, I use the wildcard approach (import *).
 
Purushoth Thambu
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a small application it doesn't matter if you use wildcard import. In first place why do you want Compiler to resolve this ambiguous references and report back to you through an error message.

Isn't it good if we can avoid this extra step the JVM (compiler) has to take ?
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second import line will be clear to anyone who is taking over your codes. He/She would know specifically the classes that you'd imported.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fully qualified import statements are always preferred.
Increasing code maintainability for no cost is a good thing.
Increasing code readability for no cost is a good thing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic