Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Wednesday, June 22, 2016

Java, check whether a string is not null and not empty?

Java, check whether a string is not null and not empty?


In my web app, I have a search field where I get some string and a combo box. So, I am sending two arguments to the remote function.

I want to check that the user input is not null and not empty. So, then I can construct a valid query.

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

What is the best way to do that?

Answer by helios for Java, check whether a string is not null and not empty?


str != null && str.length() != 0  

alternatively

str != null && !str.equals("")  

or

str != null && !"".equals(str)  

Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

Answer by codaddict for Java, check whether a string is not null and not empty?


How about:

if(str!= null && str.length() != 0 )  

Answer by Colin Hebert for Java, check whether a string is not null and not empty?


What about isEmpty() ?

if(str != null && !str.isEmpty())  

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

Answer by romaintaz for Java, check whether a string is not null and not empty?


Use org.apache.commons.lang.StringUtils

I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:

import org.apache.commons.lang.StringUtils;    if (StringUtils.isNotBlank(str)) {      ...  }     if (StringUtils.isBlank(str)) {      ...  }   

Answer by Sean Patrick Floyd for Java, check whether a string is not null and not empty?


Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

Answer by BjornS for Java, check whether a string is not null and not empty?


As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

public List findEmployees(String str, int dep) {   Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");   /** code here **/  }  

May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.

Answer by BjornS for Java, check whether a string is not null and not empty?


I got bored, have a free refactoring. Its a little cleaner but not pristine.

public class ALittleCleaner {    public List findEmployees(String str, int dep) throws ClassNotFoundException, SQLException {      log("List IN");      List list = Lists.newArrayList();        Connection con = getConnection();      Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);      String qry = buildQueryString(str, dep);      log(qry);      ResultSet rs = stmt.executeQuery(qry);      parseResults(list, rs);      log("List Out");      return list;  }    private void parseResults(List list, ResultSet rs) throws SQLException {      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);      }  }    private String buildQueryString(String str, int dep) {      String qry = "SELECT * FROM PERSON ";      StringBuilder sb = new StringBuilder();        if (StringUtils.isNotBlank(str)) {            sb.append("WHERE NAME LIKE '%").append(str).append("%'");          log(qry);      }      if (dep != 0) {            if (sb.toString().length() > 0) {              sb.append(" AND ");          } else {              sb.append("WHERE ");          }          sb.append("dept=").append(dep);      }        qry += sb.append(";").toString();      return qry;  }    private Connection getConnection() throws SQLException, ClassNotFoundException {      Class.forName("com.mysql.jdbc.Driver");        String url = "jdbc:mysql://localhost:3306/general";        java.sql.Connection con = DriverManager.getConnection(url, "root", "1234");        log("URL: " + url);      log("Connection: " + con);      return con;  }    private void log(String out) {      // Replace me with a real logger        System.out.println(out);    }    class Employee implements Serializable {      private static final long serialVersionUID = -8857510821322850260L;      String name;      int id, dept, age;        public String getName() {          return this.name;      }        public void setName(String name) {          this.name = name;      }        public int getId() {          return this.id;      }        public void setId(int id) {          this.id = id;      }        public int getDept() {          return this.dept;      }        public void setDept(int dept) {          this.dept = dept;      }        public int getAge() {          return this.age;      }        public void setAge(int age) {          this.age = age;      }  }    }  

Answer by A Null Pointer for Java, check whether a string is not null and not empty?


Use Apache StringUtils' isNotBlank method like

StringUtils.isNotBlank(str)  

It will return true only if the str is not null and is not empty.

Answer by Eddy for Java, check whether a string is not null and not empty?


Really funny to see so many answers on such a "simple" thing :D So, I want to add my approach here as well. I usually have my own Utils-Class containing some static methods, like the string-checking-one:

public static boolean isCool(String param) {      if (param == null) {          return false;      }      if (param.trim().equals("")) {          return false;      }      return true;  }  

Answer by Adam Gent for Java, check whether a string is not null and not empty?


To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

Strings.nullToEmpty(str).isEmpty();   // or  Strings.isNullOrEmpty(str);  

Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).

