Sunday, February 23, 2014

4 Ways To Create Object In Java

There are 4 ways to create object in java.
This is one of the most common question asked by interviewer.

1. Using new keyword

The very first and easy way to create an object in java is using  new keyword

     HelloWorld object = new HelloWorld() ;


2. Using Class.forName()

A call to Class.forName("X") causes the class named X to be  dynamically loaded (at runtime). 

    HelloWorld object= (HelloWorld )                                                                                         Class.forName("com.core.HelloWorld").newInstance();

3. Using Clone()

Clone method is used to create exact copy of an object.

    HelloWorld object = new HelloWorld() ;
    HelloWorld object1 = (HelloWorld) object.clone();

4. Using object Deserialization

Serialization is the process of converting an object into sequence  of bytes , The reverse process of creating object from sequence  of bytes is called  deserialization.

   ObjectInputStream ois =new ObjectInputStream();

   HelloWorld object = (HelloWorld)ois.readObject();