Reputation: 5084
why every time, everyone import (or this is not import)
Class.forName("com.mysql.jdbc.Driver").newInstance();
And when I
import com.mysql.jdbc.Driver;
It display Notice
he import com.mysql.jdbc.Driver is never used
What is the different between this two ??
Upvotes: 0
Views: 111
Reputation: 24022
When you do not actually know which class has to be loaded you go for factory methods.
In your case it is Class.forName
on a database driver class.
It is a runtime instruction to the JVM to load the class and hence the import ...
statement is not required in this case.
Where as if you use import ...
a specific class, the Java compiler tries to find and load it before using it in the class being compiled. In your example case, when you import a class and never use it in your code, usually the IDE's like MyEclipse where you are writing the code, you will be notified that the imported class never used. It is not an error or warning but you can safely remove to reduce load on compiler.
Upvotes: 3
Reputation: 10346
You do not need the import when using Class.forName
, because it uses Reflection.
Upvotes: 2