📜  Java中的整数shortValue()方法

📅  最后修改于: 2022-05-13 01:55:45.866000             🧑  作者: Mango

Java中的整数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() method
import 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() method
import 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