3
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.

2
  • You are trying to evaluate "1<2" as a boolean - i.e. maybe "true" and "false" or "1" and "0" (I'm unsure what java's implementation does). parseBoolean won't try to parse and execute an expression. Commented Nov 22, 2016 at 17:47
  • You need to use some java expression language interpreter to do this. That function only converts a text to true/false, like Integer.parseInt will do with a number. Commented Nov 22, 2016 at 18:17

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you gave exact solution which i want.
-1

Here we go:

class A{

public static void main(String a[]){
    String ad ="1<2";
    String tmpDataArray[] = ad.split("<");
   int num1 = Integer.parseInt(String.valueOf(tmpDataArray[0]));
   int num2 = Integer.parseInt(String.valueOf(tmpDataArray[1]));

   // Boolean b = Boolean.parseBoolean(ad);
    if(num1<num2){
        System.out.println("true"); 
    }
    else
    {
        System.out.println("false");
    }
}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.