
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get the Maximum of Two Numbers Using Math.max in Java
To obtain the maximum of two numbers using Math.max in Java, we use the java.lang.Math.max() method. The Math.max() accepts two numbers and returns the greater of the two. The result is closer to positive infinity on the number line. Even if one of the values is not a number(NaN), the result is NaN.
Declaration - The java.lang.Math.max() method is declared as follows −
public static int max(int a, int b) public static double max(double a, double b) public static long max(long a, long b) public static float max(float a, float b)
Let us see a program to get the maximum of two numbers using the Math.max() method
Example
import java.lang.Math; public class Example { public static void main(String[] args) { // declaring and intializing some integer values int a = 10; int b = 9; // declaring and intializing some float values float c = 10.00f; float d = 9.99f; // declaring and initializing some double values double x = 300.01d; double y = 290.344d; // declaring and initializing some long values long r = 123456l; long s = 35678l; System.out.println("Maximum of " + a +" and " + b +" is " + Math.max(a,b)); System.out.println("Maximum of " + c +" and " + d +" is " + Math.max(c,d)); System.out.println("Maximum of " + x +" and " + y +" is " + Math.max(x,y)); System.out.println("Maximum of " + r +" and " + s +" is " + Math.max(r,s)); } }
Output
Maximum of 10 and 9 is 10 Maximum of 10.0 and 9.99 is 10.0 Maximum of 300.01 and 290.344 is 300.01 Maximum of 123456 and 35678 is 123456
Advertisements