JAVA MATH

Maha

JAVA MATH 

Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc. The basic methods and constructors provided by Java programming language.
Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric function.

Java Math Method

  • Math.min(): this method returns the smallest of two values.
  • Math.max(): this method returns the largest of two values.
  • Math.abs(): this method returns the absolute value of the value provided.
  • Math.round(): this method is used to round off the decimal numbers to the nearest value.
  • Math.sqrt(): this method returns the square root of a number given.
  • Math.cbrt(): this method returns the cube root of a given number.
1. Math.max() 
    Math.max(a, b): Returns the larger of a and b.

Example:
    public static void main(String[] args) {
        System.out.println(Math.max(10, 20)); 
    }
}
Output:
20

2. Math.min() 
    Math.min(a, b): Returns the smaller of a and b.

Example:

public class MathExample {
    public static void main(String[] args) {
        System.out.println(Math.min(10, 20)); 
    }
} 
Output: 
10 

3. Math.abs() – Absolute Value

public class MathExample {
Returns the absolute (positive) value of a number.

Example:

public class MathExample {
    public static void main(String[] args) {
        int a = -10;
        double b = -5.7;

        System.out.println(Math.abs(a));  
        System.out.println(Math.abs(b));  
    }
}

Output: 
10
5.7


4. Math.pow() – Power Function
    Returns the value of a raised to the power of b (a^b).

Example:

public class MathExample {
    public static void main(String[] args) {
        System.out.println(Math.pow(2, 3));   
        System.out.println(Math.pow(5, 2));   
    }
}

Output: 
8.0
25.0


5. Math.sqrt() – Square Root
    Returns the square root of a given number.

Example:

public class MathExample {
    public static void main(String[] args) {
        System.out.println(Math.sqrt(16));  
        System.out.println(Math.sqrt(25));  
    }
}

Output: 
4.0
5.0

6. Math.round() – Rounding Numbers
    Math.round(x): Rounds a floating-point number to the nearest integer.

Example:

public class MathExample {
    public static void main(String[] args) {
        System.out.println(Math.round(4.3));  
        System.out.println(Math.round(4.6)); 
    }
}

Output: 
4
5


7. Math.random() – Generate a Random Number
    Generates a random double value between 0.0 and 1.0.

Example:

public class MathExample {
    public static void main(String[] args) {
        double randomNumber = Math.random();
        System.out.println(randomNumber); 
    }
}

Output: 
A random number between 0.0 and 1.0




Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send