Java - Byte toString() 方法



描述

Java Byte toString() 方法返回一個表示此 Byte 值的 String 物件。該值被轉換為帶符號的十進位制表示形式,並作為字串返回,就像將位元組值作為引數傳遞給 toString(byte) 方法一樣。

宣告

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

public String toString()

覆蓋

Object 類中的 toString

引數

返回值

此方法返回此物件的十進位制值表示的字串。

異常

使用 new 運算子建立的 Byte 物件的字串表示示例

以下示例演示了使用 new 運算子建立的 Byte 物件的 Byte toString() 方法的使用。我們建立了兩個 Byte 變數,併為它們分配了使用 new 運算子建立的 Byte 物件。然後,我們使用 toString() 方法獲取位元組變數的字串表示,然後列印結果。

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

      // create 2 Byte objects b1, b2
      Byte b1, b2;

      // assign values to b1, b2
      b1 = new Byte("100");
      b2 = new Byte("-100");

      String str1 = "String representation of Byte " + b1 + " is " + b1.toString();
      String str2 = "String representation of Byte " + b2 + " is " + b2.toString();

      // print i1, i2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

輸出

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

String representation of Byte 100 is 100
String representation of Byte -100 is -100

使用 valueOf(String) 方法建立的 Byte 物件的字串表示示例

以下示例演示了使用 valueOf(String) 方法建立的 Byte 物件的 Byte toString() 方法的使用。我們建立了兩個 Byte 變數,併為它們分配了使用 valueOf(String) 方法建立的 Byte 物件。然後,我們使用 toString() 方法獲取位元組變數的字串表示,然後列印結果。

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

      // create 2 Byte objects b1, b2
      Byte b1, b2;

      // assign values to b1, b2
      b1 = Byte.valueOf("100");
      b2 = Byte.valueOf("-100");

      String str1 = "String representation of Byte " + b1 + " is " + b1.toString();
      String str2 = "String representation of Byte " + b2 + " is " + b2.toString();

      // print i1, i2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

輸出

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

String representation of Byte 100 is 100
String representation of Byte -100 is -100

使用 valueOf(byte) 方法建立的 Byte 物件的字串表示示例

以下示例演示了使用 valueOf(byte) 方法建立的 Byte 物件的 Byte toString() 方法的使用。我們建立了兩個 Byte 變數,併為它們分配了使用 valueOf(byte) 方法建立的 Byte 物件。然後,我們使用 toString() 方法獲取位元組變數的字串表示,然後列印結果。

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

      // create 2 Byte objects b1, b2
      Byte b1, b2;

      // assign values to b1, b2
      b1 = Byte.valueOf((byte)100);
      b2 = Byte.valueOf((byte)-100);

      String str1 = "String representation of Byte " + b1 + " is " + b1.toString();
      String str2 = "String representation of Byte " + b2 + " is " + b2.toString();

      // print i1, i2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

輸出

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

String representation of Byte 100 is 100
String representation of Byte -100 is -100
java_lang_byte.htm
廣告