Table of content:
- What Is new Keyword In Java?
- Uses Of The new Keyword In Java
- Memory Management With new Keyword In Java
- Example 1: Creating An Object Of A Class Using new Keyword In Java
- Example 2: Creating An Array Using The new Keyword In Java
- Best Practices For Using new Keyword In Java
- Conclusion
- Frequently Asked Questions
New Keyword In Java | Syntax, Uses And More (+Code Examples)
The new keyword in Java is a powerful tool that enables us to create new objects and allocate memory dynamically. It's the cornerstone of Java's object-oriented programming approach, allowing developers to instantiate classes and access their methods and properties. Without it, working with objects—one of the core aspects of Java—wouldn't be possible.
In this article, we'll explore the role of the new keyword in Java, how it works, and its significance in memory management and object creation. We'll also examine examples to demonstrate its use in real-world scenarios.
What Is new Keyword In Java?
The new keyword in Java programming is used to create objects and allocate memory dynamically during program execution. It is an integral part of Java's object-oriented design, allowing us to instantiate classes, initialize objects, and allocate memory on the heap.
When used, the new keyword calls the constructor of the class, which sets up the initial state of the object. Additionally, it can also be used to create arrays. This memory allocation is managed by Java's Garbage Collector, ensuring efficient memory usage by automatically reclaiming unused objects.
The new keyword is essential for object creation in Java, as it makes sure objects are properly initialized and ready for use.
Syntax Of new Keyword In Java
ClassName objectName = new ClassName(arguments);
Here:
- ClassName: Represents the type of object being created.
- objectName: A reference variable that stores the memory address of the newly created object.
- new: The Java keyword that allocates memory dynamically for the object.
- ClassName(arguments): A constructor call to initialize the object. The arguments provided depend on the constructor defined in the class.
Explore this amazing course and master all the key concepts of Java programming effortlessly!
Uses Of The new Keyword In Java
Below are the key uses of the new keyword in Java:
- Creating Objects: The primary use of the new keyword is to create objects of a class. It dynamically allocates memory for the object and initializes it.
MyClass obj = new MyClass(); // Creates an object of MyClass
- Invoking Constructors: When used, the new keyword calls the constructor of the class. It can invoke default or parameterized constructors.
MyClass obj = new MyClass(); // Invokes default constructor
MyClass obj2 = new MyClass(10); // Invokes parameterized constructor
- Allocating Memory for Arrays: The new keyword is used to allocate memory for arrays dynamically.
int[] numbers = new int[5]; // Allocates memory for an integer array of size 5
String[] names = new String[3]; // Allocates memory for a String array
- Creating Anonymous Objects: It is used to create objects without assigning them to a reference variable, often for one-time use.
new MyClass().someMethod(); // Calls someMethod on an anonymous object
- Instantiating Inner Classes: The new keyword is used to create instances of inner or nested classes.
OuterClass.InnerClass obj = new OuterClass().new InnerClass();
- Dynamic Class Loading via Reflection: The newInstance() method in the Reflection API uses the new keyword internally to create objects dynamically.
Class<?> cls = Class.forName("MyClass");
Object obj = cls.getDeclaredConstructor().newInstance(); // Uses `new` internally
- Creating Wrapper Objects: The new keyword is used to create objects of wrapper classes for primitive types (although autoboxing is preferred in modern Java versions).
Integer num = new Integer(10); // Deprecated in Java 9 but still valid
- Implementing Custom Data Structures: Java developers can use the new keyword to instantiate objects required for data structures like linked lists, trees, and graphs.
Node node = new Node(5); // Node of a linked list or tree
- Allocating Memory for Multidimensional Arrays: It is used for creating multidimensional arrays dynamically.
int[][] matrix = new int[3][3]; // 2D array
- With Polymorphism: The new keyword helps in creating objects of derived classes while storing references in a base class type, supporting polymorphism.
Parent obj = new Child(); // Polymorphic behavior
Memory Management With new Keyword In Java
The new keyword plays a crucial role in Java's memory management by dynamically allocating memory for objects and arrays on the heap memory. Java ensures efficient use of memory through its automatic Garbage Collection (GC) mechanism, which deallocates memory used by objects that are no longer referenced.
How Memory Management Works With The new Keyword
- Heap Memory Allocation: When we use the new keyword, Java allocates memory for the object or array on the heap. This memory includes space for the object’s fields (variables) and metadata (like the class of the object).
- Object Initialization: The new keyword invokes the class’s constructor to initialize the object with the required values or default settings.
- Reference Variables: A reference variable stores the address of the object in memory, allowing us to interact with the object. If the reference variable is reassigned or goes out of scope, the object becomes eligible for garbage collection.
- Garbage Collection: Objects created using the new keyword are managed by Java's Garbage Collector. When an object is no longer reachable by any reference, the Garbage Collector automatically deallocates its memory, freeing it for future use.
- Efficient Memory Use: Java's memory management, combined with the new keyword, ensures that memory is allocated only as needed and reclaimed when objects are no longer used.
Code Example:
Y2xhc3MgQ2FyIHsKICAgIFN0cmluZyBtb2RlbDsKICAgIENhcihTdHJpbmcgbW9kZWwpIHsKICAgICAgICB0aGlzLm1vZGVsID0gbW9kZWw7IC8vIENvbnN0cnVjdG9yIGluaXRpYWxpemVzIHRoZSBvYmplY3QKICAgIH0KfQoKcHVibGljIGNsYXNzIE1haW4gewogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIENhciBjYXIxID0gbmV3IENhcigiU2VkYW4iKTsgLy8gTWVtb3J5IGFsbG9jYXRlZCBmb3IgY2FyMQogICAgICAgIENhciBjYXIyID0gbmV3IENhcigiU1VWIik7ICAgLy8gTWVtb3J5IGFsbG9jYXRlZCBmb3IgY2FyMgogICAgICAgIGNhcjEgPSBudWxsOyAvLyBjYXIxIHJlZmVyZW5jZSByZW1vdmVkLCBvYmplY3QgaXMgbm93IGVsaWdpYmxlIGZvciBnYXJiYWdlIGNvbGxlY3Rpb24KICAgICAgICAvLyBjYXIyIHN0aWxsIHBvaW50cyB0byB0aGUgIlNVViIgb2JqZWN0LCB3aGljaCBpcyBub3QgZ2FyYmFnZSBjb2xsZWN0ZWQKICAgIH0KfQo=
Output:
Since the code does not include any System.out.println statements (except the constructor initialization), it produces no visible output when run.
Explanation:
In the above code example-
- We define a class named Car that represents a blueprint for creating Car objects.
- Inside the Car class, we declare an instance variable model of type String to store the car's model name.
- We create a constructor Car(String model) that takes a model name as a parameter and assigns it to the model variable using this.model = model. This ensures that each Car object is initialized with a specific model name when created.
- In the main method of the Main class, we first create a Car object named car1 and initialize it with the model "Sedan". This allocates memory for the car1 object and assigns it a reference.
- Similarly, we create another Car object named car2 and initialize it with the model "SUV". Now car2 references this new object in memory.
- We set car1 to null, which removes the reference to the "Sedan" object. The "Sedan" object is no longer accessible, making it eligible for garbage collection by the Java runtime.
- Meanwhile, car2 still references the "SUV" object, so it remains accessible and is not garbage collected.
Example 1: Creating An Object Of A Class Using new Keyword In Java
In this example, we create an object of a class Person using the new keyword, and initialize it with a constructor.
Code Example:
Y2xhc3MgUGVyc29uIHsKICAgIFN0cmluZyBuYW1lOwogICAgaW50IGFnZTsKCiAgICAvLyBDb25zdHJ1Y3RvcgogICAgUGVyc29uKFN0cmluZyBuYW1lLCBpbnQgYWdlKSB7CiAgICAgICAgdGhpcy5uYW1lID0gbmFtZTsKICAgICAgICB0aGlzLmFnZSA9IGFnZTsKICAgIH0KCiAgICAvLyBNZXRob2QgdG8gZGlzcGxheSBpbmZvcm1hdGlvbgogICAgdm9pZCBkaXNwbGF5KCkgewogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiTmFtZTogIiArIG5hbWUpOwogICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiQWdlOiAiICsgYWdlKTsKICAgIH0KfQoKcHVibGljIGNsYXNzIE1haW4gewogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIC8vIENyZWF0aW5nIGEgbmV3IG9iamVjdCB1c2luZyB0aGUgJ25ldycga2V5d29yZAogICAgICAgIFBlcnNvbiBwZXJzb24xID0gbmV3IFBlcnNvbigiQWxpYSIsIDI1KTsKICAgICAgICAvLyBEaXNwbGF5aW5nIHRoZSBpbmZvcm1hdGlvbgogICAgICAgIHBlcnNvbjEuZGlzcGxheSgpOwogICAgfQp9Cg==
Output:
Name: Alia
Age: 25
Explanation:
In the above code example-
- We define a class called Person, which represents an individual with two attributes: name (a String) and age (an int).
- Inside the Person class, we define a constructor Person(String name, int age), which takes two parameters—name and age. This constructor initializes the instance variables this.name and this.age with the provided values, ensuring that each Person object has a specific name and age.
- We also define a method display() in the Person class, which prints the name and age of the Person object to the console.
- In the main method of the Main class, we create a new Person object called person1 using the new keyword. This initializes the object with the name "Alia" and age 25.
- Finally, we call the display() method on the person1 object, which prints Alia's name and age to the console.
Sharpen your coding skills with Unstop's 100-Day Coding Sprint and compete now for a top spot on the leaderboard!
Example 2: Creating An Array Using The new Keyword In Java
In this example, we create an array of integers using the new keyword and initialize its elements.
Code Example:
cHVibGljIGNsYXNzIE1haW4gewogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIC8vIENyZWF0aW5nIGFuIGFycmF5IG9mIGludGVnZXJzIHVzaW5nIHRoZSAnbmV3JyBrZXl3b3JkCiAgICAgICAgaW50W10gbnVtYmVycyA9IG5ldyBpbnRbNV07CiAgICAgICAgLy8gSW5pdGlhbGl6aW5nIHRoZSBhcnJheSBlbGVtZW50cwogICAgICAgIG51bWJlcnNbMF0gPSAxMDsKICAgICAgICBudW1iZXJzWzFdID0gMjA7CiAgICAgICAgbnVtYmVyc1syXSA9IDMwOwogICAgICAgIG51bWJlcnNbM10gPSA0MDsKICAgICAgICBudW1iZXJzWzRdID0gNTA7CiAgICAgICAgLy8gRGlzcGxheWluZyB0aGUgYXJyYXkgZWxlbWVudHMKICAgICAgICBTeXN0ZW0ub3V0LnByaW50bG4oIkFycmF5IGVsZW1lbnRzOiIpOwogICAgICAgIGZvciAoaW50IG51bSA6IG51bWJlcnMpIHsKICAgICAgICAgICAgU3lzdGVtLm91dC5wcmludGxuKG51bSk7CiAgICAgICAgfQogICAgfQp9Cg==
Output:
Array elements:
10
20
30
40
50
Explanation:
In the above code example-
- We begin by defining the Main class, where the execution of the program starts in the main method.
- Inside the main method, we create an array of integers called numbers using the new keyword. This array has a size of 5, meaning it can hold 5 integer elements. Initially, all elements in the array are set to 0.
- We then initialize the array elements by assigning values to each index in the array:
- numbers[0] = 10;
- numbers[1] = 20;
- numbers[2] = 30;
- numbers[3] = 40;
- numbers[4] = 50;
- After assigning values to all the elements, we print a message "Array elements:" to indicate that we are about to display the array's contents.
- We then use a for-each loop to iterate over the elements of the numbers array. For each element (referred to as num), we print its value using System.out.println(num);. This will display each integer in the array on a new line.
Best Practices For Using new Keyword In Java
The new keyword plays a central role in Java programming, especially when creating objects and managing memory dynamically. To use it effectively, it is essential to follow best practices that ensure code efficiency, clarity, and proper memory management.
- Initialize Objects Immediately: Always initialize reference variables when they are declared to avoid NullPointerException.
- Use Constructor Overloading Appropriately: Select the appropriate constructor for the specific use case to avoid unnecessary object creation.
- Avoid Overusing Anonymous Objects: Use anonymous objects only when you don't need to reuse the object later.
- Prefer Factory Methods Over Direct Instantiation: Use factory methods or design patterns like Singleton instead of directly using new for better maintainability and flexibility.
- Use Autoboxing for Wrapper Classes: Take advantage of autoboxing to avoid manually using new with wrapper classes, which reduces memory overhead.
- Avoid Memory Leaks by Nullifying References: Explicitly nullify references to objects when they are no longer needed, helping garbage collection to reclaim memory.
- Use Reflection with Caution: When using reflection, handle exceptions properly and avoid overusing it to prevent runtime errors.
- Use new Only When Necessary: Avoid creating objects unnecessarily, especially when they are only needed temporarily.
- Leverage new for Array Creation: Use new for dynamically creating arrays with a size determined at runtime.
- Be Careful with Inner Class Instantiation: Ensure that when instantiating inner classes, the correct syntax is used and the outer class instance is properly referenced.
Are you looking for someone to answer all your programming-related queries? Let's find the perfect mentor here.
Conclusion
The new keyword in Java is a vital tool for object creation and memory management. By dynamically allocating memory on the heap, it enables us to instantiate objects and initialize them using constructors. Whether we are working with classes or arrays, the new keyword ensures that objects are properly initialized and ready for use. Additionally, Java's automatic memory management system, particularly through Garbage Collection, helps reclaim memory occupied by objects that are no longer needed.
Understanding how the new keyword works in Java empowers developers to write efficient, object-oriented code while relying on Java's memory management to handle cleanup tasks. Overall, the new keyword is indispensable for creating objects and managing memory in Java applications.
Frequently Asked Questions
Q. What does the new keyword do in Java?
The new keyword in Java is used to create objects and allocate memory dynamically. When the new keyword is used, it performs two actions:
- Memory Allocation: It allocates memory for the object on the heap, where all objects in Java are stored.
- Object Initialization: It invokes the constructor of the class, initializing the object's fields with the values provided (if any).
For example, when we create an object of a class using the new keyword, the memory for the object is reserved on the heap, and the constructor is called to set the initial state of the object.
Q. Can we use the new keyword for primitive data types in Java?
No, we cannot use the new keyword with primitive data types in Java. Primitive data types such as int, char, float, etc., are directly stored in stack memory, and they are not objects. The new keyword is only used for creating instances of classes (objects) and arrays. For example:
int num = 10; // No 'new' keyword needed for primitive types
In contrast, for arrays and objects, the new keyword is required to allocate memory dynamically.
Q. How does Garbage Collection work with objects created using the new keyword in Java?
In Java, objects created with the new keyword are stored in the heap memory. Once an object is no longer referenced, it becomes eligible for Garbage Collection. Java’s Garbage Collector automatically identifies objects that are no longer reachable from any active part of the program and reclaims the memory they occupy.
For example, if we assign null to an object reference or the reference goes out of scope, the object can be garbage collected, and its memory is freed for reuse. The new keyword does not directly handle memory deallocation; that responsibility lies with the Garbage Collector.
Person person = new Person("John"); // object created
person = null; // object becomes eligible for garbage collection
Q. What is the difference between using new keyword for creating an object and creating an array in Java?
While the new keyword is used for both creating objects and arrays, the way memory is allocated differs slightly:
- Objects: When an object is created using the new keyword, memory is allocated on the heap for the instance variables defined in the class.
- Arrays: When an array is created with the new keyword, memory is allocated for the entire array, and the array elements are initialized to their default values (e.g., 0 for int, null for objects).
For example:
Person person = new Person("Alice"); // Creates an object
int[] numbers = new int[5]; // Creates an array of integers with 5 elements, all initialized to 0
Q. Can we create an array of objects using the new keyword?
Yes, we can create an array of objects using the new keyword in Java. When we create an array of objects, the array itself is created first, and then each element of the array can reference an object created using the new keyword.
For example:
Person[] people = new Person[3]; // Creates an array of 3 Person objects (null references initially)
people[0] = new Person("Alia"); // Allocates memory for the first Person object
people[1] = new Person("Bhaskar"); // Allocates memory for the second Person object
people[2] = new Person("Chandra"); // Allocates memory for the third Person object
In this case, the array is created first, and then the individual objects are instantiated within that array using the new keyword.
With this, we conclude our discussion on the new keyword in Java. Here are a few other topics that you might be interested in reading:
- Convert String To Date In Java | 3 Different Ways With Examples
- Final, Finally & Finalize In Java | 15+ Differences With Examples
- Super Keyword In Java | Definition, Applications & More (+Examples)
- How To Find LCM Of Two Numbers In Java? Simplified With Examples
- How To Find GCD Of Two Numbers In Java? All Methods With Examples
- Volatile Keyword In Java | Syntax, Working, Uses & More (+Examples)
I’m a Computer Science graduate with a knack for creative ventures. Through content at Unstop, I am trying to simplify complex tech concepts and make them fun. When I’m not decoding tech jargon, you’ll find me indulging in great food and then burning it out at the gym.
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Subscribe
to our newsletter
Comments
Add comment