Java Integer max() method
The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max.
Syntax
public static int max(int a, int b)
Parameters
The parameters ‘a’ and ‘b’ represent the first and second operand.
Return Value
This method returns the greater of ‘a’ and ‘b’.
Example 1
public class JavaIntegerMaxExample1 { public static void main(String[] args) { Integer val1=134; Integer val2=567; // returns the greater of two values int max=Integer.max(val1,val2); System.out.println("The greater number between "+val1+" and "+val2+" is "+max); } }
Output
The greater number between 134 and 567 is 567
Example 2
import java.util.Scanner; public class JavaIntegerMaxExample2 { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); System.out.print("Enter the total number"); int n=scanner.nextInt(); System.out.println("Enter "+n+" elements : "); int[] a= new int[n]; for (int i=0;i<n;i++ ){ a[i]=scanner.nextInt(); } for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++){ int max=Integer.max(a[i],a[j]); if (a[j]==max){ a[j]=a[i]; a[i] =max ; } } } System.out.print("Descending Order : "); for (int i=0;i<n;i++) { System.out.print(a[i]+" "); } } }
Output
Enter the total number5 Enter 5 elements : 12 56 90 34 76 Descending Order : 90 76 56 34 12
Example 3
import java.util.Scanner; public class JavaIntegerMaxExample3 { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); System.out.print("Enter the total number : "); int n=scanner.nextInt(); System.out.println("Enter "+n+" elements : "); int max=0; int[] a= new int[n]; for (int i=0;i<n;i++ ){ a[i]=scanner.nextInt(); } for (int i=0;i<n;i++){ for (int j=i+1;j<n;j++){ max=Integer.max(a[i],a[j]); if (a[j]==max){ a[j]=a[i]; a[i] =max ; } } } System.out.println("The greatest number is "+max+" "); } }
Output
Enter the total number : 6 Enter 6 elements : 12 876 55 678 34 223 The greatest number is 876