max()
方法返回指定参数中的最大值。
示例
class Main {
public static void main(String[] args) {
// compute max of 88 and 98
System.out.println(Math.max(88, 98));
}
}
// Output: 98
Math.max() 语法
max()
方法的语法是:
Math.max(arg1, arg2)
这里,max()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
max() 参数
max()
方法接受两个参数。
- arg1/arg2 - 返回最大值之间的参数
注意:参数的 数据类型 必须是 int
、long
、float
或 double
。
max() 返回值
- 返回指定参数中的最大值
示例 1:Java Math.max()
class Main {
public static void main(String[] args) {
// Math.max() with int arguments
int num1 = 35;
int num2 = 88;
System.out.println(Math.max(num1, num2)); // 88
// Math.max() with long arguments
long num3 = 64532L;
long num4 = 252324L;
System.out.println(Math.max(num3, num4)); // 252324
// Math.max() with float arguments
float num5 = 4.5f;
float num6 = 9.67f;
System.out.println(Math.max(num5, num6)); // 9.67
// Math.max() with double arguments
double num7 = 23.44d;
double num8 = 32.11d;
System.out.println(Math.max(num7, num8)); // 32.11
}
}
在上面的示例中,我们使用了带有 int
、long
、float
和 double
类型参数的 Math.max()
方法。
示例 2:获取数组中的最大值
class Main {
public static void main(String[] args) {
// create an array of int type
int[] arr = {4, 2, 5, 3, 6};
// assign first element of array as maximum value
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
// compare all elements with max
// assign maximum value to max
max = Math.max(max, arr[i]);
}
System.out.println("Maximum Value: " + max);
}
}
在上面的示例中,我们创建了一个名为 arr 的 数组。最初,变量 max 存储了数组的第一个元素。
在这里,我们使用了 for 循环 来访问数组的所有元素。请注意这一行:
max = Math.max(max, arr[i])
Math.max()
方法将变量 max 与数组的所有元素进行比较,并将最大值赋给 max。
另请阅读