As per my knowledge, Class.forName() does dynamic loading of class mentioned in parameters but I am confused how the loaded class gets linked to this statement “DriverManager.getConnection(conn url, uname, pswd)” .
Also I want to know whether Class.forName can be used for any own created class because as per my understanding, “Class.forName(my own class)” and the object created using the new operator like Class a = new Class() differ only in the loading. One is static loading and the other one being lazy loading(dynamic)..
Does loading a class in JVM takes memory or not?
Can anyone please clarify my doubt or correct me if I am wrong…
Class.forName(...) indeed makes Java load the class that you specify dynamically. When the driver class is loaded, its static initializer blocks are executed. The driver class has a static initializer to register the driver with JDBC, so that when you call DriverManager.getConnection, JDBC knows where to find the driver for the URL that you specify.
You can use Class.forName(...) also for your own classes, and your understanding is correct. The advantage of Class.forName(...) is that the class that you are loading does not need to be known at compile time (it doesn't have to be in the classpath at compile time). This can be very useful for software that works with plug-ins, because you don't know in advance what plug-ins are going to be used.
Loading a class does cost memory, because the JVM has to store the content of the class (the bytecode of the methods etc.) in memory. But it doesn't matter if you load the class statically or dynamically, both will cost (approximately) the same amount of memory.