How to convert Java String to boolean

In Java, a String can be converted into a boolean by Boolean.parseBoolean(string) and valueOf() method.

In order to obtain a boolean true, string must contain "true" irrespective of the case(uppercase TRUE or lowercase true). Any other string value except "true" will return boolean false.

1. Boolean.parseBoolean(string) method

The parseBoolean() method is a part of the Boolean class and is used to convert the string value into boolean.

Syntax:

Following is the syntax:

public static boolean parseBoolean(String s) 

Example 1:

Here, the String s1 and s2 and will be boolean true and all other strings will return boolean false.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s1 = "true";  
		String s2 = "TRUE";  
		String s3 = "studytonight";  

		boolean b1=Boolean.parseBoolean(s1);  
		boolean b2=Boolean.parseBoolean(s2);  
		boolean b3=Boolean.parseBoolean(s3);  

		System.out.println(b1);  
		System.out.println(b2);  
		System.out.println(b3);  
	}
}


true
true
false

Also, a String can be converted into a Boolean Object using the Boolean.valueOf() method.

2. Boolean.valueOf() method

The valueOf() method is a part of Boolean class and returns the Boolean object of the String value passed.

Example 2:

Here, a boolean value of the passed string is returned.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s1 = "true";    
		String s2 = "TRUE";    
		String s3 = "studytonight";    

		boolean b1 = Boolean.valueOf(s1);    
		boolean b2 = Boolean.valueOf(s2);    
		boolean b3 = Boolean.valueOf(s3);    

		System.out.println(b1);    
		System.out.println(b2);    
		System.out.println(b3); 
	}
}


true
true
false