How to check if String value is Boolean type in Java?

How to check if String value is Boolean type in Java?

In Java, you can check if a String value represents a Boolean type by comparing it to the known Boolean values "true" and "false" in a case-insensitive manner. Here's a simple way to do it:

public class Main { public static void main(String[] args) { String str = "True"; // or "False" or "true" or "false" // Convert the string to lowercase and compare it to "true" and "false" if (str.toLowerCase().equals("true") || str.toLowerCase().equals("false")) { System.out.println("The string is a Boolean value."); } else { System.out.println("The string is not a Boolean value."); } } } 

In this code:

  1. We convert the input string to lowercase using toLowerCase() to make the comparison case-insensitive.

  2. We then compare the lowercase string with "true" and "false" using the equals() method.

  3. If the string matches either "true" or "false," we consider it a Boolean value.

Keep in mind that this approach assumes that the input string is well-formed and contains only "true" or "false" (case-insensitive). If the input can contain other variations or typos, you might need a more robust validation method, such as regular expressions or a custom parser.


More Tags

mvn-repo singlechildscrollview shopify entity sql-date-functions truncate session-state expression oracle-apex-5.1 firefox-addon-webextensions

More Java Questions

More Internet Calculators

More Math Calculators

More Livestock Calculators

More Biochemistry Calculators