자바에서 String이 null이 아닌지 안 비었는지 어떻게 확인하죠?

조회수 22817회

발생하는 문제 및 실행환경

제 웹앱에 문자열 몇개를 받는 검색 필드랑 콤보박스가 있는데요. 그래서 인자 두개를 리모트 함수로 보내요. 제가 원하는건 입력값이 null이거나 비었는지를 확인해서 쿼리를 구성하는거에요..

소스코드

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;
}

이건 제 소스인데, 어떻게 하면 될까요?

1 답변

  • 좋아요

    2

    싫어요
    채택 취소하기

    isEmpty()를 써보세요. if(str != null && !str.isEmpty()) 이런 식으로 쓰시면 됩니다. &&은 둘다 참일때 참을 리턴하는데요. 자바에서 A && b가 있을때 앞의 A가 거짓이면 B의 조건은 검사하지않고 바로 거짓을 리턴합니다. 그리고 str이 null은 아니지만 비었을경우 isEmpty()로 비었는지를 검사해줍니다.

    또 Java SE 1.6부터 str.length() == 0도 사용 가능한데요. 문자열의 길이가 0인지를 확인해 String이 비었나를 확인할수있습니다.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)