Category Archives: Core Java

How Class.forName(“…”) works

When we create an instance of a class using new operator, it does two things

1. Load the class in to memory, if it is not loaded –
which means creating in-memory representation of the class from the .class file so that an instance can be created out of it. This includes initializing static variables (resolving of that class)
2. create an instance of that class and store the reference to the variable.

Class.forName does only the first thing.
It loads the class in to memory and return that reference as an instance of Class. If we want to create an instance then, we can call newInstance method of that class. which will invoke the default constructor (no argument constructor).
Note that if the default constructor is not accessible, then newInstance method will throw an IllegalAccessException. and if the class is an abstract class or interface or it does not have a default constructor, then it will throw an InstantiationException. If any exception araises during resolving of that class, it will throw an ExceptionInInitializerError.

If the default constructor is not defined, then we have to invoke the defiend constructor using reflection API.

But the main advantage with Class.forName is, it can accept the class name as a String argument. So we can pass the class name dynamically. But if we create an instance of a class using new operator, the class name can’t be changed dynamically.

Class.forName() inturn will call loadClass method of the caller ClassLoader (ClassLoder of the class from where Class.forName is invoked).

By default, the Class.forName() resolve that class. which means, initialize all static variables inside that class.
same can be changed using the overloaded method of Class.forName(String name,boolean initialize,ClassLoader loader)

The main reason for loading jdbc driver using Class.forName() is, the driver can change dynamically.
in the static block all Drivers will create an instance of itself and register that class with DriverManager using DriverManager.registerDriver() method. Since the Class.forName(String className) by default resolve the class, it will initialize the static initializer.
So when we call Class.forName(“com.sun.jdbc.odbc.JdbcOdbcDriver”),
the Driver class will be loaded, instantiated and registers with DriverManager

So if you are using new Operator you have to do the following things.

Driver drv = new com.sun.jdbc.odbc.JdbcOdbcDriver();
DriverManager.registerDriver(drv);

Major Difference Between StringBuffer and StringBuilder

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

Difference between String and StringBuffer Class

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:

String str = new String ("Nirmal ");
str += "Jatania!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:

StringBuffer str = new StringBuffer ("Nirmal ");
str.append("Jatania!!");

Programmers usually assume that the first example above is more efficient (Just like me before some days !!!) because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.

The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:

0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup
14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1

The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Nirmal ");

Then, the bytecode at location 10 through 29 is executed for the concatenation:

str += "Jatania!!";

Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.

In summary, the two lines of code above result in the creation of three objects:

A String object at location 0
A StringBuffer object at location 10
A String object at location 26

Now, let’s look at the bytecode generated for the example using StringBuffer:

0 new #8
3 dup
4 ldc #2
6 invokespecial #13
9 astore_1
10 aload_1
11 ldc #1
13 invokevirtual #15
16 pop

The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer(“Nirmal “);

The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Jatania!!");

Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

I found this useful piece of information in sun website…

Rule for Exception Handling while overriding methods

The question why makes any topic makes more clearer and interesting than just to know about what the concept is.

The rule about exceptions when we use them in overriding is:

If super class method is throwing any exception(checked) and if we are overriding that method in sub class

Then the subclass method can be declared using following rules

1. The subclass method can throw exception or may ignore the exception, the rule here is quite clear because if super class method is taking risk does not mean that sub class has to take the same risk.

for example in sub class i can write the code which may not be risky at all so we need not to handle any exception or need not to throw any.

below code explains the scenario.
class Super{
public void test() throws IOException{
System.out.println(”Super.test()”);
}
}
class Sub extends Super{
public void test(){
System.out.println(”Sub.test()”);
}
}

2. If we are throwing any exceptions those should be sub type of exceptions declared in super class method.

this rule is very interesting to discuss.

Now i will present some code which is calling Super class method test()

public class Overriding {
public static void main(String[] args) {
Super super1 = new Super ();
try {
super1.test();
} catch (IOException e) {
e.printStackTrace();
}
}
}

In overriding class i am calling the method test() using object of Super class, here the reference variable super1 is of type Super,and test() method is throwing IOException which is checked exception so either we have to handle it or declare it, here i am handling it with try and catch.

Now i decided to override the test() method is my Sub class by throwing the same exception.

class Super{
public void test() throws IOException{
System.out.println(”Super.test()”);
}
}

and i will change the way i am creating instance in Overriding class to polymorphic

Super super1 = new Sub();

Here the reference super1 is of type Super but it is actually pointing ti Sub class object

so when we say super1.test()

compiler checks whether test() method is there in super class or not of it is not there it will not compile. We have test() method in Super class and it throws checked exception so we have to surround it with try and catch

try {
super1.test();
} catch (IOException e) {
e.printStackTrace();
}

Now let me say why we have to use Same or sub type of Exception in sub class test method declaration.

super1.test() is going to call subclass method in runtime because we are using polymorphic assignment in creating super1 instance.

if sub class method is allowed to throw any super type of exceptions declared in Super class method. that is if we are allowed to throw Exception instead IOException( or its subtype). it will not fit into catch statement since catch is using exception declared in super class method that is IOException.

That is the reason we have to use same exception or its subtype.

complete code is given below.

public class Overriding {
public static void main(String[] args) {
Super super1 = new Sub();
try {
super1.test();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Super{
public void test() throws IOException{
System.out.println(”Super.test()”);
}
}
class Sub extends Super{
public void test(){
System.out.println(”Sub.test()”);
}
}

Thanks…

New Features in Java 7.0

Have a look on New Features in Java 7.0

* JSR 277 Java Module System
* JSR 294 Improved Modularity Support
* JSR 295 Beans Binding
* JSR 303 Beans Validation
* JSR 296 Swing Application Framework
* JSR 203 NIO2 JSR 220 Java Persistence APIs
* JSR 255 JMX 2.0
* JSR 262 Web Services Connector for JMX
* JSR 260 Javadoc Technology Update
* JSR 275 Units and Quantities
* JSR 310 Date and Time API
* JSR 308 Annotations on Java Types