Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the new Keyword in Java
2.1.
Java
3.
Syntax of the new Keyword in Java
3.1.
Java
4.
Process of Object Creation in Java
4.1.
Java
5.
Points to Remember about the new Keyword in Java
5.1.
Java
6.
What is the Use of the new Keyword in Java
6.1.
Java
7.
Examples of the new Keyword in Java
7.1.
Example 1: Creating an Instance of a Simple Class
7.2.
Java
7.3.
Example 2: Using new with Arrays
7.4.
Java
7.5.
Example 3: Dynamic Memory Allocation with Objects
7.6.
Java
8.
Frequently Asked Questions
8.1.
Can I use the new keyword with primitive types?
8.2.
What happens if I forget to use the new keyword when creating an object?
8.3.
Is it possible to overload the constructor called by the new keyword?
9.
Conclusion
Last Updated: May 1, 2024
Easy

New Keyword in Java

Author Rahul Singh
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java is a widely-used programming language that facilitates object-oriented programming. A fundamental concept in Java is the creation of objects, which is where the new keyword plays a crucial role. This keyword is used to instantiate new objects, essentially creating an instance of a class with specified attributes and behaviors. 

New Keyword in Java

In this article, we'll learn the syntax of the new keyword, looks into the process of object creation, and illustrate its use with practical examples. 

What is the new Keyword in Java

The new keyword in Java is a special operator used to create new objects. When you write code that involves classes and objects, using new is essential for initializing new instances of a class. This keyword does two important things: it allocates memory for the new object in the Java Virtual Machine (JVM) and it calls the constructor of the class to initialize the object.

Here's a basic way to understand it: if you think of a class as a blueprint for a building, then using the new keyword is like starting the construction of a building based on that blueprint. It doesn't add any extra details—it simply follows the plans and sets up everything as specified in the class definition.

For example, if you have a class named Car, and this class has attributes like color, make, and model, using the new keyword helps you create a specific car object with its own color, make, and model. Here’s a simple code example:

  • Java

Java

class Car {
String color;
String make;
String model;

Car(String color, String make, String model) {
this.color = color;
this.make = make;
this.model = model;
}
}

public class Main {
public static void main(String[] args) {
// Creating a new Car object
Car myCar = new Car("Red", "Toyota", "Corolla");
System.out.println("Created a " + myCar.color + " " + myCar.make + " " + myCar.model);
}
}

Output

Created a Red Toyota Corolla


In this code, new Car("Red", "Toyota", "Corolla") creates a new object of Car. The new keyword allocates the necessary memory for a Car object & calls the Car constructor to set the color, make, and model of the car to Red, Toyota, and Corolla, respectively.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of the new Keyword in Java

Understanding the syntax of the new keyword in Java is crucial for correctly using it to create objects. The general syntax is straightforward:

ClassName objectName = new ClassName(arguments);


Here's what each part means:

  1. ClassName: This is the name of the class from which you want to create an object.
     
  2. objectName: This is the name you give to the new object. You can use this name to access the object later.
     
  3. new: This keyword is used to create the object.
     
  4. ClassName(arguments): This calls the constructor of the class. The constructor is a special method in the class that sets up the object with specific initial values. Arguments are the values you pass to the constructor, which may vary depending on what the constructor of the class is designed to accept.
     

For example, let’s take a closer look at a simple class named Book. Suppose this class has a constructor that accepts two parameters: the title and the author of the book.

  • Java

Java

class Book {
String title;
String author;

// Constructor for Book class
Book(String title, String author) {
this.title = title;
this.author = author;
}
}

public class Library {
public static void main(String[] args) {
// Creating a new Book object
Book myBook = new Book("1984", "George Orwell");
System.out.println("Book: " + myBook.title + " by " + myBook.author);
}
}

Output

Book: 1984 by George Orwell


In this example:

  • new Book("1984", "George Orwell") creates a new instance of Book.
     
  • Book myBook declares an object of type Book and assigns it the new Book instance.
     
  • The constructor Book(String title, String author) initializes the new book object's title and author attributes with the values provided.
     
  • Using the new keyword, as shown, ensures that each object has its unique set of data, encapsulated within that object. Each time you use new, a separate space in memory is allocated for a new object.

Process of Object Creation in Java

