The new operator in Java

Java 8Object Oriented ProgrammingProgramming

The new operator is used in Java to create new objects. It can also be used to create an array object.

Let us first see the steps when creating an object from a class −

  • Declaration − A variable declaration with a variable name with an object type.

  • Instantiation − The 'new' keyword is used to create the object.

  • Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Now, let us see an example −

Example

public class Puppy {
   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Passed Name is : " + name );
   }
   public static void main(String []args) {
      // Following statement would create an object myPuppy
      Puppy myPuppy = new Puppy( "jackie" );
   }
}

Output

Passed Name is : jackie

Now, let us see an example to create an array using the new operator −

Example

public class Main {
   public static void main(String[] args) {
      double[] myList = new double[] {1.9, 2.9, 3.4, 3.5};
      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

Output

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
raja
Updated on 20-Sep-2019 11:23:09

Advertisements