String to Boolean Custom
This example shows parsing a string literal to a boolean primitive using custom parse function.
package com.bethecoder.tutorials.core.bool;
public class CustomParseBoolean {
/**
* 'parseBoolean' method treats any string
* other than TRUE/YES/ON(ignore case)/positive number
* as FALSE
*/
public static boolean parseBoolean ( String value ) {
if ( value != null &&
( value.equalsIgnoreCase ( "true" ) ||
value.equalsIgnoreCase ( "yes" ) ||
value.equalsIgnoreCase ( "on" ) ||
isPositive ( value ))) {
return true ;
}
return false ;
}
private static boolean isPositive ( String value ) {
int intValue = 0 ;
try {
intValue = Integer.parseInt ( value ) ;
} catch ( NumberFormatException e ) {
//Ignore for now
}
return intValue > 0 ;
}
public static void main ( String [] args ) {
boolean bool = parseBoolean ( null ) ;
System.out.println ( bool ) ; //false
bool = parseBoolean ( "true" ) ;
System.out.println ( bool ) ; //true
bool = parseBoolean ( "On" ) ;
System.out.println ( bool ) ; //true
bool = parseBoolean ( "oFF" ) ;
System.out.println ( bool ) ; //false
bool = parseBoolean ( "1" ) ;
System.out.println ( bool ) ; //true
bool = parseBoolean ( "-1" ) ;
System.out.println ( bool ) ; //false
bool = parseBoolean ( "yES" ) ;
System.out.println ( bool ) ; //true
bool = parseBoolean ( "no" ) ;
System.out.println ( bool ) ; //false
}
}
It gives the following output,
false
true
true
false
true
false
true
false