此方法在java.lang包中可用。
此方法用于返回方法中给定参数的绝对值。
这是一个静态方法,因此也可以使用类名访问此方法。
此方法的返回类型取决于给定的参数数据类型,这里我们在方法中传递int数据类型,这意味着该方法的返回类型为int。
在此方法中,我们仅将一个参数作为参数传递给Math类的方法。
此方法不会引发任何异常。
这是一个可重写的方法,因此可以使用该方法的各种版本,但是在这里我们正在寻找int数据类型参数,因此以下语法如下:
语法:
public static int abs(int i){ }
参数:
int i-可以找到其绝对值的整数值。
返回值:
此方法的返回类型为int,以整数形式返回绝对值。
注意:
如果我们传递一个正整数,它将返回相同的值。
如果我们传递一个负整数,它将返回不带符号的值,即它将返回正整数。
如果我们传递正零或负零(-0),则它将返回零而没有符号。
如果我们传递一个无穷大参数,它将返回异常。
如果我们传递“ NaN”(非数字),则返回相同的值,即“ NaN”。
//Java程序演示的例子 //数学类的abs(int i)方法 class AbsIntTypeMethod { public static void main(String[] args) { //我们声明了几个变量 int a = 123121; int b = -123121; int c = 0; int d = -0; /* int e = 7/0; int f = -7/0; */ //通过使用abs(int i)方法,我们将计算 //方法中给定参数的绝对值 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 AbsIntTypeMethod.java E:\Programs>java AbsIntTypeMethod 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