Java Integer.max() – Examples

In this tutorial, we will learn about Java Integer.max() method, and learn how to use this method to get the maximum of given two integer values, with the help of examples.

max()

Integer.max(a, b) returns the greater of two integer values: a and b.

Syntax

The syntax of max() method with two integers for comparison as parameters is

</>
Copy
Integer.max(int a, int b)

where

ParameterDescription
aThe first integer to compare.
bThe second integer to compare.

Returns

The method returns value of type int.

Example 1 – max(a, b) : a<b

In this example, we will take two integers in a and b such that a is less than b. We will find the maximum of a and b using Integer.max() method. Since a is less than b , max() should return the value of b.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		int a = 5;
		int b = 7;
		int result = Integer.max(a, b);
		System.out.println("Result of max("+a+", "+b+") = " + result);
	}
}

Output

Result of max(5, 7) = 7

Example 2 – max(a, b) : a=b

In this example, we will take two integers in a and b such that a is equal to b in value. We will find the maximum of a and b using Integer.max() method. Since a equals bin value, max() returns the value of a or b.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		int a = 5;
		int b = 5;
		int result = Integer.max(a, b);
		System.out.println("Result of max("+a+", "+b+") = " + result);
	}
}

Output

Result of max(5, 5) = 5

Example 3 – max(a, b) : a>b

In this example, we will take two integers in a and b such that a is greater than b. We will find the maximum of a and b using Integer.max() method. Since a is greater than b , max() should return the value of a.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args){
		int a = 7;
		int b = 5;
		int result = Integer.max(a, b);
		System.out.println("Result of max("+a+", "+b+") = " + result);
	}
}

Output

Result of max(7, 5) = 7

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Integer.max() method, and also how to use this method with the help of Java example programs.