Java Math abs()

abs() accepts an argument and returns its absolute value.

Datatype of the argument could be double, float, int or long and the return type would be same as that of argument.

If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

Following is the syntax of abs() method.

int result = abs(int value)
float result = abs(float value)
double result = abs(double value)
long result = abs(long value)

Example 1 – Math.abs(int)

In the following example, we pass int value as argument to abs() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		int x = -12;
		int a = Math.abs(x);
		System.out.println(a);
	}
}

Output

12
ADVERTISEMENT

Example 2 – Math.abs(float)

In the following example, we pass float value as argument to abs() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		float x = -12.25F;
		float a = Math.abs(x);
		System.out.println(a);
	}
}

Output

12.25

Example 3 – Math.abs(double)

In the following example, we pass double value as argument to abs() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		double x = -12.252366822153;
		double a = Math.abs(x);
		System.out.println(a);
	}
}

Output

12.252366822153

Example 4 – Math.abs(long)

In the following example, we pass long value as argument to abs() method.

Java Program

public class MathExample {
	public static void main(String[] args) {
		long x = -812252366822153L;
		long a = Math.abs(x);
		System.out.println(a);
	}
}

Output

812252366822153

Conclusion

In this Java Tutorial, we learned about Java Math.abs() function, with example programs.