Java Math min, max, and abs Methods

Introduction

The min() and max() methods return the minimum and maximum numbers of two numbers: int, long, float, or double.

For example, max(4.4, 5.0) returns 5.0, and min(3, 2) returns 2.

The abs method returns the absolute value of the number ( int, long, float, or double).

For example,

Math.max(2, 3)       //3 
Math.max(2.5, 3)     //4.0 
Math.min(2.5, 4.6)   //2.5 
Math.abs(-2)         //2 
Math.abs(-2.1)       //2.1 

Use Java Math min() to find the smallest number of three.


public class Main
{

  public static void main( String[] args )
  {/*from   w  w w  .  j  av  a  2s .  c o  m*/
    java.util.Scanner input = new java.util.Scanner( System.in );
    
    System.out.print( "Enter to first number: " );
    int number1 = input.nextInt();
    
    System.out.print( "Enter to seconde number: " );
    int number2 = input.nextInt();
    
    System.out.print( "Enter to third number: " );
    int number3 = input.nextInt();
    
    System.out.printf( "The menimum number is: %d%n", minimumTree( number1, number2, number3 ) );
  }
  
  public static int minimumTree( int number1, int number2, int number3 )
  {
    return Math.min( number1, Math.min( number2, number3 ) );
  }

}



PreviousNext

Related