Java 中的新運算子


Java 中的新運算子用於建立新物件。它還可用於建立陣列物件。

讓我們首先了解從類中建立物件時的步驟 −

  • 宣告 −帶物件型別的變數名稱的變數宣告。

  • 例項化 −使用“new”關鍵字建立物件。

  • 初始化 −“new”關鍵字後面是呼叫建構函式。此呼叫會初始化新物件。

現在,讓我們看一個示例 −

示例

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" );
   }
}

輸出

Passed Name is : jackie

現在,讓我們看一個使用新運算子建立陣列的示例 −

示例

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);
   }
}

輸出

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

更新於: 20-Sep-2019

6K+ 瀏覽

開始你的 職業生涯

完成課程後獲得認證

開始
Advertisement