Back

New Keyword In Java

06 Feb 2025
6 min read

The new keyword in Java helps make objects. It’s like a tool for creating something new in memory. When you use it, Java gives space for your object and links it to your code. The keyword is important in object-oriented programming as it helps to bring classes to life. In this article we’ll look into what the new keyword is and some examples for a good understanding of the topic.

What is New Keyword in Java?

The new keyword in Java is used to create objects, which are class instances. It has a role in allocating memory for the object and initialising it. When you use the new keyword, Java automatically calls the class's constructor. The constructor is a special method that sets the initial values of the object’s fields and performs any setup required. Without the new keyword, you cannot create objects or call the constructor. Therefore, it is essential for object-oriented programming in Java.

Syntax of New Keyword in Java

The syntax of new keywords in Java is as follows: 

ClassName objectName = new ClassName(parameters);

ClassName: This is the name of the class for which you want to create an object.

objectName: This is the name of the reference variable that will store the address of the newly created object.

New: This keyword allocates memory for the object and calls the constructor.

ClassName(parameters): This is the constructor of the class. It initialises the object's fields and performs any required setup.

custom img

Consider this example: 

Student student1 = new Student("Rahul", 21);

Here, Student is the class, student1 is the object reference, and new Student("Rahul", 21) creates a new Student object by calling the constructor with the parameters "Rahul" and 21.

Constructors

When we create an object in Java, the constructor is called to set it up. For example, in the code Student student1 = new Student("Rahul", 21);, the new keyword creates the object, and the Student("Rahul", 21) constructor is used to give initial values to the object.

A constructor is a special method that has the same name as the class. It helps initialise the object, meaning it gives values to the object's fields like name and age in the Student class. If no constructor is used, the object will not be set up properly. So, it keeps the object ready to use as soon as it's created. 

Process of Object Creation in Java

The object creation process in Java involves several steps: 

1. Declare a variable: First, we declare a variable of the class type to hold the reference to the object.
Example: Student student1;

2. Instantiation or Allocate memory: Then, we use the new keyword to allocate memory for the object in the heap.
Example: student1 = new Student();

3. Initialize the object: Finally, the constructor is called automatically to set up the object with initial values.
Example: Student student1 = new Student("Rahul", 21);

The full example is as follows:

// Define the Student class
class Student {
    String name;
    int age;

    // Constructor to initialize the object
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display student details
    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

// Main class to demonstrate object creation
public class Main {
    public static void main(String[] args) {
        // Step 1: Declare a variable
        Student student1;

        // Step 2: Allocate memory
        student1 = new Student("Rahul", 21);

        // Step 3: Initialize the object and call a method
        student1.displayDetails();
    }
}

How the Code Works  

1. The Student class defines two fields: name and age.

2. A constructor initializes these fields when an object is created.

3. The displayDetails() method prints the student's name and age.

4. In the Main class, a Student object is declared first.

5. The new keyword allocates memory and calls the constructor to set values.

6. The displayDetails() method is called to print the object's details.

Output

Name: Rahul
Age: 21

=== Code Execution Successful ===

Points to Remember about new Keyword in Java

When using the new keyword in Java, there are some important things to remember. These points will help you understand how it works in object creation and how it impacts your Java programs.

1. The new keyword is used with non-primitive data types. In Java, primitive types like int, double, char, etc., don’t need the new keyword because they are not objects. Only the non-primitive types, such as classes, arrays, and interfaces, need new to create objects.

2. Objects created using the new keyword are stored in heap memory. The heap is a storage area which is managed by the Java Virtual Machine (JVM). Objects in the heap can be accessed from anywhere in the program and remain in memory until the garbage collector removes them.

3. Every time you create an object using new, the class constructor is called. The constructor initialises the new object. If you don’t define a constructor, Java itself provides a default constructor that doesn’t set any initial values.

4. Each time the new keyword is used, a new and unique object is created. Even if the objects are of the same class and have the same values, they are separate in memory. So, changes in one object won’t affect the other.

5. The new keyword does not return a type like a method. Instead, it returns a reference or pointer to the newly created object. This reference is then used to access and change the object's properties and methods.

What is the use of new Keyword in Java

The new keyword in Java is necessary for creating objects and managing memory. It performs the task of allocating space, initialising fields, and enabling dynamic behaviour. 

Memory Allocation 

The new keyword helps to allocate memory for an object in the heap. This is where Java stores objects. So without new, no memory is given, and the object cannot be created.

Object Initialization 

The new keyword automatically calls the constructor of a class. The constructor initialises the object’s fields with starting values and sets up the object properly. Without new, you cannot call the constructor, and the object does not work as expected. 

Object Polymorphism 

The new keyword is used to create objects of subclasses. This allows the object to use methods overridden in the subclass instead of those from the superclass. It helps make objects behave differently based on their type.

Dynamic Memory Allocation 

You can use the new keyword to create arrays at runtime. This means the size of the array doesn’t have to be fixed beforehand—it can be decided while the program is running.

Examples of New Keyword in Java

Now let’s look at some examples: 

1. Creating an Object 

Here, the new keyword in Java allocates memory for the object on the heap and calls the class constructor to set its initial state. It returns a reference to the object, which can be stored in a variable to access its fields and methods.

Code

class Student {
    String name;
    int age;

