Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

new Keyword in Java: For Object Creation and Memory Allocation

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

In Java, the new keyword plays a crucial role in object-oriented programming. It serves as the primary mechanism for creating instances of classes. This article delves into the new keyword’s significance, usage, and various nuances, providing a comprehensive understanding of how it functions within the Java programming language.

 

What is the new Keyword in Java?

 

Creating objects using the new keyword is important as it is the main area of Java object-oriented programming. When you want to instantiate an object, then you use a new keyword with its class constructor, which allocates memory in the heap for the new object. For example, ClassName objectName = new ClassName(); makes a new class instance and initializes it using the constructor.

 

Not only does this process allocate memory and set up the object with values as specified in the constructor itself, but it also packs and decays pointers to the appropriate new values into the bitwise representation. It may be null if you declare a class-type variable without a new one. That is, it does not refer to any object. Moreover, after an object is no longer used, Java’s garbage collector takes care of the memory, freeing it up for the future. The new keyword is a savior in Java because it creates objects, a must-have for Java’s classes and methods.

 

Syntax of new Keywords in Java

ClassName objName = new ClassName()

Process of Object Creation in Java

The process of object creation in Java involves several steps.

 

  • Declare a variable: A variable declared with the class type of an object does not contain the object itself; instead, it refers to that object.

 

Syntax

ClassName objName

 

  • Allocate Memory: The new keyword allocates memory for the object on the heap, which is reserved for the object’s fields and methods.

 

Syntax

ClassName objName = new ClassName()

 

  • Initialize the object: The class’s constructor is called to initialize the object’s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup.

 

The following program demonstrates the Object Creation in Java.

 

Program

class Person{ String name ; int age ; public Person(String name, int age){ this.name = name ; this.age = age ; } } class Main{ public static void main(String args[]){ Person ob = new Person("Harry Potter", 32) ; System.out.println("Name of Person is ="+ob.name)  ; System.out.println("Name of Person is ="+ob.age); } }

Output

Name of Person is =Harry Potter Name of Person is =32

Points to Remember about new Keyword in Java

Some points must be remembered about the new keyword in Java language.

 

  • A new keyword in Java language is used to create an instance of a class, also known as an object.
  • It allocates memory for the object on the heap, the memory space where objects are stored.
  • A new keyword in Java calls the constructor of a class to initialize the object’s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup.
  • When creating immutable objects, like instances of the String class, using new will create a new object each time, even if the content in the same.
  • When creating an object with the new keyword in the Java language, the object is created on the heap. It will remain in memory until it is no longer reachable by any reference in the source code. At that point, it will be eligible for garbage collection.

What is the use of new keywords in Java?

 

Some of the uses of new keywords in Java language.

 

  • Memory Allocation: The new keyword allocates memory for an object on the heap, the memory space where objects are stored in Java. We cannot allocate the memory without using teh new keyword.
  • Object Initialization: The new keyword in Java is also called a class constructor, which initializes the object‘s state. The constructor sets the initial values for the object’s fields and performs any other necessary setup. The constructor cannot be called for the “new” keyword, and the object would not be properly initialized.
  • Object Polymorphism: A new keyword for creating instances of subclasses inherited from a superclass. The runtime type of the object will be the type of the subclass. It enables the object to use the method overridden by the subclass and not the one inherited from the superclass.
  • Dynamic Memory Allocation: A new keyword in Java allows you to create arrays dynamically. This means the size of the array can be determined during runtime.

 

Also Read: Constructors in Java

Examples of new keyword in Java

Let’s see how new keywords work in Java with the help of the following examples.

 

Example 1  of new keyword in Java

 

class Student{ String name ; Student(String name){ this.name = name ; } } class Main{ public static void main(String args[]){ Student ob = new Student("Neeraj Kumar") ; System.out.println("Name of the Developer = "+ob.name); } }

Output

Name of the Developer = Neeraj Kumar

Example 2: Calling the constructor using a new Keyword.

class Person{ Person(){ System.out.println("Harry Potter"); } } class Main{ public static void main(String args[]){ Person ob = new Person() ; } }  

Output

Harry Potter

Example 3 of new Keyword in Java

class Main{ public static void main(String args[]){ int arr[] = new int[5] ;  for(int i =0 ;i< 5;i++){ arr[i] = i ; } System.out.println("The value of element at index 3 is = "+arr[i]); } }

Output

The value of element at index 3 is = 3

Example 5 of new Keyword in Java

 

The following program shows the usage of new keywords in Java with Collection Framework.

 

Program

import java.util.*; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Voldemort"); list.add("ComputerDekho"); System.out.println(list); } }

Output

[Voldemort, ComputerDekho]
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Conclusion

 

Creating Objects and Memory Allocation in a class instance of how Java uses the new keyword is necessary. This allows us to have a simple and efficient way to make objects, each with a unique state and behavior. Using Java’s object-oriented features, like encapsulation and inheritance, the new keyword saves us from copying all these features in our source code. For Java programmers, it is essential to know how to use it efficiently because it will be the base for classes and objects working in Java applications. This concept allows developers to create robust and maintainable software solutions. Dig deeper into Java with Hero Vired’s Certificate Program in Full Stack Development.

FAQs
The new keyword is used to create new objects in Java. It allocates memory for the object and initializes it by invoking the class's constructor.
In the Java language, we can create objects using factory methods, clone methods, or serialization instead of directly using the new keyword. These approaches provide more control over object creation.
Attempting to create an object without using the new keyword will result in a compile-time error. The new keyword is essential for object instantiation.
You can use the new keyword in an initializer block to create the object and initialize instance variables before the constructor is called.
Yes, you can use the new keyword to instantiate static inner classes without needing an outer class instance.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

19 October, 12:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved