📜  Java中的短 shortValue() 方法

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

Java中的短 shortValue() 方法

shortValue() 是Java中 Short 类的内置方法,用于返回值的 Short 值。

句法:

public short shortValue()

参数:该方法不带任何参数。

返回值:该方法返回该对象转换为short类型后所代表的数值。

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

方案一:

// Java program that demonstrates
// Short.shortValue() method
  
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        short svalue = 21;
        Short sh_obj = new Short(svalue);
  
        // It will return the short value of Short
        short sh_Value = sh_obj.shortValue();
  
        // Printing short value
        System.out.println("The short value of the given Short is = "
                                                          + sh_Value);
    }
}
输出:
The short value of the given Short is = 21

方案二:

// java program that demonstrates
// Short.shortValue() method
  
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        short svalue = -19;
        Short sh_obj = new Short(svalue);
  
        // It will return the short value of Short
        short sh_Value = sh_obj.shortValue();
  
        // Printing short value
        System.out.println("The short value of the given Short is = " 
                                                          + sh_Value);
    }
}
输出:
The short value of the given Short is = -19

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

// Java program that demonstrates
// Short.shortValue() method
  
import java.lang.*;
  
public class Geeks {
  
    public static void main(String[] args)
    {
  
        short svalue = 9.6;
        Short sh_obj = new Short(svalue);
  
        // It will return the short value of Short
        short sh_Value = sh_obj.shortValue();
  
        // Printing short value
        System.out.println("The short value of the given Short is = "
        + sh_Value);
        short svalue2 = "61";
        Short sh_obj2 = new Short(svalue2);
  
        // It will return the short value of Short
        short sh_Value2 = sh_obj2.shortValue();
  
        // Printing short value
        System.out.println("The short value of the given Short is = " +
        sh_Value2);
    }
}

输出:

prog.java:10: error: incompatible types: possible lossy conversion from double to short
    short svalue = 9.6;
                   ^
prog.java:18: error: incompatible types: String cannot be converted to short
    short svalue2 = "61";
                    ^
2 errors