Java Program to convert string type variables into boolean

Example 1: Convert string to boolean using parseBoolean()

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

    // create two string variables
    String str1 = "true";
    String str2 = "false";

    // convert string to boolean using parseBoolean()
    boolean b1 = Boolean.parseBoolean(str1);
    boolean b2 = Boolean.parseBoolean(str2);

    // print boolean values
    System.out.println(b1);    
    System.out.println(b2);   
  }
}
Output
true
false

Example 2: Convert string to boolean using valueOf()

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

    // create two string variables
    String str1 = "true";
    String str2 = "false";

    // convert string to boolean using valueOf()
    boolean b1 = Boolean.valueOf(str1);
    boolean b2 = Boolean.valueOf(str2);

    // print boolean values
    System.out.println(b1);    
    System.out.println(b2);    
  }
}
Output
true
false

Leave a Reply