Java Integer shortValue()方法

来源:这里教程网 时间:2026-02-17 20:51:19 作者:

Java Integer shortValue()方法

Integer.shortValue()是java.lang的一个内置方法,用于返回短类型的Integer的值。

语法

public short shortValue()

参数 :该方法不接受任何参数。

返回值 :该方法在将该对象转换为short类型后,返回其代表的整数值。

下面的程序说明了Integer.shortValue()方法:

程序1: 对于正整数。

// Java program that demonstrates// Integer.shortValue() method  import java.lang.*;  public class Geeks {      public static void main(String[] args)    {          Integer sh_object = new Integer(763);          // It will return the value of this Integer as a short type        short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);    }}

输出。

The Value of sh_value = 763

程序2: 对于负数。

// Java program that demonstrates// Integer.shortValue() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          Integer sh_object = new Integer(-43);          // It will return the value of this Integer as a short type        short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);    }}

输出。

The Value of sh_value = -43

程序3: 对于一个十进制值和字符串。

注意: 当十进制值和字符串作为参数传递时,会返回错误信息。

// java program that demonstrates// Integer.shortValue() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {          // passing a decimal value        Integer sh_object = new Integer(27.51);          short sh_value = sh_object.shortValue();        System.out.println(" The Value of sh_value = " + sh_value);          // passing a string        Integer sh_object2 = new Integer("51");          short sh_value2 = sh_object2.shortValue();        System.out.println(" The Value of sh_value2 = " + sh_value2);    }}

输出

prog.java:10: error: no suitable constructor found for Integer(double)    Integer sh_object = new Integer(27.51);                        ^    constructor Integer.Integer(int) is not applicable      (argument mismatch; possible lossy conversion from double to int)    constructor Integer.Integer(String) is not applicable      (argument mismatch; double cannot be converted to String)1 error

相关推荐