    // Constructor to initialise the object
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Student class
        Student student1 = new Student("Rahul", 21);

        // Accessing the object's fields
        System.out.println("Name: " + student1.name);
        System.out.println("Age: " + student1.age);
    }
}

Output

Name: Rahul
Age: 21

=== Code Execution Successful ===

2. Creating an Array 

The new keyword allocates memory for the array on the heap and sets its size. It initialises all elements to default values like 0 for integers and returns a reference to the array. This can be used to access and modify its elements.

Code

public class Main {
    public static void main(String[] args) {
        // Creating an array of integers
        int[] numbers = new int[5];

        // Assigning values to the array
        numbers[0] = 10;
        numbers[1] = 20;

        // Printing the array values
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Output

Element at index 0: 10
Element at index 1: 20
Element at index 2: 0
Element at index 3: 0
Element at index 4: 0

=== Code Execution Successful ===

3. Creating an Object with Default Constructor 

The new keyword allocates memory for the object and calls the default constructor of the class. The default constructor then initialises the object with predefined values or default settings and returns a reference to the object for further use.

class Book {
    String title;

    // Default constructor
    Book() {
        title = "Unknown Title";
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object with the default constructor
        Book book1 = new Book();

        // Accessing the object's field
        System.out.println("Book Title: " + book1.title);
    }
}

Output

Book Title: Unknown Title

=== Code Execution Successful ===

4. Creating an Object With Parameterized Constructor

A parameterized constructor is invoked when you create an object and pass arguments to the constructor. This allows you to initialize the object with custom values instead of predefined ones. The constructor takes parameters that set the values of the object’s fields. Like in this example, you're providing arguments ("Java Fundamentals" and " Tory Steinberg ") to initialize the fields (title and author).

Code

class Book {
    String title;
    String author;

    // Parameterized constructor
    Book(String t, String a) {
        title = t;
        author = a;
    }
}

public class Main {
    public static void main(String[] args) {
        // Invoking the parameterized constructor
        Book book2 = new Book("Java Fundamentals", "Tory Steinberg");
        System.out.println("Book Title: " + book2.title); 
        System.out.println("Book Author: " + book2.author);     }
}

Output

Book Title: Java Fundamentals
Book Author: Tory Steinberg

=== Code Execution Successful ===

Use new keywords in Java collections

In Java, collections like ArrayList, HashSet, and HashMap are used to store and manage groups of data. These collections use the new keyword to create and initialize objects. The new keyword dynamically allocates memory for these objects, which allows for efficient data handling. Let’s break down how the new keyword is used in different collections:

Example 1: ArrayList

Using new ArrayList<>() creates a new ArrayList object in memory, ready to store elements. You can add data to it and dynamically increase its size.

Code

import java.util.ArrayList;
 
public class Main {
	public static void main(String[] args) {
    	// Creating a new ArrayList using the new keyword
    	ArrayList<String> list = new ArrayList<>();
 
    	// Adding elements to the ArrayList
    	list.add("Java");
    	list.add("Python");
 
        // Printing the ArrayList
    	System.out.println(list);
	}
}

How the code works

1. Memory Allocation: new ArrayList<>() allocates memory for the ArrayList object.

2. Dynamic Collection: The ArrayList automatically grows or shrinks based on the number of elements added.

3. Adding and Accessing Data: Data is added using list.add() and can be accessed or manipulated.

Output

[Java, Python]
 
=== Code Execution Successful ===

Example 2: HashSet

The new keyword helps in creating a new HashSet which is an unordered collection that does not allow duplicate elements.

import java.util.HashSet;
 
public class Main {
	public static void main(String[] args) {
    	// Creating a new HashSet using the new keyword
    	HashSet<String> set = new HashSet<>();
 
    	// Adding elements to the HashSet
    	set.add("Java");
    	set.add("Python");
 
    	// Printing the HashSet
    	System.out.println(set);
	}
}

How the code works

1. Memory Allocation: The new keyword creates a new HashSet object, which allocates memory to store unique elements.

2. Uniqueness of Elements: Unlike an ArrayList, a HashSet does not allow duplicate values.

3. Adding and Accessing Data: Data is added with set.add() and can be accessed without worrying about order, as HashSet does not maintain the insertion order.

Output

[Java, Python]
 
=== Code Execution Successful ===

Example 3: HashMap

Similarly, new HashMap<>() is used to create a new HashMap object, where key-value pairs can be stored and retrieved.

Code

import java.util.HashMap;
 
public class Main {
	public static void main(String[] args) {
    	// Creating a new HashMap using the new keyword
    	HashMap<String, String> map = new HashMap<>();
 
    	// Adding key-value pairs to the HashMap
    	map.put("1", "Java");
    	map.put("2", "Python");
 
    	// Printing the HashMap
    	System.out.println(map);
	}
}

How the code works

1. Memory Allocation: The new keyword initializes the HashMap object, allocating space to store key-value pairs.

2. Key-Value Pair Storage: In HashMap, data is stored as key-value pairs, making it easy to access values by using the associated key.

3. Adding and Accessing Data: You add key-value pairs with map.put() and retrieve values using map.get().

Output

{1=Java, 2=Python}
 
=== Code Execution Successful ===

Object Polymorphism By Using New Keyword in Java

In Java polymorphism, objects of different classes can be treated as objects of a common superclass. Using new, you can create instances of subclasses, which can then be treated as instances of the superclass. This is known as runtime polymorphism because the method that gets called is determined at runtime based on the object type.

We can also say that polymorphism lets you use the same method name, but it will behave differently depending on the object (or class) it is called on. The new keyword is used to create the object of the subclass, and this object can override methods of the superclass, providing its own implementation. Here’s an example:

Code

// Superclass
class Animal {
	void sound() {
    	System.out.println("Animal makes a sound");
	}
}
 
// Subclass 1
class Dog extends Animal {
	void sound() {
    	System.out.println("Dog barks");
	}
}
 
// Subclass 2
class Cat extends Animal {
	void sound() {
    	System.out.println("Cat meows");
	}
}
 
public class Main {
	public static void main(String[] args) {
    	// Creating objects using 'new' keyword
    	Animal animal1 = new Dog(); // Dog object treated as Animal
    	Animal animal2 = new Cat(); // Cat object treated as Animal
 
    	// Calling the overridden methods
    	animal1.sound(); // Will call Dog's sound method
    	animal2.sound(); // Will call Cat's sound method
	}
}

How the code works

1. Superclass Animal defines a method sound().

2. Subclasses Dog and Cat override the sound() method with their own implementations.

3. In the main method, we create two objects:

  • animal1 is an instance of Dog, but it is treated as an Animal.
  • animal2 is an instance of Cat, but it is also treated as an Animal.

4. Despite the objects being of different types (Dog and Cat), calling sound() on both of them results in different outputs depending on the actual object type.

Output

Dog barks
Cat meows
 
=== Code Execution Successful ===

Conclusion

Understanding the new keyword is essential for coding students as it forms the foundation of object-oriented programming in Java. You will learn how it enables object creation, memory allocation, and proper initialisation. Therefore it’s a key tool for building and applications. To learn more, enroll into the CCBP 4.0 Academy program and become job-ready with top-notch programming skills.

Frequently Asked Questions

1. Can we create an object in Java without using the new keyword?

Yes, objects can be created using methods like clone(), deserialisation, or factory methods. But the new keyword is the most common way to create objects.

2. What happens if the constructor is missing in a class?

If no constructor is defined, Java provides a default constructor. It initialises the object with default values like null or 0.

3. Can we create an array without using the new keyword?

No, the new keyword is required to allocate memory for arrays in Java. Without it, the array cannot be created.

4. Where is memory allocated when we use the new keyword?

Memory is allocated on the heap when the new keyword is used. The reference to this memory is stored in a variable.

5. Why is the new keyword important in object-oriented programming?

The new keyword is essential as it enables object creation, memory allocation, and initialisation. Without it, classes cannot be instantiated.

Read More Articles

Chat with us
Chat with us
Talk to career expert