Programming





Difference between new operator vs newInstance() method in Java

Difference between new operator vs newInstance() method in Java


by Administrator | 10-Aug-2020
Java

Tags:  Object

Share: 


 

new Operator

  • It is used when the object type is known at runtime
  • Using the new operator, we can call no-arg as well as argument constructor to create an object.
  • If the class is not available at runtime then it’ll result in NoClassDefFoundError error.

Usage

1. Student student = new Student(); // no-arg constructor
2. Student student = new Student(1, “John”); // argument constructor

newInstance() method

  • This method is located in Class class.
  • It is used when the object type is not known at runtime. It is used to create database instance for a specific database type like postgres, mySQL etc.
  • Creating object by using newInstance() will always call the no-arg constructor. If the no-arg constructor is not available it’ll result in IllegalAccessException exception.
  • If the class whose object we are going to create is not available at runtime it’ll result in ClassNotFoundException.
  • Since, the return type is an Object we need to provide a casting.

Usage

 

String str = (String) Class.forName("java.lang.String").newInstance();

 


Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.