Published: February 6, 2025 | Reading Time: 6 minutes
The new keyword in Java is a fundamental operator used to create objects and allocate memory dynamically. It plays a critical role in object-oriented programming by instantiating classes, calling constructors, and enabling dynamic memory allocation. This comprehensive guide covers everything you need to know about the new keyword in Java, including syntax, usage, examples, and best practices.
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.
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.
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.
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.
The object creation process in Java involves several steps:
First, we declare a variable of the class type to hold the reference to the object.
Example: Student student1;
Then, we use the new keyword to allocate memory for the object in the heap.
Example: student1 = new Student();
Finally, the constructor is called automatically to set up the object with initial values.
Example: Student student1 = new Student("Rahul", 21);
// 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();
}
}
Student class defines two fields: name and age.displayDetails() method prints the student's name and age.Main class, a Student object is declared first.new keyword allocates memory and calls the constructor to set values.displayDetails() method is called to print the object's details.Name: Rahul
Age: 21
=== Code Execution Successful ===
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Now let's look at some examples:
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.
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);
}
}
Name: Rahul
Age: 21
=== Code Execution Successful ===
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.
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]);
}
}
}
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 ===
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);
}
}
Book Title: Unknown Title
=== Code Execution Successful ===
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).
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);
}
}
Book Title: Java Fundamentals
Book Author: Tory Steinberg
=== Code Execution Successful ===
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.
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.
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);
}
}
new ArrayList<>() allocates memory for the ArrayList object.list.add() and can be accessed or manipulated.[Java, Python]
=== Code Execution Successful ===
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);
}
}
new keyword creates a new HashSet object, which allocates memory to store unique elements.ArrayList, a HashSet does not allow duplicate values.set.add() and can be accessed without worrying about order, as HashSet does not maintain the insertion order.[Java, Python]
=== Code Execution Successful ===
Similarly, new HashMap<>() is used to create a new HashMap object, where key-value pairs can be stored and retrieved.
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);
}
}
new keyword initializes the HashMap object, allocating space to store key-value pairs.HashMap, data is stored as key-value pairs, making it easy to access values by using the associated key.map.put() and retrieve values using map.get().{1=Java, 2=Python}
=== Code Execution Successful ===
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.
// 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
}
}
sound().sound() method with their own implementations.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.sound() on both of them results in different outputs depending on the actual object type.Dog barks
Cat meows
=== Code Execution Successful ===
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 applications. To learn more, enroll into the CCBP 4.0 Academy program and become job-ready with top-notch programming skills.
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.
If no constructor is defined, Java provides a default constructor. It initialises the object with default values like null or 0.
No, the new keyword is required to allocate memory for arrays in Java. Without it, the array cannot be created.
Memory is allocated on the heap when the new keyword is used. The reference to this memory is stored in a variable.
The new keyword is essential as it enables object creation, memory allocation, and initialisation. Without it, classes cannot be instantiated.
NxtWave offers comprehensive programming courses through CCBP 4.0 Academy to help students become job-ready with industry-recognized certifications and hands-on training.
Contact Information: