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:
-
ClassName: This is the name of the class from which you want to create an object.
-
objectName: This is the name you give to the new object. You can use this name to access the object later.
-
new: This keyword is used to create the object.
-
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
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);
}
}
You can also try this code with Online Java Compiler
Run Code
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:
-
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.
-
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.
-
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.
-
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
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);
}
}
You can also try this code with Online Java Compiler
Run Code
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.
-
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.
-
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.
-
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.
-
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.
-
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
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.");
}
}
}
You can also try this code with Online Java Compiler
Run Code
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.
-
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.
-
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.
-
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.
-
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
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
}
}
You can also try this code with Online Java Compiler
Run Code
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
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
}
}
You can also try this code with Online Java Compiler
Run Code
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
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);
}
}
}
You can also try this code with Online Java Compiler
Run Code
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
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();
}
}
You can also try this code with Online Java Compiler
Run Code
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 DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.