Guava's version of Commons Lang isBlank would be:

Strings.nullToEmpty(str).trim().isEmpty()  

I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').

Answer by phreakhead for Java, check whether a string is not null and not empty?


Just adding Android in here:

import android.text.TextUtils;    if (!TextUtils.isEmpty(str)) {  ...  }  

Answer by Tom for Java, check whether a string is not null and not empty?


If you don't want to include the whole library; just include the code you want from it. You'll have to maintain it yourself; but it's a pretty straight forward function. Here it is copied from commons.apache.org

    /**   * 

Checks if a String is whitespace, empty ("") or null.

* *
   * StringUtils.isBlank(null)      = true   * StringUtils.isBlank("")        = true   * StringUtils.isBlank(" ")       = true   * StringUtils.isBlank("bob")     = false   * StringUtils.isBlank("  bob  ") = false   * 
* * @param str the String to check, may be null * @return true if the String is null, empty or whitespace * @since 2.0 */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; }

Answer by Mindwin for Java, check whether a string is not null and not empty?


test equals with an empty string and null in the same conditional:

if(!"".equals(str) && str != null) {      // do stuff.  }  

Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.

the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.

Also check this answer: http://stackoverflow.com/a/531825/1532705

Answer by Javatar for Java, check whether a string is not null and not empty?


This works for me:

import com.google.common.base.Strings;    if (!Strings.isNullOrEmpty(myString)) {         return myString;  }  

Returns true if the given string is null or is the empty string.

Consider normalizing your string references with nullToEmpty. If you do, you can use String.isEmpty() instead of this method, and you won't need special null-safe forms of methods like String.toUpperCase either. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.

Answer by W.K.S for Java, check whether a string is not null and not empty?


I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty). This is the function:

public class StringUtils{        public static boolean areSet(String... strings)      {          for(String s : strings)              if(s == null || s.isEmpty)                  return false;            return true;      }       }  

so I can simply write:

if(!StringUtils.areSet(firstName,lastName,address)  {      //do something  }  

Answer by Vivek Vermani for Java, check whether a string is not null and not empty?


You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.

 String str1 = "";   String str2 = null;     if(StringUtils.isEmpty(str)){       System.out.println("str1 is null or empty");   }     if(StringUtils.isEmpty(str2)){       System.out.println("str2 is null or empty");   }  

will result in

str1 is null or empty

str2 is null or empty

Answer by Thomas Eizinger for Java, check whether a string is not null and not empty?


If you know the string you want to check against, you can use the following

if (!"mystring".equals(str)) {       /* your code here */   }  

Answer by msysmilu for Java, check whether a string is not null and not empty?


Just some small good practice if not just some syntax sugar (put the constant in front of the =='s and !='s).

if(null != str && !str.isEmpty())  

Answer by gprasant for Java, check whether a string is not null and not empty?


You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.

The isNotBlank() checks that the input parameter is:

  • not Null,
  • not the empty string ("")
  • not a sequence of whitespace characters (" ")

The isNotEmpty() checks only that the input parameter is

  • not null
  • not the Empty String ("")

Answer by BlondCode for Java, check whether a string is not null and not empty?


I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:

import com.google.common.base.Strings;  import org.apache.commons.lang.StringUtils;    /**   * Created by hu0983 on 2016.01.13..   */  public class StringNotEmptyTesting {    public static void main(String[] args){          String a = "  ";          String b = "";          String c=null;        System.out.println("Apache:");      if(!StringUtils.isNotBlank(a)){          System.out.println(" a is blank");      }      if(!StringUtils.isNotBlank(b)){          System.out.println(" b is blank");      }      if(!StringUtils.isNotBlank(c)){          System.out.println(" c is blank");      }      System.out.println("Google:");        if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){          System.out.println(" a is NullOrEmpty");      }      if(Strings.isNullOrEmpty(b)){          System.out.println(" b is NullOrEmpty");      }      if(Strings.isNullOrEmpty(c)){          System.out.println(" c is NullOrEmpty");      }    }  }  

Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.