Java - Boolean valueOf(String value) 方法



描述

Java Boolean valueOf(String value) 方法返回一個 Boolean 物件,其值由指定的字串表示。如果字串引數不為空,並且忽略大小寫後等於字串“true”,則返回的 Boolean 物件表示真值。

宣告

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

public static Boolean valueOf(String s)

引數

s − 一個字串

返回值

此方法返回由字串表示的 Boolean 值。

異常

從字串“true”獲取 Boolean 示例

以下示例演示了對字串值“true”使用 Boolean valueOf() 方法。在這個程式中,我們建立了一個 Boolean 變數,並使用 valueOf() 方法從字串“true”中檢索了一個值為 true 的 Boolean 物件。然後列印結果。

package com.tutorialspoint;

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

      // create 1 Boolean object b1
      Boolean b1;

      // create 1 string variable and assign value
      String s1 = "true";

      /**
       *  static method is called using class name 
       *  assign result of valueOf method on s1 to b1
       */
      b1 = Boolean.valueOf(s1);
      String str1 = "Boolean instance of string " + s1 + " is "  + b1;

      // print b1 values
      System.out.println( str1 );
   }
}

輸出

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

Boolean instance of string true is true

從字串“yes”獲取 Boolean 示例

以下示例演示了對字串值“yes”使用 Boolean valueOf() 方法。在這個程式中,我們建立了一個 Boolean 變數,並使用 valueOf() 方法從字串“yes”中檢索了一個值為 false 的 Boolean 物件。然後列印結果。

package com.tutorialspoint;

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

      // create 1 Boolean object b1
      Boolean b1;

      // create 1 string variable and assign value
      String s1 = "yes";

      /**
       *  static method is called using class name 
       *  assign result of valueOf method on s1 to b1
       */
      b1 = Boolean.valueOf(s1);

      String str1 = "Boolean instance of string " + s1 + " is "  + b1;

      // print b1 values
      System.out.println( str1 );
   }
}

輸出

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

Boolean instance of string yes is false

從空字串獲取 Boolean 示例

以下示例演示了對空字串使用 Boolean valueOf() 方法。在這個程式中,我們建立了一個 Boolean 變數,並使用 valueOf() 方法從空字串中檢索了一個值為 false 的 Boolean 物件。然後列印結果。

package com.tutorialspoint;

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

      // create 1 Boolean object b1
      Boolean b1;

      // create 1 string variable and assign value
      String s1 = null;

      /**
       *  static method is called using class name 
       *  assign result of valueOf method on s1 to b1
       */
      b1 = Boolean.valueOf(s1);

      String str1 = "Boolean instance of string " + s1 + " is "  + b1;

      // print b1 values
      System.out.println( str1 );
   }
}

輸出

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

Boolean instance of string null is false
java_lang_boolean.htm
廣告