Find maximum and minimum of two values in Java

Methods which can be used to find maximum of two values are

  • static int max(int a,int b) for finding maximum between integer values.
  • static long max(long a,long b) for finding maximum between long values.
  • static float max(float a,float b) for finding maximum between float values.
  • static double max(double a,double b) for finding maximum between double values.

All the methods belongs to Math class of java.lang package. Since all the methods are static, we can call the methods directly using class name.


Example 1 (max between int values)

class MathTest{

public static void main(String args[]){

int num1=15,num2=20;

System.out.println("Maximum bw "+num1+" and "+num2+" is "+Math.max(num1,num2));

}

}

Output 1

Maximum bw 15 and 20 is 20


Example 2 (max between long values)

class MathTest{

public static void main(String args[]){

long a1=123415,a2=24444440;

System.out.println("Maximum bw "+a1+" and "+a2+" is "+Math.max(a1,a2));

}

}

Output 2

Maximum bw 123415 and 24444440 is 24444440


Example 3 (max between float values)

class MathTest{

public static void main(String args[]){

float f1=123.64f,f2=2.3f;

System.out.println("Maximum bw "+f1+" and "+f2+" is "+Math.max(f1,f2));

}

}

Output 3

Maximum bw 123.64 and 2.3 is 123.64


Example 4 (max between double values)

class MathTest{

public static void main(String args[]){

double d1=123.64999999,d2=255.3999999999;

System.out.println("Maximum between two values is "+Math.max(d1,d2));

}

}

Output 4

Maximum bw 123.64 and 2.3 is 123.64


Methods which can be used to find minimum of two values are

  • static int min(int a,int b) for finding minimum between integer values.
  • static long min(long a,long b) for finding minimum between long values.
  • static float min(float a,float b) for finding minimum between float values.
  • static double min(double a,double b) for finding minimum between double values.

Example 1 (min between int values)

class MathTest{

public static void main(String args[]){

int num1=105,num2=210;

System.out.println("Minimum bw "+num1+" and "+num2+" is "+Math.min(num1,num2));

}

}

Output 1

Minimum bw 105 and 210 is 105


Example 2 (min between long values)

class MathTest{

public static void main(String args[]){

long a1=123415,a2=24444440;

System.out.println("Minimum bw "+a1+" and "+a2+" is "+Math.min(a1,a2));

}

}

Output 2

Minimum bw 123415 and 24444440 is 123415


Example 3 (min between float values)

class MathTest{

public static void main(String args[]){

float f1=123.64f,f2=2.3f;

System.out.println("Minimum bw "+f1+" and "+f2+" is "+Math.min(f1,f2));

}

}

Output 3

Minimum bw 123.64 and 2.3 is 2.3


Example 4 (min between double values)

class MathTest{

public static void main(String args[]){

double d1=123.64999999,d2=255.3999999999;

System.out.println("Minimum between two values is "+Math.min(d1,d2));

}

}

Output 4

Minimum between two values is 123.64999999