Turns a string into a boolean value and returns a default value if unsuccessful. - Java java.lang

Java examples for java.lang:boolean

Description

Turns a string into a boolean value and returns a default value if unsuccessful.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        boolean d = true;
        System.out.println(parseBoolean(s, d));
    }/*from  w  w  w . jav  a  2s . c  o  m*/

    /** Turns a string into a boolean value and returns a default value if unsuccessful.
     * @param s the string to convert
     * @param d the default value
     * @return equivalent boolean value
     */
    public static boolean parseBoolean(String s, boolean d) {

        if (s == null)
            return d;

        s = s.trim();
        if (s.length() == 0)
            return d;

        char c = s.charAt(0);

        if (c == 't' || c == 'T' || c == 'y' || c == 'Y')
            return true;

        if (c == 'f' || c == 'F' || c == 'n' || c == 'N')
            return false;

        return d;
    }
}

Related Tutorials