當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。