当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Short shortValue()用法及代码示例


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

用法:

public short shortValue()

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


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

以下示例程序旨在说明Short.shortValue()方法:

示例1:

// 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

示例2:

// 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


相关用法


注:本文由纯净天空筛选整理自ankita_chowrasia大神的英文原创作品 Short shortValue() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。