The new
keyword in Java is used to create new objects. It is one of the most fundamental and important keywords in the Java programming language. This article aims to explain the new
keyword and explore its inner workings, providing a clear understanding to both beginners and seasoned programmers.
If you don’t have a medium membership, you can use this link to reach the article without a paywall.
New
Keyword in Action
In Java, the new
keyword acts as a facilitator for the creation of new instances of classes, allowing the developer to initialize objects and allocate memory dynamically during runtime. So you use the new
keyword, when you instantiate an object in Java. It serves as a directive to the Java Virtual Machine (JVM) to allocate memory for a new object. Here's the simplest example:
MyClass object = new MyClass();
In this line, new MyClass()
tells the JVM to create an object of MyClass
type. For the resulting object, object
serves as the reference variable for the newly instantiated object.