Java Integer.max()方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-max-method

Java max()方法是java.lang包的Integer类的一部分,由Math类的Math.max()方法指定。此方法用于返回作为参数传递的两个数字中数值较大的值(最大值)。

如果传递了一个正数和一个负数,则返回正值,但是如果传递的两个数字都是负数,则返回较小的数值。

语法:

public static int max(int a, int b)

参数:

传递的参数是用户用来检查传递的两个数字的最大值的数值。

返回:

作为参数传递的两个值中数值较大的值。

例 1:

这里,取一个正数和一个负数,因此返回正值,如果两者都为负值,则返回较小的值。

import java.lang.Integer;

public class StudyTonight {

  public static void main(String[] args) 
  {
    int x = 5485;
    int y = -3242;
    int z = -5645;
    // print the larger number between x and y 
    System.out.println("Greater number is " + Integer.max(x, y)); 
    // print the larger number between y and z
    System.out.println("Greater number is " + Integer.max(y, z)); 
  }
}

更大的数字是 5485 更大的数字是-3242

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

import java.util.Scanner; 

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
           System.out.println("Enter the Two values: ");  
           Scanner sc= new Scanner(System.in);  
           int a = sc.nextInt();  
           int b = sc.nextInt();              
           //Print the larger number between a and b 
           System.out.println("Larger value is " + Integer.max(a, b)); 
        }
        catch(Exception e)
        {
            System.out.println("Exception occurred...");
        }
    }  
}

输入两个值: 82 -67 较大的值是 82

                                              • T4】输入两个值: 43-67 较大的值是-43

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。