Java - Boolean toString() 方法



描述

Java Boolean toString() 方法返回一個表示此布林值的 String 物件。如果此物件表示值為 true,則返回等於“true”的字串。否則,返回等於“false”的字串。

宣告

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

public String toString()

重寫

Object 類中的 toString

引數

返回值

此方法返回此物件的字串表示形式。

異常

從布林值獲取字串表示形式為 true 的示例

以下示例演示了 Boolean toString() 方法對布林物件值 true 的用法。在這個程式中,我們有一個布林變數,其底層值為 true,並使用 toString() 方法獲取一個字串“true”,然後列印結果。

package com.tutorialspoint;

public class BooleanDemo {
   public static void main(String[] args) {

      // create 1 Boolean objects b1
      Boolean b1;

      // assign value to b1
      b1 = Boolean.valueOf(true);

      // create 1 String s1
      String s1;

      // assign string value of object b1 to s1
      s1 = b1.toString();

      String str1 = "String value of boolean object " + b1 + " is "  + s1;

      // print s1 value
      System.out.println( str1 );
   }
}

輸出

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

String value of boolean object true is true

從布林值獲取字串表示形式為 false 的示例

以下示例演示了 Boolean toString() 方法對布林物件值 false 的用法。在這個程式中,我們有一個布林變數,其底層值為 false,並使用 toString() 方法獲取一個字串“false”,然後列印結果。

package com.tutorialspoint;

public class BooleanDemo {
   public static void main(String[] args) {

      // create 1 Boolean objects b1
      Boolean b1;

      // assign value to b1
      b1 = Boolean.valueOf(false);

      // create 1 String s1
      String s1;

      // assign string value of object b1 to s1
      s1 = b1.toString();

      String str1 = "String value of boolean object " + b1 + " is "  + s1;

      // print s1 value
      System.out.println( str1 );
   }
}

輸出

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

String value of boolean object false is false

從 null 布林值獲取字串表示形式的示例

以下示例演示了 Boolean toString() 方法對 null 布林物件值的用法。在這個程式中,我們有一個布林變數,其底層值為 null,並使用 toString() 方法獲取一個字串“false”,然後列印結果。

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

      // create 1 Boolean objects b1
      Boolean b1;

      // assign value to b1
      b1 = Boolean.valueOf(null);

      // create 1 String s1
      String s1;

      // assign string value of object b1 to s1
      s1 = b1.toString();

      String str1 = "String value of boolean object " + b1 + " is "  + s1;

      // print s1 value
      System.out.println( str1 );
   }
}

輸出

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

String value of boolean object false is false
java_lang_boolean.htm
廣告