1. Java Math.abs() Method
Syntax:
javapublic static int abs(int value)
Explanation:
The Math.abs()
method is used to find the absolute value of a given numeric value. It takes a single argument value
, which can be of type int, long, float, or double, and returns its absolute value as an integer.
Code Example:
javaint number = -10;
int absoluteValue = Math.abs(number);
System.out.println("Absolute value of " + number + " is " + absoluteValue);
Output:
Absolute value of -10 is 10
2. Java Math.round() Method
Syntax:
javapublic static long round(double value)
Explanation:
The Math.round()
method is used to round a floating-point number to the nearest long or int value. It takes a double value
as an argument and returns the closest long value to the given number.
Code Example:
javadouble num = 3.6;
long roundedNum = Math.round(num);
System.out.println("Rounded value of " + num + " is " + roundedNum);
Output:
Rounded value of 3.6 is 4
3. Java Math.ceil() Method
Syntax:
javapublic static double ceil(double value)
Explanation:
The Math.ceil()
method is used to find the smallest integer that is greater than or equal to the given value. It takes a double value
as an argument and returns the smallest double value that is greater than or equal to the given number.
Code Example:
javadouble num = 5.3;
double ceilValue = Math.ceil(num);
System.out.println("Ceil value of " + num + " is " + ceilValue);
Output:
Ceil value of 5.3 is 6.0
4. Java Math.floor() Method
Syntax:
javapublic static double floor(double value)
Explanation:
The Math.floor()
method is used to find the largest integer that is less than or equal to the given value. It takes a double value
as an argument and returns the largest double value that is less than or equal to the given number.
Code Example:
javadouble num = 7.8;
double floorValue = Math.floor(num);
System.out.println("Floor value of " + num + " is " + floorValue);
Output:
Floor value of 7.8 is 7.0
5. Java Math.min() Method
Syntax:
javapublic static int min(int a, int b)
public static long min(long a, long b)
public static float min(float a, float b)
public static double min(double a, double b)
Explanation:
The Math.min()
method is used to find the minimum of two given numeric values. It has overloaded versions for int, long, float, and double types. It takes two arguments a
and b
, and returns the smaller of the two values.
Code Example:
javaint num1 = 15;
int num2 = 9;
int minValue = Math.min(num1, num2);
System.out.println("Minimum value between " + num1 + " and " + num2 + " is " + minValue);
Output:
Minimum value between 15 and 9 is 9
These are some of the important Math methods available in Java that can be utilized for performing various mathematical operations in your programs.
0 Comments