new keyword in java
The " new "
keyword is used to create a new instance or new object of a class.
Example
- String str = new String("Welcome to Java new keyword");
String str = new String("Welcome to Java new keyword");
Create custom class and object
- class Vehicle {
- }
- Vehicle vehicle = new Vehicle();
- class Person {
- }
- Person person = new Person();
class Vehicle { } Vehicle vehicle = new Vehicle(); class Person { } Person person = new Person();
Create a new array object:
- String[] names = new String[5];
String[] names = new String[5];
Create a new ArrayList object:
- ArrayList hobbies = new ArrayList();
ArrayList hobbies = new ArrayList();
When we create object using new
, memory gets allocated in the heap for that object.
The argument following the new
keyword must be a class name followed by a series of constructor arguments in required parentheses.
The collection of arguments must match the signature of a constructor in the corresponding class.
The type of the variable on the left side of the =
must be assignment−compatible with the class or interface being instantiated.