Java - Short shortValue() 方法



**Java Short shortValue() 方法** 用於獲取給定 Short 的等效 short 值,經過縮窄原始型別轉換,這意味著將更高資料型別轉換為較低資料型別。short 資料型別可以儲存 -32,768 到 32,767 範圍內的整數。

通常,它是一個*拆箱方法*。雖然 Java 5 引入了自動裝箱,這意味著轉換現在自動完成,但瞭解裝箱和拆箱的概念非常重要。

  • **拆箱** 是將 Short 轉換為 short 的過程。

  • **裝箱** 是將 short 轉換為 Short 的過程。

例如,假設我們有一個 short 值 '876'。給定 short 值的等效 Short 為 '876'。

Short s = 876
shortValue s1 = 876 // corresponding short value

語法

以下是 **Java Short shortValue()** 方法的語法:

public short shortValue()

引數

此方法不接受任何引數。

返回值

此方法返回此物件表示的 short 值,轉換為 short 型別。

從包含正 short 值的 Short 物件獲取 short 值示例

以下是一個示例,演示了 Java Short shortValue() 方法的使用。在這裡,我們建立一個 Short 物件 'obj' 併為其分配一個正值。然後,透過在此 Short 物件上呼叫該方法來顯示 short 值:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      /*
      * returns the short value represented by this object
      * converted to type short
      */
      Short obj = new Short("35");
      short s = obj.shortValue();
      System.out.println("Value = " + s);
      obj = new Short("2");
      s = obj.shortValue();
      System.out.println("Value = " + s);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Value = 35
Value = 2

從包含負 short 值的 Short 物件獲取 short 值示例

在下面給出的程式碼中,使用 try-catch 語句返回給定 Short 的 short 值:

package com.tutorialspoint;

import java.util.Scanner;

public class ShortDemo {
   public static void main(String[] args) {
      try {
         short value = -739;
         Short s = value;
         short x = s.shortValue();
         System.out.println("The corresponding short Value is = " + x);
      } catch (Exception e) {
         System.out.println("Error: not a valid short value");
      }
   }
}

輸出

以下是上述程式碼的輸出:

The corresponding short Value is = -739

從包含正 short 值的 Short 物件獲取 short 值時遇到異常示例

當在具有十進位制值和字串的 Short 物件上呼叫 shortValue() 方法時,該方法會返回錯誤,如下例所示:

package com.tutorialspoint;

public class ShortDemo {
   public static void main(String[] args) {
      short s = 8.3;
      Short x = new Short(s);
      
      // returning the short value of Short
      short value = x.shortValue();
      
      // Printing the short value
      System.out.println("The short value is: " + value);
      short s1 = "87";
      Short y = new Short(s1);
      
      // returning the short value of Short
      short value1 = y.shortValue();
      // Print the short value
      System.out.println("The short value is: " + value1);
   }
}

異常

上述程式碼的輸出如下:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
      Type mismatch: cannot convert from double to short
      Type mismatch: cannot convert from String to short

      at com.tutorialspoint.ShortDemo.main(ShortDemo.java:7)
java_lang_short.htm
廣告

© . All rights reserved.