Dynamic SQL query when number of fields in where clause in not known

suppose we have a front end where user can select different filters to narrow down the query results.In this case it is not already known which all fields user will select.
A dynamic query for this case can be constructed using this trick:

here fieldNames is the array containing names of all filters and fields is the array containing values provided by user.

String query="SELECT * from tableName";
String prefix=" WHERE "; //notice spaces before and after WHERE
for(int i=0;i<fields.length;i++){
    if(fields(i)!=null) {         
        query=query+prefix+fieldNames(i)+" = "+fields(i);
        prefix=" OR " //notice spaces before and after OR  
    }
}