Tuesday 31 May 2022

Java math max(): Find the maximum of two numbers

‘java.lang.Math’ class provides max method to get the maximum of two numbers. ‘max’ method is available in below overloaded forms.

 

public static double max(double a, double b)

public static int max(int a, int b)

public static long max(long a, long b)

public static float max(float a, float b)

‘max’ method return the larger of a and b.

 

Example

Math.max(10, 20)

 


 

MathMaxDemo.java

package com.sample.app;

public class MathMaxDemo {
	
	public static void main(String[] args) {
		int a = 10;
		int b = 11;
		
		long c = 12l;
		long d = 13l;
		
		float e = 3.23f;
		float f = 3.24f;
		
		double g = 4.23;
		double h = 4.24;
		
		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 " + e + " and " + f + " is : " + Math.max(e, f));
		System.out.println("Maximum of " + g + " and " + h + " is : " + Math.max(g, h));
	}

}

Output

Maximum of 10 and 11 is : 11
Maximum of 12 and 13 is : 13
Maximum of 3.23 and 3.24 is : 3.24
Maximum of 4.23 and 4.24 is : 4.24






Previous                                                 Next                                                 Home

No comments:

Post a Comment