What is the difference between creating String as new() and
literal?
When we create string with new() Operator, it’s
created in heap and not added into string pool while String created using
literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not put
the object in String pool , we need to call String.intern() method which is
used to put them into String pool
explicitly. its only when you create String object as String literal e.g.
String s = "Test" Java automatically put that into String pool.
What does Class.forName() method do?
Method forName() is a static method of
java.lang.Class. This can be used to dynamically load a class at run-time.
Class.forName() loads the class if its not already loaded. It also executes the
static block of loaded class. Then this method returns an instance of the
loaded class. So a call to Class.forName('MyClass') is going to do following
·
Load the class MyClass.
·
Execute any static block code of
MyClass.
·
Return an instance of MyClass.
JDBC Driver loading using Class.forName is a good
example of best use of this method. The driver loading is done like this
Class.forName("org.mysql.Driver");
All JDBC Drivers have a static block that registers
itself with DriverManager and DriverManager has static initializer method
registerDriver() which can be called in a static blocks of Driver class. A
MySQL JDBC Driver has a static initializer which looks like this:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch
(SQLException E) {
throw
new RuntimeException("Can't register driver!");
}
}
Class.forName() loads driver class and executes the
static block and the Driver registers itself with the DriverManager.
Visit:www.sssedu.inhttp://sssedu.in/java-training-in-chennai.html
No comments:
Post a Comment