• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Difference between new operator vs newInstance() method in Java

October 15, 2019 by javainterviewpoint Leave a Comment

In this article, we will learn the difference between new operator vs newInstance() method. In general, the new operator is used to create the object if you know the type of the object at the beginning itself, but if you don’t know the type of the object at the beginning and if it is passed at the Runtime then we need to go with newInstance() method.

Difference between new operator vs newInstance() method in Java

new operator vs newInstance method

Before getting into the difference between new operator vs newIntance() method, let’s get some basic understanding of them.

new operator in Java

First of all, new is an operator in Java, it creates a new object of a type that is known beforehand and allocates memory dynamically for the object

Below goes the syntax to use the new keyword

ClassName reference = new ClassName

The ClassName is the name of the class for which the object needs to be created and reference is the variable that refers to the created object. ClassName followed by parenthesis determines the constructor which will be called.

Let’s now try to create an object for Test class using new keyword

package com.javainterviewpoint;

public class Test
{
    public Test()
    {
        System.out.println("Test class no-args Constructor called!!");
    }

    public static void main(String args[])
    {  
        Test t = new Test();
        t.disp();
    }  
    
    public void disp()
    {
        System.out.println("Disp() method of Test class");
    }
}

Upon the creation of object, the no-args constructor will be called.

Constructor with the new operator

The new keyword can call any constructor no-args or parameterized constructor. Let’s now remove the no-args constructor in the above code and write a parameterized constructor.

package com.javainterviewpoint;

public class Test
{
    public Test(int i)
    {
        System.out.println("Test class Parameterized Constructor called!!");
    }

    public static void main(String args[])
    {  
        Test t = new Test(10);
        t.disp();
    }  
    
    public void disp()
    {
        System.out.println("Disp() method of Test class");
    }
}

We had no issues in calling the parameterized constructor using the new keyword.

newInstance() method in Java

newInstance() method is present in java.lang.Class is used to create a new instance of the class dynamically.

Imagine a situation where you load classes dynamically from a remote source and you will not be able to import those classes during compile-time. In those cases we will not able to use the regular new keyword to create the object, we have to go only for the newInstance() method.

Every Java developer should have come across this, have you ever connected to the database to perform any operation?

If yes, then you should have come across this approach. We will be using Class.forName() to load the class dynamically and using the newInstance() method on top of it to create the object dynamically.

Let’s now try to create an object for the Test class dynamically using the newInstance() method.

package com.javainterviewpoint;

public class Test
{
    public Test()
    {
        System.out.println("Test class no-args Constructor called!!");
    }

    public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException
    {  
        Test t = (Test)Class.forName(args[0]).newInstance();
        t.disp();
    }  
    
    public void disp()
    {
        System.out.println("Disp() method of Test class");
    }
}

We will have to pass the class name with the fully qualified path as a command-line argument.

javac Test.java

java Test com.javainterviewpoint.Test

Constructor with newInstance() method

Unlike the new operator which can call both no-args and parameterized constructors, but the newInstance() method will only be able to call only the no-args constructor when a class has only parameterized constructors we cannot use newInstance() method.

If there is no no-args constructor and if we still used the newInstance() method to create an object, then we will be getting the below exception

Exception in thread "main" java.lang.InstantiationException: com.javainterviewpoint.Test
	at java.lang.Class.newInstance(Class.java:427)
	at com.javainterviewpoint.Test.main(Test.java:12)
Caused by: java.lang.NoSuchMethodException: com.javainterviewpoint.Test.()
	at java.lang.Class.getConstructor0(Class.java:3082)
	at java.lang.Class.newInstance(Class.java:412)
	... 1 more

Test.java

package com.javainterviewpoint;

public class Test
{
    public Test(int i)
    {
        System.out.println("Test class Parameterized Constructor called!!");
    }
    
    public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException
    {  
        Test t = (Test)Class.forName(args[0]).newInstance();
        t.disp();
    }
    
    public void disp()
    {
        System.out.println("Disp() method of Test class");
    }
}

Let’s now put every possible difference between new operator and newInstance() method in a tabular form

new Operator newInstance() method
Operator in Java Method present in java.lang.Class
new operator can be used to create an object if we know the type of object beforehand newInstance() method can be used to create an object if we doesn’t know the type of object beforehand and we will be getting at runtime
Can call any constructor such as no-args constructor and parameterized constructor Can call only the no-args constructor and it is mandatory to have a no-args constructor
At runtime, if the .class file is not available, then we will be getting NoClassDefFoundError At runtime, if the .class file is not available, then we will be getting ClassNotFoundException

Other interesting articles which you may like …

  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method
  • Java Constructor.newInstance() method Example
  • Parameterized Constructor in Java
  • Sort Objects in a ArrayList using Java Comparator
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Difference between equals() and ==
  • Difference Between Interface and Abstract Class in Java
  • Difference between fail-fast and fail-safe Iterator
  • Difference between Enumeration and Iterator ?
  • Difference between HashMap and Hashtable | HashMap Vs Hashtable
  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?

Hope I have covered some of the key difference between new operator vs newInstance() method. Happy Learning !!

Filed Under: Core Java, Java, Java Interview Tagged With: new keyword, new operator, new operator vs newInstance() method, newInstance(), newInstance() method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·