Java - Boolean parseBoolean(String s) 方法



描述

Java Boolean parseBoolean(String) 方法將字串引數解析為布林值。如果字串引數不為空,並且忽略大小寫後等於字串“true”,則返回的布林值表示 true。

宣告

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

public static boolean parseBoolean(String s)

引數

s − 包含要解析的布林值表示形式的字串

返回值

此方法返回由字串引數表示的布林值。

異常

將字串值解析為 true 布林值示例

以下示例演示瞭如何使用 Boolean parseBoolean() 方法將字串值解析為 true。在這個程式中,我們有一個字串“TRue”,使用 parseBoolean() 方法,我們將“TRue”解析為 true 的原始布林值,然後列印結果。

package com.tutorialspoint;

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

      // create and assign values to String s1
      String s1 = "TRue";

      // create 1 boolean primitive bool1
      boolean bool1;

      /**
       *  static method is called using class name
       *  apply result of parseBoolean on s1 to bool1
       */
      bool1 = Boolean.parseBoolean(s1);      
      String str1 = "Parse boolean on " + s1 + " gives "  + bool1;

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

輸出

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

Parse boolean on TRue gives true

將字串值解析為 false 布林值示例

以下示例演示瞭如何使用 Boolean parseBoolean() 方法將字串值解析為 "Yes"。在這個程式中,我們有一個字串“Yes”,使用 parseBoolean() 方法,我們將“Yes”解析為 false 的原始布林值,然後列印結果。

package com.tutorialspoint;

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

      // create and assign values to String s1
      String s1 = "Yes";

      // create 1 boolean primitive bool1
      boolean bool1;

      /**
       *  static method is called using class name
       *  apply result of parseBoolean on s1 to bool1
       */
      bool1 = Boolean.parseBoolean(s1);
      
      String str1 = "Parse boolean on " + s1 + " gives "  + bool1;

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

輸出

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

Parse boolean on Yes gives false

將空字串值解析為 false 布林值示例

以下示例演示瞭如何使用 Boolean parseBoolean() 方法解析空字串。在這個程式中,我們有一個空字串,使用 parseBoolean() 方法,我們將空字串解析為 false 的原始布林值,然後列印結果。

package com.tutorialspoint;

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

      // create a String variable s1
      String s1 = null;

      // create 1 boolean primitive bool1
      boolean bool1;

      /**
       *  static method is called using class name
       *  apply result of parseBoolean on s1 to bool1
       */
      bool1 = Boolean.parseBoolean(s1);
      
      String str1 = "Parse boolean on " + s1 + " gives "  + bool1;

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

輸出

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

Parse boolean on null gives false
java_lang_boolean.htm
廣告