Java - Byte valueOf() 方法



描述

Java Byte valueOf(byte b) 方法返回一個表示指定位元組值的 Byte 例項。

如果不需要新的 Byte 例項,則通常應優先使用此方法而不是建構函式 Byte(byte),因為此方法可能會產生明顯更好的空間和時間效能,因為所有位元組值都被快取。

宣告

以下是 java.lang.Byte.valueOf() 方法的宣告

public static Byte valueOf(byte b)

引數

b − 位元組值

返回值

此方法返回一個表示 b 的 Byte 例項。

異常

獲取原始正位元組值的 Byte 物件示例

以下示例演示了 Byte valueOf(byte) 方法的用法。我們建立了一個位元組變數併為其賦值。然後建立一個字串變數,並使用 Byte.valueOf(byte) 方法列印位元組值的數值。

package com.tutorialspoint;
public class ByteDemo {
   public static void main(String[] args) {

      // create a byte primitive bt and asign value
      byte bt = 20;

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of bt to b
       */
      b = Byte.valueOf(bt);

      String str = "Byte value of byte primitive " + bt + " is " + b;

      // print b value
      System.out.println( str );
   }
}

輸出

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

Byte value of byte primitive 20 is 20

獲取原始負位元組值的 Byte 物件示例

以下示例演示了 Byte valueOf(byte) 方法的用法。我們建立了一個位元組變數併為其賦予負值。然後建立一個字串變數,並使用 Byte.valueOf(byte) 方法列印位元組值的數值。

package com.tutorialspoint;
public class ByteDemo {
   public static void main(String[] args) {

      // create a byte primitive bt and asign value
      byte bt = -20;

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of bt to b
       */
      b = Byte.valueOf(bt);

      String str = "Byte value of byte primitive " + bt + " is " + b;

      // print b value
      System.out.println( str );
   }
}

輸出

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

Byte value of byte primitive -20 is -20

獲取原始零位元組值的 Byte 物件示例

以下示例演示了 Byte valueOf(byte) 方法的用法。我們建立了一個位元組變數併為其賦值零。然後建立一個字串變數,並使用 Byte.valueOf(byte) 方法列印位元組值的數值。

package com.tutorialspoint;
public class ByteDemo {
   public static void main(String[] args) {

      // create a byte primitive bt and asign value
      byte bt = 0;

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of bt to b
       */
      b = Byte.valueOf(bt);

      String str = "Byte value of byte primitive " + bt + " is " + b;

      // print b value
      System.out.println( str );
   }
}

輸出

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

Byte value of byte primitive 0 is 0
java_lang_boolean.htm
廣告