📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
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.
Comments
Post a Comment
Leave Comment