When you use the new keyword in Java, several important steps occur behind the scenes to ensure that your object is set up correctly. Understanding this process can help you better grasp how Java manages memory and object lifecycle. Here's a breakdown of what happens:
 

  1. Memory Allocation: The first step when you use the new keyword is the allocation of memory. Java allocates memory for the new object in the heap, which is a portion of memory dedicated to storing objects. The size of the memory allocated depends on the data types and the number of variables in the class.
     
  2. Constructor Invocation: After memory allocation, the constructor of the class is called. A constructor is a special method in the class that initializes new objects. It sets up the initial state of the object with the values provided or default values. Constructors can be overloaded, meaning you can have multiple constructors with different parameters. The appropriate constructor is chosen based on the arguments passed during object creation.
     
  3. Initialization: Inside the constructor, the fields of the object are initialized. This can involve setting fields with values passed via the constructor or default values defined in the class. Initialization also includes the execution of any code inside the constructor, which may set up more complex state or call other methods.
     
  4. Object Reference: Once the object is created and initialized, its reference is returned to the program. This reference is used to access the object in your code. It points to the object's location in the heap, allowing the Java Virtual Machine (JVM) to track the object's data and state.
     

Here's a simple example to illustrate this process using a class Rectangle to represent geometric rectangles:

  • Java

Java

class Rectangle {
int width;
int height;

// Constructor for Rectangle
Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
}

public class Geometry {
public static void main(String[] args) {
// Creating a new Rectangle object
Rectangle myRect = new Rectangle(5, 10);
System.out.println("Rectangle dimensions: " + myRect.width + "x" + myRect.height);
}
}

Output

Rectangle dimensions: 5x10


In this example:

  • Memory Allocation: Memory is allocated for a Rectangle object with space for its width and height.
     
  • Constructor Invocation: The Rectangle(int, int) constructor is called, setting width and height.
     
  • Initialization: The width and height are initialized to 5 and 10, respectively.
     
  • Object Reference: myRect holds the reference to the newly created Rectangle object, and this reference is used to access and display the rectangle's dimensions.

Points to Remember about the new Keyword in Java

When using the new keyword in Java, there are several key points to keep in mind to ensure you are using it correctly and effectively. These points will help you understand the nuances of object creation and how it affects your Java programs.
 

  1. Non-Primitive Types: The new keyword is used with non-primitive data types. In Java, primitive types (like int, double, char, etc.) do not require the new keyword because they are not objects. Non-primitive types, which include classes, arrays, and interfaces, do require the use of new to create an object.
     
  2. Memory Allocation in the Heap: Objects created with the new keyword are stored in the heap memory. The heap is a general storage area for all Java objects, managed by the Java Virtual Machine (JVM). Storing objects in the heap ensures that they can be accessed from any part of the program and remain in memory as long as needed until they are removed by the garbage collector.
     
  3. Constructor Call: Every time an object is created with the new keyword, a constructor of the class is invoked. The constructor is responsible for initializing the new object. If no constructor is explicitly defined in the class, Java provides a default constructor that does not set any initial values.
     
  4. Unique Object: Each use of the new keyword results in the creation of a new, unique object. Even if the objects are instantiated from the same class and with the same parameters, they are distinct and separate in memory. This means changes to one object do not affect another.
     
  5. Return Type: The new keyword does not have a return type like a method does. Instead, it returns a reference (or pointer) to the object created. This reference is then used to access and manipulate the object's properties and methods.
     

Here’s an example to illustrate these points using a class Student:

  • Java

Java

class Student {
String name;
int age;

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

public class School {
public static void main(String[] args) {
// Creating two different Student objects
Student student1 = new Student("Gunjan", 20);
Student student2 = new Student("Gunjan", 20);

// Checking if both students are the same
if (student1 == student2) {
System.out.println("Both students are the same.");
} else {
System.out.println("Students are different.");
}
}
}

Output

Students are different.


In this example, even though student1 and student2 have the same name and age, they are different objects in memory, and comparing them with == will confirm that they are not the same object.

What is the Use of the new Keyword in Java

The new keyword in Java serves several important purposes in Java programming, particularly in the context of object-oriented programming. Understanding these uses helps clarify why this keyword is fundamental when working with Java.

  1. Object Creation: The primary use of the new keyword is to create new instances of a class. When you use new, it allocates memory for a new object and returns a reference to that memory. This is essential for the management of dynamic memory in Java, which is a core aspect of its operation and efficiency.
     
  2. Constructor Invocation: Using new automatically invokes the constructor of the class. This is crucial because the constructor initializes the new object with initial values. Constructors can be overloaded with different parameters, allowing for different ways of initializing objects depending on the provided arguments.
     
  3. Access to Instance Methods and Variables: Once an object is created using new, you can use it to access instance methods and variables. These are specific to the object and can vary from one instance to another. By creating objects, new enables you to utilize the full capabilities of class-based features in Java.
     
