How do I check if the String is null or not empty in Java?

Asked 2 years ago, Updated 2 years ago, 106 views

My web app has a search field and a combo box that receives some strings. So we send two factors as a remote function. All I want is to configure the query by checking whether the input value is null or empty.

public ArrayList findEmployees(String str, int dep)
       throws ClassNotFoundException, SQLException{

    System.out.println("List IN");
    ArrayList list = new ArrayList();
    java.sql.Statement stmt;
    java.sql.ResultSet rs;
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/general";
    java.sql.Connection con = DriverManager.getConnection(url, "root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    stmt = con.createStatement();
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    String qry = "SELECT * FROM PERSON ";
    String werstr = "WHERE";
    if(str!= null && str != "**here i want to check the 'str' is empty or not." )
    {
        qry += werstr + " NAME LIKE '%"+str+"%'";
        System.out.println(qry);
        werstr = "AND";
    }
    if(dep != 0)
    {
        qry += werstr + "dept="+dep;
    }
    qry += ";";
    System.out.println(qry);
    rs = stmt.executeQuery(qry);
    while (rs.next()) {
        Employee employee = new Employee();
        String name = rs.getString(2);
        employee.setName(name);
        int id = rs.getInt(1);
        employee.setId(id);
        int dept = rs.getInt(4);
        employee.setDept(dept);
        int age = rs.getInt(3);
        employee.setAge(age);
        list.add(employee);
    }
    System.out.println("List Out");
    return list;
}

This is my sauce, what should I do?

mysql string java string-comparison

2022-09-22 08:17

1 Answers

Try isEmpty(). if(str != null && !str.isEmpty()) You can write it like this. && return true when both are true. If A&&b exists in Java and the preceding A is false, the condition of B is not checked and immediately returns false. Also, if str is not null but empty, check if isEmpty() is empty.

From Java SE 1.6, str.length() == 0 is also available. You can check the length of the string to see if it is empty.


2022-09-22 08:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.