New keyword in Java


Yes, it is similar to a new keyword of C++. a new keyword is used to initialize/create an object. See the following example −

Employee employee = new Employee();

Here new keyword is used to create an object of class Employee.

new Employee() invokes the constructor of the class Employee.

new keyword can also be used without assigning the object to a reference variable. See the example −

String name = new Employee().getName();

Here we are creating an object using new keyword and then invoked a method getName() on the object and passed the result to a variable.

Updated on: 06-Mar-2020

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements