Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String Expression into boolean expression

class A{

    public static void main(String a[]){
        String ad ="1<2";
        Boolean b = Boolean.parseBoolean(ad);
        if(b){
            System.out.println("true"); 
        }
        else
        {
            System.out.println("false");
        }
    }
}

I was hoping the output would be true but it actually prints false.

like image 741
Axay Gadhia Avatar asked May 16 '26 08:05

Axay Gadhia


1 Answers

You seem to confuse how Boolean.parseBoolean works. The javadoc clearly states that:

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

I.e. only expressions like Boolean.parseBoolean("True") or Boolean.parseBoolean("tRuE") return true, there is no argument evaluation done like for example in Javascript's eval() (although you can use the ScriptEngine in Java).

See this example:

public static void main (String[] args) throws java.lang.Exception
{
    String ad ="1<2";
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Object result = engine.eval(ad);
    System.out.println(Boolean.TRUE.equals(result)); // true
}
like image 165
Marvin Avatar answered May 18 '26 21:05

Marvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!