Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

new Keyword in Java

Last Updated on April 17, 2023 by Prepbytes

Java is an object-oriented programming language and object creation is a fundamental aspect of object-oriented programming. The new keyword in Java is an essential part of creating objects. Let’s learn how the new keyword in Java is used to create objects, what happens when an object is created using the new Keyword in Java, and some important things to keep in mind when using the new Keyword in Java to create objects. We will also discuss some examples for a better understanding of the topic.

What is new Keyword in Java

The new keyword in Java is used to create an instance of a class, also known as an object. It is used to allocate memory for an object and call the constructor of the class to initialize the object’s state.

The new keyword is followed by the constructor of a class, which sets the initial values for the object’s fields and performs any other necessary setup. The constructor is a special method that is called automatically when an object is created. Without the new keyword, an object cannot be created and the constructor cannot be called.

Syntax of new Keyword in Java

ClassName objName = new ClassName();

Process of Object Creation in Java

The process of object creation in Java involves several steps:

  1. Declare a variable: A variable is declared with the class type of the object that needs to be created. The variable does not hold the object itself, but it holds the reference to the object.

    Syntax:

    ClassName objName;
  2. Allocate memory: The new keyword is used to allocate memory for the object on the heap. The memory is reserved for the object’s fields and methods.

    Syntax:

    ClassName objName = new ClassName();
  3. Initialize the object: The constructor of the class is called to initialize the object’s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup.

Here is an example of the process of object creation in Java:

Code:

class Person {
    String name;
    int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

class Main{
    public static void main(String args[]){
        Person person1 = new Person("PrepBuddy", 21);
        System.out.println("Name of person is " + person1.name);
    }
}

Output:

Name of person is PrepBuddy

In this example, the class "Person" has a constructor that takes a two arguments of type String and integer. To create an object of this class, you have used the "new" keyword followed by the constructor which creates a new object of the class "Person" and assigns it to the variable "person1". The constructor assigns the value to fields named name and age. And then we have printed the name of “person1”.

Points to Remember about new Keyword in Java

Here are some important points to remember about the new keyword in Java:

  • The new keyword in Java is used to create an instance of a class, also known as an object.
  • The new keyword in Java is used to allocate memory for the object on the heap, the memory space where objects are stored.
  • The new keyword in Java calls the constructor of a class to initialize the object’s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup.
  • The new keyword in Java also allows for dynamic memory allocation, it can be used to create arrays dynamically, which means the size of the array can be determined during runtime.
  • The new keyword in Java returns a reference to the object that was created, this reference can be stored in a variable and it can be used to access and interact with the object.
  • When creating an object with the new keyword in Java, the object is created on the heap, and it will remain in memory until it is no longer reachable by any reference in the code, at that point, it will be eligible for garbage collection.

What is the use of new Keyword in Java

Here are the some of uses of new keyword in Java:

  • Memory Allocation: The new keyword is used to allocate memory for an object on the heap, the memory space where objects are stored in Java. Without the "new" keyword, an object cannot be created and there would be no memory allocated for it.
  • Object Initialization: The new keyword in java also calls the constructor of a class to initialize the object’s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup. Without the "new" keyword, the constructor cannot be called and the object would not be properly initialized.
  • Object Polymorphism: The new keyword in java is used to create instances of subclasses that inherit from a superclass, the runtime type of the object will be the type of the subclass, making the object able to use the method overridden by the subclass and not the one inherited from the superclass.
  • Dynamic Memory Allocation: the new Keyword in Java can be used to create arrays dynamically, which means the size of the array can be determined during runtime.

Examples of new Keyword in Java

Let us understand the working of new keyword in Java with the help of following examples:

Example 1 of new Keyword in Java
Let’s look at a straightforward example of creating an object with the new keyword and calling the method with the corresponding object reference.

Code:

class Prepbytes{
    void display(){  
        System.out.println("Invoked Method");  
    }  
      
    public static void main(String[] args) {  
        Prepbytes obj = new Prepbytes();  
        obj.display();  
    }  
}

Output:

Invoked Method

Explanation: In the above example, we have created a new object using the new keyword in java and we have invoked the method using the corresponding object reference.

Example 2 of new Keyword in Java
Example of creating an object with the new Keyword in Java and calling the constructor with the corresponding object reference.

Code:

class Person{
    Person(){
        System.out.println("Constructor is called");
    }
}

class Main{
    public static void main(String args[]){
        Person p = new Person();
    }
}

Output:

Constructor is called

Explanation: In the above example, we have instantiated a new object of class “Person” and initialized it using the default constructor “Person()”.

Example 3 of new Keyword in Java
Example of Creating a new Object using new Keyword in Java and invoking the parameterized constructor.

Code:

class Person {
    String name;
    
    Person(String name){
        this.name = name;
    }
}

class Main{
    public static void main(String args[]){
        Person person1 = new Person("Prepbytes");
        System.out.println("The name of Person1 is " + person1.name);
    }
}

Output:

The name of Person1 is Prepbytes

Explanation: In the above code, we have instantiated a new object of class “Person” using the parameterized constructor and passed the name of the person.

Example 4 of new Keyword in Java
Example of usage of new Keyword in Java in creating an Array Object.

Code:

class Main{
    public static void main(String args[]){
        //instantiation of array object
        //using new keyword
        int arr[] = new int[5];
        
        //initialisation of array 
        for(int i=0; i<5; i++){
            arr[i] = i;
        }
        
        System.out.println("The value of element at index 3 is " + arr[3]);
        
    }
}

Output:

The value of element at index 3 is 3

Explanation:In the above example, we have instantiated an array object using the new keyword in Java. Then we initialized the array object with values using the “for” loop.

Example 5 of new Keyword in Java
Example of usage of new Keyword in Java with Collections Framework.

Code:

import java.util.*;  
  
public class Main {  
    public static void main(String[] args) {  
        ArrayList<String> list = new ArrayList();  
        list.add("Prebytes");  
        list.add("CollegeDekho");    
        System.out.println(list);  
    }  
      
}

Output:

[Prebytes, CollegeDekho]

Explanation: Here, we have instantiated an object of type “ArrayList” which is present in the Collections Framework using the new keyword in Java.

Conclusion
The new keyword in Java is used to create an instance of a class, also known as an object. It is used to allocate memory for an object on the heap and call the constructor of the class to initialize the object’s state. Each time the new keyword in Java is used, a new and unique instance of the class is created, which has its own state and behavior. It also plays a key role in polymorphism by allowing the creation of instances of subclasses that inherit from a superclass, and dynamic memory allocation by allowing the creation of arrays dynamically. The new keyword in Java is an essential part of object-oriented programming and allows for the creation and initialization of objects.

Frequently Asked Questions(FAQs)

Some Questions that are frequently asked related to “new Keyword in Java” are given below.

Ques 1. What does the new keyword in Java return?
Ans. The new keyword in Java returns a reference to the new object that has been created.

Ques 2. What is the difference between static and new keyword in Java?
Ans. "new" is used to create a new instance of a class, while "static" is used to declare a variable or method that belongs to the class rather than to an instance of the class.

Ques 3. How many objects can be created using the new keyword in Java?
Ans. You can create as many objects as you need using the new keyword in Java.

Ques 4. What happens if you don’t use the new keyword in Java to create an object?
Ans. If you don’t use the new keyword in Java to create an object, then you will not have a valid reference to that object.

Ques 5. Can you create an object without using the new keyword in Java?
Ans. No, you cannot create an object without using the new keyword in Java.

Leave a Reply

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