Java

What is new Keyword in Java

To construct a class object, use the new keyword.

  • During runtime, it allocates memory for the object.
  • To build the object, it calls the class’s designated constructor.

Java new Keyword Example

Here, a variable and a method are found in the class JavaExample. We must establish a class object in order to access the variable and function. In this example, the new keyword was used to create an object of this type called obj.

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

We created the object in the aforementioned example using the following command.

JavaExample obj = new JavaExample();

This object creation can be divided into three parts:

Declaration: object name coming after the class name. This establishes a class reference.

JavaExample obj

Instantiation: after the class’s constructor comes the new keyword. By doing this, a new instance of the class whose constructor is being called is created.

new JavaExample();

Initialization: establishing the class reference with the newly formed object.

JavaExample obj = new JavaExample();

Example 2: new keyword with array

Here, we’re creating an object for an array using the new keyword.

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

Using the new keyword, we can also construct an object of the String type. Java String Tutorial discusses the distinction between a basic assignment and an assignment using new.

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

The new keyword can also be used to generate objects from different collection classes. In the example below, we are building an ArrayList class object.

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:

new keyword to create object example

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button