1. Introduction
Converting a String to a boolean is a common task in Java. The Boolean class in Java has a method parseBoolean(String s), which returns the boolean represented by the specified String. It is not case-sensitive, so it does not matter if the string contains “true” or “TRUE” – the result will be the same.
2. Program Steps
1. Define a main method inside a Java class.
2. Create a few String variables containing different boolean values.
3. Use the Boolean.parseBoolean method to convert these String values to boolean.
4. Print the original String values and the corresponding boolean values.
3. Code Program
public class StringToBoolean {
public static void main(String[] args) {
// Step 2: Create a few String variables containing different boolean values
String str1 = "true";
String str2 = "TRUE";
String str3 = "false";
String str4 = "FALSE";
// Step 3: Use the Boolean.parseBoolean method to convert these String values to boolean
boolean bool1 = Boolean.parseBoolean(str1);
boolean bool2 = Boolean.parseBoolean(str2);
boolean bool3 = Boolean.parseBoolean(str3);
boolean bool4 = Boolean.parseBoolean(str4);
// Step 4: Print the original String values and the corresponding boolean values
System.out.println(str1 + " converts to " + bool1);
System.out.println(str2 + " converts to " + bool2);
System.out.println(str3 + " converts to " + bool3);
System.out.println(str4 + " converts to " + bool4);
}
}
Output:
true converts to true TRUE converts to true false converts to false FALSE converts to false
4. Step By Step Explanation
– Step 1: A main method is defined inside the StringToBoolean class.
– Step 2: Four String variables str1, str2, str3, and str4 are created, each containing different representations of boolean values.
– Step 3: The Boolean.parseBoolean method is used to convert the string values to their corresponding boolean values.
– Step 4: The original String values and the resulting boolean values are printed to the console.
By using the Boolean.parseBoolean method, we can effectively convert a String containing "true" or "false" (regardless of case) to a boolean in Java.