Search code examples
javaboolean-expression

Converting a string into a boolean condition


Say I have a String

String strCondition = something.contains("value") && somethingElse.equals("one");

How do I convert this String into a boolean condition so that I can be able to use it in an IF statement?

If I use valueOf(), will it evaluate the contents of the String?

RE-EDIT: I am not sure how to put this.

I am taking the value something.contains("value") && somethingElse.equals("one") from a database column. If I try to assign that to boolean variable it shows a type mismatch.


Solution

  • you don't.

    it already is a boolean expression.

    something.contains("value") -> this returns either true or false && somethingElse.equals("one"); -> this also returns true or false.

    what you need, is either:

    boolean strCondition = something.contains("value") && somethingElse.equals("one");
    if ( strCondition )
    

    or

    if ( something.contains("value") && somethingElse.equals("one"))
    

    EDIT:

    The above would either return true, false, or throw a nasty NullPointerException.

    To avoid the latter, you should use:

    if ( "one".equals(somethingElse) && (something != null && something.contains("value"))