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
Advertisement
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP