Java - Boolean valueOf(String value) method



Description

The Java Boolean valueOf(String value) returns a Boolean with a value represented by the specified string. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string "true".

Declaration

Following is the declaration for java.lang.Boolean.valueOf() method

public static Boolean valueOf(String s)

Parameters

s − a string

Return Value

This method returns the Boolean value represented by the string.

Exception

NA

Example 1

The following example shows the usage of Boolean valueOf() method for a String value as true.

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 );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Boolean instance of string true is true

Example 2

The following example shows the usage of Boolean valueOf() method for a String value as not true.

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 );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Boolean instance of string yes is false

Example 3

The following example shows the usage of Boolean valueOf() method for a String value as null.

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 );
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Boolean instance of string null is false
java_lang_boolean.htm
Advertisements