Java new Keyword:
In Java programming, the new keyword plays a crucial role in dynamically allocating memory and initializing objects. It is fundamental to object-oriented programming (OOP) and allows developers to create instances of classes, arrays, and more. Let's explore how to use new effectively in different contexts.
Creating Objects
The primary use of the new keyword is to instantiate objects from classes. Here's how you create an object in Java:
// Example: Creating an object of class Person
Person person = new Person();
Initializing Arrays
Java arrays are also created using the new keyword. You specify the size of the array during creation:
// Example: Initializing an array of integers
int[] numbers = new int[5];
Here, new int[5] creates an array of 5 integers, initialized with default values (0 for int).
Creating Anonymous Objects
You can create objects without assigning them to a variable, known as anonymous objects. They are useful for invoking methods without storing references:
// Example: Creating an anonymous object
new Person().sayHello();
Here, new Person() creates an anonymous instance of Person and immediately calls its sayHello() method.
Dynamic Memory Allocation
The new keyword dynamically allocates memory at runtime, which is managed by Java's garbage collector. This enables flexible memory management without manual memory allocation or deallocation.
Constructor Invocation
When you use new to create an object, Java invokes the constructor of the class to initialize the object. Constructors can be parameterized to initialize object state during instantiation.
public class Person {
private String name;
// Constructor with parameters
public Person(String name) {
this.name = name;
}
public void introduce() {
System.out.println("Hello, my name is " + name);
}
public static void main(String[] args) {
// Creating an object using constructor
Person person = new Person("Alice");
person.introduce(); // Output: Hello, my name is Alice
}
}
Example on Java ‘new’ operator
Output: