Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in java (can be null)

Tags:

java

I have a function with a boolean parameter, but it could be null too.

If it's true or false, it makes a query with a "WHERE" clause. If it was null, the query has no "WHERE" clause, only the select clause.

How can I do that in Java ?

like image 970
Pythorogus Avatar asked Feb 06 '26 19:02

Pythorogus


1 Answers

Use Boolean class

public String foo(Boolean addWhere){
    String query = "SELECT * FROM tbl";
    if(addWhere != null){
        query += (addWhere? " WHERE true" : " WHERE false");
    }
    return query;
}

Call it as following,

String q = foo(false);
like image 98
Roshana Pitigala Avatar answered Feb 09 '26 10:02

Roshana Pitigala