此方法在java.lang包中可用。
此方法用于返回方法中给定参数的绝对值。
这是一个静态方法,因此也可以使用类名访问此方法。
该方法的返回类型取决于给定的参数数据类型,这里我们在方法中传递long数据类型,这意味着该方法的返回类型很长。
在此方法中,我们仅将一个参数作为参数传递给Math类的方法。
此方法不会引发任何异常。
在此方法中,如果给定参数等于long.MIN_VALUE的值,则它将返回相同的负值。
这是一个可重写的方法,因此可以使用该方法的各种版本,但是在这里我们正在寻找long数据类型参数,因此以下语法如下:
语法:
public static long abs(long l){ }
参数:
long l-一个长值,其绝对值将找到。
返回值:
此方法的返回类型为long,将绝对值返回为long。
注意:
如果我们传递一个正长整数,它将返回相同的值。
如果我们传递一个负长整数,它将返回不带符号的值,即它将返回正长整数。
如果我们传递正零或负零(-0),则它将返回零而没有符号。
如果我们传递一个无穷大参数,它将返回异常。
如果我们传递“ NaN”(非数字),则返回相同的值,即“ NaN”。
//Java程序演示的例子 //Math类的abs(long l)方法 class AbsLongTypeMethod { public static void main(String[] args) { //我们声明了几个变量 long a = 123121l; long b = -123121l; long c = 0l; long d = -0l; /* long e = 74587l/0l; long f = -7458l/0l; */ //通过使用abs(long l)方法,我们将找到 //方法中给定参数的绝对值 System.out.println("The absolute value of a is : " + Math.abs(a)); System.out.println("The absolute value of b is : " + Math.abs(b)); System.out.println("The absolute value of c is : " + Math.abs(c)); System.out.println("The absolute value of d is : " + Math.abs(d)); /* //在下面的代码中将抛出异常 //因为我们正在传递无限 System.out.println("The absolute value of e is : "+Math.abs(e)); System.out.println("The absolute value of f is : "+Math.abs(f)); */ } }
输出结果
E:\Programs>javac AbsLongTypeMethod.java E:\Programs>java AbsLongTypeMethod The absolute value of a is : 123121 The absolute value of b is : 123121 The absolute value of c is : 0 The absolute value of d is : 0