Java - Byte valueOf() 方法



描述

Java Byte valueOf(String s, int radix) 方法返回一個 Byte 物件,該物件儲存從指定字串中提取的值,該值使用第二個引數給出的基數進行解析。

第一個引數被解釋為代表一個用第二個引數指定的基數表示的有符號位元組,就像該引數被提供給 parseByte(java.lang.String, int) 方法一樣。結果是一個 Byte 物件,它表示字串指定的位元組值。

宣告

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

public static Byte valueOf(String s, int radix)throws NumberFormatException

引數

  • s − 要解析的字串

  • radix − 用於解釋 s 的基數

返回值

此方法返回一個 Byte 物件,該物件儲存由字串引數在指定基數中表示的值。

異常

NumberFormatException − 如果字串不包含可解析的位元組。

使用基數 2 解析包含減號的字串以獲取位元組示例

以下示例顯示了 Byte valueOf(String,int) 方法的用法。我們建立了一個字串變數併為其賦值。然後建立一個 Byte 變數,並使用 Byte.valueOf(String,, int) 方法,使用基數 2 解析字串的值並列印。

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

      // create a String s and assign value to it
      String s = "-1010";

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of s to b using radix as 2
       *  radix 2 represents binary
       */
      b = Byte.valueOf(s, 2);

      String str = "Byte value of string " + s + " using radix 2 is " + b;

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

輸出

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

Byte value of string -1010 using radix 2 is -10

使用基數 8 解析包含減號的字串以獲取位元組示例

以下示例顯示了 Byte valueOf(String,int) 方法的用法。我們建立了一個字串變數併為其賦值。然後建立一個 Byte 變數,並使用 Byte.valueOf(String,, int) 方法,使用基數 8 解析字串的值並列印。

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

      // create a String s and assign value to it
      String s = "-101";

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of s to b using radix as 8
       *  radix 8 represents octal
       */
      b = Byte.valueOf(s, 8);

      String str = "Byte value of string " + s + " using radix 8 is " + b;

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

輸出

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

Byte value of string -101 using radix 8 is -65

使用基數 10 解析包含減號的字串以獲取位元組示例

以下示例顯示了 Byte valueOf(String,int) 方法的用法。我們建立了一個字串變數併為其賦值。然後建立一個 Byte 變數,並使用 Byte.valueOf(String,, int) 方法,使用基數 10 解析字串的值並列印。

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

      // create a String s and assign value to it
      String s = "-101";

      // create a Byte object b
      Byte b;

      /**
       *  static method is called using class name.
       *  assign Byte instance value of s to b using radix as 10
       *  radix 8 represents decimal
       */
      b = Byte.valueOf(s, 10);

      String str = "Byte value of string " + s + " using radix 10 is " + b;

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

輸出

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

Byte value of string -101 using radix 10 is -101
java_lang_boolean.htm
廣告