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.

Marvin
  • 13,325
  • 3
  • 51
  • 57
Axay Gadhia
  • 73
  • 2
  • 4
  • 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. – asu Nov 22 '16 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. – Joao Polo Nov 22 '16 at 18:17

2 Answers2

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
}
Community
  • 1
  • 1
Marvin
  • 13,325
  • 3
  • 51
  • 57
-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");
    }
}}
Py-Coder
  • 2,024
  • 1
  • 22
  • 28