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


Java Integer shortValue()用法及代碼示例


Integer.shortValue()是java.lang的內置方法,該方法以short類型返回此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


相關用法


注:本文由純淨天空篩選整理自ankita_chowrasia大神的英文原創作品 Integer shortValue() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。