String to boolean Conversion in Java

April 26, 2011 | java.lang
String to boolean Conversion: Sometimes, we obtain the values in string format in Java. Printing the value is no problem (as long as user gets the same output) as it prints the same value as data type prints.

For example, a boolean value is obtained in string format as in command-line arguments or from TextField's getText() method. The string value is to be converted into boolean data type format to use in coding. To convert, casting does not work as string and boolean are incompatable for conversion either implicitly or explicitly. It requires extra effort in coding known as "parsing operation". Parsing operation involves the usage of a wrapper class and parseXXX() method. For string to boolean conversion, it is required Boolean class and parseBoolean() method and explained in the following program.

Parsing Example on String to boolean conversion
public class Conversions
{
  public static void main(String args[])
  {
    String str = "true";
    System.out.println("true in String form: " = + str);     // printing is no problem

    boolean b1 = Boolean.parseBoolean(str);                  // String to boolean conversion
          
    if(b1)
    {
      System.out.println("Yes converted");                   // using in coding
    }
  }
}

String to boolean Output screenshot on String to boolean Example

parseBoolean() is a method of wrapper class Boolean which converts string str to boolean b1. Now b1 can be used in coding as in control structures.

Using the same technique, it is possible to convert string to other data types byte, short, int, long, float, double and character also.

Note: The other way boolean to string is also possible.

View all for 65 types of Conversions