The new keyword is used to create an object of a class.
- It allocates a memory to the object during runtime.
- It invokes the specified constructor of the class to create the object.
Java new Keyword Example
Here, we have a class JavaExample
, which contains a variable and a method. In order to access the variable and method, we need to create an object of this class. In this example, we have created an object obj
of this class using new keyword.
public class JavaExample { int num = 100; //variable public void demo(){ System.out.println("hello"); } public static void main(String[] args) { JavaExample obj = new JavaExample(); System.out.println(obj.num); obj.demo(); } }
Output:
100 hello
In the above example, we have used the following statement to create the object.
JavaExample obj = new JavaExample();
This object creation can be divided into three parts:
Declaration: Class name followed by object name. This creates a reference of the class.
JavaExample obj
Instantiation: new keyword followed by the constructor of the class. This creates an object of the class, whose constructor is being called.
new JavaExample();
Initialization: Initializing the reference of class with the created object.
JavaExample obj = new JavaExample();
Example 2: new keyword with array
Here, we are using the new keyword to create an array object.
public class JavaExample { public static void main(String[] args) { //int array arr of size 3 int arr[] = new int[3]; arr[0] = 101; arr[1] = 102; arr[2] = 103; for(int i: arr){ System.out.println(i); } } }
Output:
101 102 103
Example 3: new keyword with strings
We can also create an object of String class using new keyword. There is a difference between simple assignment and assignment using new, the difference is covered in Java String Tutorial.
public class JavaExample { public static void main(String[] args) { String s1 = new String("Hello"); String s2 = new String("World!"); System.out.println(s1+" "+s2); } }
Output:
Hello World!
Example 4: Creating an object of a collection class
We can also use new keyword to create object of various collection classes. In the following example, we are creating an object of ArrayList class.
import java.util.ArrayList; public class JavaExample { public static void main(String[] args) { ArrayList<Integer> arrList = new ArrayList<>(); arrList.add(101); arrList.add(201); arrList.add(301); arrList.add(401); for(int i: arrList){ System.out.println(i); } } }
Output:
