new keyword in java

The " new " keyword is used to create a new instance or new object of a class.

Example
1
String str = new String("Welcome to Java new keyword");
String str = new String("Welcome to Java new keyword");


Create custom class and object

1
2
3
4
5
6
7
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:

1
String[] names = new String[5];
String[] names = new String[5];


Create a new ArrayList object:

1
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.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on