Everything You Need To Know About Java Math abs()

Published on Sep 13,2019 2.2K Views

Everything You Need To Know About Java Math abs()

edureka.co

This article will introduce you to Java Math Abs() method, and in the process tell you how to generate absolute value of an argument. Following pointers will be covered in this article,

Table of Content

Lets begin!!

Java Math abs()

following are the overloaded abs methods from Math class –

a, b c or d can be negative values, whereas returns will be positive value, but if argument is Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int value or long value, the result is that same value, that is negative value. Above methods can take infinity and NaN as argument and return the same respectively

Moving on with this article on Java Math abs()

Examples of abs()

Moving on with this article on Java Math abs()

int
public class Example1{
public static void main(String args[]){
int a = 56;
int b = -47;
//printing absolute value of int and Integer.MIN_VALUE
System.out.println(Math.abs(a));
System.out.println(Math.abs(b));
System.out.println(Math.abs(Integer.MIN_VALUE));
}
}

Output
56
47
-2147483648

Moving on with this article on Java Math abs()

double –

public class Example2
{
public static void main(String args[])
{
double x = -27.64;
double y = -394.27;
//printing absolute value of double type
System.out.println(Math.abs(x));
System.out.println(Math.abs(y));
System.out.println(Math.abs(7.0 / 0)); //infinity
}
}

Output –
27.64
394.27
Infinity

Moving on with this article on Java Math abs()

float-

public class Example3
{
public static void main(String args[])
{
float x = -63.02f;
float y = -438.0f;
//printing absolute value of float type
System.out.println(Math.abs(x));
System.out.println(Math.abs(y));
}
}

Output
63.02
438.0

Moving on with this article on Java Math abs()

long-

public class Example4
{
public static void main(String args[])
{
long x = 78730363;
long y = -4839233;
//printing absolute value of long type
System.out.println(Math.abs(x));
System.out.println(Math.abs(y));
System.out.println(Math.abs(Long.MIN_VALUE));
}
}

Output
78730363
4839233
-9223372036854775808

Now after executing the above program you would have understood the Java Math abs() Method. Thus we have come to an end of this article. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES