When we get a connection for a DB, we generally load a class using Class.forName(). I would like to know if there is a specific reason why we only use this way and not directly create an instance. The only reason that comes to my mind is that because we only need the class to be loaded and not really need an instance.
One reason is that we'd like to avoid hard-coding DB access parameters, even the name of the driver class. It is not uncommon to switch drivers; thus its name should be kept out of the source code, e.g. in some config file.
And, yes, the JDBC code does not need an instance, it only nneds to make sure that the class is loaded (which will cause it to register itself with the DriverManager).
Originally posted by Arnav Velimala: Are you sure that it is not really required to instantiate the class.
I believe in the Driver classes there will be a static block that will instantiate the class.
It helps to be precise here. What Anupam refers to as "we" is the client program, and that does not need an instance of the driver - it needs objects that implement the relevant interfaces. Of course there's an instance of the driver class being involved somewhere, but not (directly) in the client code.
You're right that loading the class will lead to the driver creating an instance of itself, as per the java.sql.Driver javadocs.
You can't have everything. Where would you put it?