How many ways to create Object in Java ?

Most of Java folks creating lots of objects by calling constructor using new. But mostly developers are not aware that there are other ways to create object in Java.
Many people face this question in interview as well.

Below you can see 3 different ways to create object in Java. Other than these 3 there are two more ways to create object and that are using clone() method and using deserialization. Make note that in case deserialization there is no call to constructor. So total there are 5 ways you can create object in Java.



package com.infybuzz.core;

import java.lang.reflect.Constructor;

public class WaysToCreateObject {

 public static void main(String[] args) throws Exception {
  
  // 1. using new
  
  WaysToCreateObject first = new WaysToCreateObject();
  
  // 2. using newInstance() method on class.
  
  WaysToCreateObject second = WaysToCreateObject.class.newInstance();
  
  // 3. using newInstance() method on constructor.
  
  Constructor<WaysToCreateObject> constructor = WaysToCreateObject.class.getConstructor();
  
  WaysToCreateObject third = constructor.newInstance();
  
 }

}

If you want to prepare for Java interview then checkout below articles as well.
Java Interview Questions and Answers
Java 8 Interview Questions and Answers