Java Math

In java Math is a class, which is available in java.lang package. Math class contains many predefined methods we can use those methods to perform required mathematical operations.

Math.max(x,y)

The Math.max(x,y) method can be used to find the highest value of x and y:


  public class MathsExamples {
    public static void main(String[] args) {
      int x = 5;
      int y = 10;
      System.out.println(Math.max(x, y));  
    }
  }
Math.min(x,y)

The Math.min(x,y) method can be used to find the lowest value of x and y:


  public class MathsExamples {
    public static void main(String[] args) {
      int x = 5;
      int y = 10;
      System.out.println(Math.min(x, y));  
    }
  }
Math.sqrt(x,y)

The Math.sqrt(x,y) method returns the correctly rounded positive square root value, return data type is double

  1. If the argument is NaN or less than zero, then the result is NaN.
  2. If the argument is positive infinity, then the result is positive infinity.
  3. If the argument is positive zero or negative zero, then the result is the same as the argument.

  public class MathsExamples {
    public static void main(String[] args) {
      int x = 5;
      System.out.println(Math.sqrt(x));  
    }
  }
Math.abs(x,y)

The Math.abs(x) method Returns the absolute value of a double value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned

  1. If the argument is positive zero or negative zero, the result is positive zero.
  2. If the argument is infinite, the result is positive infinity.
  3. If the argument is NaN, the result is NaN.

  public class MathsExamples {
    public static void main(String[] args) {
      int x = -4.8;
      System.out.println(Math.max(x));  
    }
  }
Math.ceil(x)

The Math.ceil(x) is a Java Math utility method used to round a number UP to the nearest integer value. It accept double as an input and output. For example if we pass 10.1890 it will round-up to the 11.0, if we pass the -10.1890 then it will round-up to the -10.0

  1. If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
  2. If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
  3. If the argument value is less than zero but greater than -1.0, then the result is negative zero.

  public class MathsExamples {
    public static void main(String[] args) {
      int x = -10.1890;
      System.out.println(Math.ceil(x));  
    }
  }