If I just use HashMap in my class, I can always just import java.util.HashMap.
If I am using more classes from a util package, I can say java.util.* / import all the classes individually as above.
I saw code which uses 10 classes from util and the developer had imported all classes individually.
If I import the whole package, all classes in the package are available to my class.
What happens when I import the whole package. Will all the classes are loaded into JVM?
So is it a good idea to import whole package / for optimizing reasons import classes individually.
Which one is better?
No, nothing will be loaded. It's just a way of telling the compiler where to look for the classes you're using. Some people prefer to import every class individually.
Personally, I use 'mass import' for the well known standard packages. You may expect from any Java programmer worth their salt that they can find a Map in java.util, an InputStream in java.io and a Socket in java.net.
Classes I've written myself, or that are otherwise not found in these packages I mostly import individually.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Importing is a compile time mechanism. It doesn't make any classes being loaded at runtime. Only classes you actually use are loaded. Importing only allows you to write HashMap in your code instead of java.util.HashMap.
As for which one is better: both are. It all depends on your preferences. There are people (and I am one of them) that like to specify each import individually. This has two advantages:
1) it's a bit clearer from which package a used class comes
2) you prevent ambiguities
Let me clarify the second with an example:
If you always specify the imported classes individually (I let Eclipse handle it ) you don't get this problem.