  4. Enabling Polymorphism: By using new with class instantiation, Java allows for polymorphism. This means you can assign a subclass object to a superclass reference, enabling dynamic method dispatch. This is a cornerstone of object-oriented programming, allowing for flexible and reusable code.
     

Here's a simple example to demonstrate these uses:

  • Java

Java

class Bicycle {
int gears;
String color;

// Constructor for Bicycle class
Bicycle(int gears, String color) {
this.gears = gears;
this.color = color;
}

void displayFeatures() {
System.out.println("Bicycle features: " + gears + " gears & " + color + " color.");
}
}

public class TestBicycle {
public static void main(String[] args) {
// Creating a new Bicycle object
Bicycle myBike = new Bicycle(5, "blue");
myBike.displayFeatures(); // Accessing an instance method
}
}

Output

Bicycle features: 5 gears & blue color.


In this example:

  • A new Bicycle object is created with 5 gears and blue color. The new keyword allocates memory for this object and calls its constructor to set the gears and color.
     
  • The object myBike is then used to call the displayFeatures() method, showing how new allows access to instance-specific methods that operate on the data of individual objects.
     
  • These functionalities shows the importance of the new keyword in building flexible and dynamic software in Java. Its role in object creation and management is central to implementing the principles of object-oriented programming effectively.

Examples of the new Keyword in Java

Example 1: Creating an Instance of a Simple Class

Let's consider a simple class named Laptop that represents a laptop with attributes for its model and price.

  • Java

Java

class Laptop {
String model;
double price;

// Constructor for Laptop class
Laptop(String model, double price) {
this.model = model;
this.price = price;
}

void displayInfo() {
System.out.println("Laptop Model: " + model + ", Price: $" + price);
}
}

public class ElectronicsStore {
public static void main(String[] args) {
// Creating a new Laptop object
Laptop myLaptop = new Laptop("Dell XPS 15", 1500.00);
myLaptop.displayInfo(); // Displaying information about the laptop
}
}

Output

Laptop Model: Dell XPS 15, Price: $1500.0


In this example, the new keyword is used to create a Laptop object. The constructor initializes the object's model and price, and the displayInfo() method is then used to output these details.

Example 2: Using new with Arrays

The new keyword is not limited to just creating objects from classes; it is also used for creating arrays.

  • Java

Java

public class ArrayExample {
public static void main(String[] args) {
// Creating a new array of integers
int[] numbers = new int[5]; // An array to hold 5 integers

// Initializing array elements
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i * 2; // Each element is twice its index
}

// Printing the array elements
for (int number : numbers) {
System.out.println("Number: " + number);
}
}
}

Output

Number: 0
Number: 2
Number: 4
Number: 6
Number: 8

Example 3: Dynamic Memory Allocation with Objects

Creating multiple instances of a class dynamically shows the flexibility of the new keyword.

  • Java

Java

class Book {
String title;
String author;

Book(String title, String author) {
this.title = title;
this.author = author;
}

void displayDetails() {
System.out.println("Book: " + title + " by " + author);
}
}

public class Library {
public static void main(String[] args) {
// Creating multiple Book objects
Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Brave New World", "Aldous Huxley");

book1.displayDetails();
book2.displayDetails();
}
}

Output

Book: 1984 by George Orwell
Book: Brave New World by Aldous Huxley


This example creates two Book objects, each initialized with its own title and author. Each book's details are then printed, demonstrating how each instance maintains its own data.

Frequently Asked Questions

Can I use the new keyword with primitive types?

No, the new keyword is not used with primitive types like int, boolean, or double. It is used exclusively for creating instances of classes, arrays, and other object types.

What happens if I forget to use the new keyword when creating an object?

If you forget to use the new keyword, you will likely encounter a compile-time error because the syntax expects a reference to an object. Without new, the necessary memory allocation and constructor calls cannot be made, resulting in an error.

Is it possible to overload the constructor called by the new keyword?

Yes, constructors can be overloaded, which means you can have multiple constructors within the same class with different parameters. The new keyword can be used to call any of these constructors, depending on the arguments passed.

Conclusion

In this article, we have learned about the new keyword in Java, which is fundamental for object-oriented programming in the language. Starting with a clear definition and moving through the syntax, process of object creation, key points to remember, practical uses, and concrete examples, we've covered the essential aspects that every Java programmer should understand. The new keyword not only facilitates memory allocation but also initiates object construction through constructor calls, allowing for detailed initialization of new objects. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Setting up the environment
Next article
Reverse the Number in Java
Live masterclass