In this guide, you will learn about the Math max() method in Java programming and how to use it with an example.
1. Math max() Method Overview
Definition:
The max() method of Java's Math class is used to return the greater of two numbers provided as arguments.
Syntax:
1. Math.max(int a, int b)
2. Math.max(double a, double b)
3. Math.max(float a, float b)
4. Math.max(long a, long b)
Parameters:
- a and b: Two numbers of which the larger one will be returned. These can be of type int, double, float, or long.
Key Points:
- If either of the arguments is NaN, then the result will be NaN.
- The comparison is based on value, not on the data type. Hence, -0.0 is considered smaller than 0.0.
- The method is overloaded to support different data types.
2. Math max() Method Example
public class MaxExample {
public static void main(String[] args) {
System.out.println("Max of 42 and 58: " + Math.max(42, 58));
System.out.println("Max of 42.5 and 42: " + Math.max(42.5, 42));
System.out.println("Max of -42 and -58: " + Math.max(-42, -58));
System.out.println("Max of NaN and 42: " + Math.max(Double.NaN, 42));
System.out.println("Max of -0.0 and 0.0: " + Math.max(-0.0, 0.0));
}
}
Output:
Max of 42 and 58: 58 Max of 42.5 and 42: 42.5 Max of -42 and -58: -42 Max of NaN and 42: NaN Max of -0.0 and 0.0: 0.0
Explanation:
In the example:
1. Between the numbers 42 and 58, 58 is the maximum.
2. The maximum between 42.5 (double) and 42 (int) is 42.5.
3. For negative numbers -42 and -58, the number -42 is greater.
4. If any of the arguments is NaN, the result will be NaN.
5. For -0.0 and 0.0, since -0.0 is considered smaller, 0.0 is returned.
Related Java Math class method examples
- Java Math abs() example
- Java Math ceil() example
- Java Math floor() example
- Java Math max() example
- Java Math pow() example
- Java Math sqrt() example
- Java Math random() example
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment