Convert String Type Variables to Boolean in Java

Exercise:

Write a Java Program to convert string type variables into boolean.

Click Here to View the Solution!
public class StringToBool {
  public static void main(String[] args) {
    String str1 = "true";
    String str2 = "false";
    boolean b1 = Boolean.valueOf(str1);
    boolean b2 = Boolean.valueOf(str2);
    System.out.println(b1);    
    System.out.println(b2);    
  }
} 
Click Here to View the Output!
true
false
Click Here to View the Explanation!
  • This program deals with the conversion of a given string into a Boolean value.
  • Unlike the previous example, method valueOf() of Boolean class is employed.
  • Similar to the previous example, two String type variables str1 and str2 are declared, containing values ‘true’ and ‘false’ respectively. 
  • Then these two strings are passed to valueOf() method as arguments.
  • After that the converted results respectively, are assigned to two Boolean type variables b1 and b2.
  • In the last step, Boolean values are printed on the console.

%d bloggers like this: