How to check if String is null or blank in Java / Android

4

I went through this problem by implementing a simple database query library in and would like to share the solution with community, I think it's useful as I've thought through until I find a simple solution.

  

In the implementation it was necessary to know if the String of the where was null or empty or if it was a String blank, being that the check of null and empty was simple the problem was a String in white.

And how to do this?

    
asked by anonymous 27.03.2014 / 01:06

3 answers

2

This is my class utils:

public class StringUtils {

    // Verifica se a String é null ou vazia ou só tem espaços em branco
    public static boolean isNullOrBlank(String s) {
        return (s == null || s.trim().equals(""));
    }

    // Verifica se a String é null ou vazia
    // Pode ser utilizado como suporte em APIs menores que 9 do android onde não está disponivel o metódo de String isEmpty()
    public static boolean isNullOrEmpty(String s) {
        return (s == null || s.equals(""));
    }
}

Example usage:

String teste = null;
System.out.println(StringUtils.isNullOrEmpty(teste)); // true
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "";
System.out.println(StringUtils.isNullOrEmpty(teste)); // true
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "    ";
System.out.println(StringUtils.isNullOrEmpty(teste)); // false
System.out.println(StringUtils.isNullOrBlank(teste)); // true

teste = "  t  ";
System.out.println(StringUtils.isNullOrEmpty(teste)); // false
System.out.println(StringUtils.isNullOrBlank(teste)); // false

Hope it will be of great use to you as it is for me.

Source: link

    
27.03.2014 / 01:06
3

Another interesting API to use is the Google Guava . It has a number of features for this type of task.

An example usage would be:

 import com.google.common.base.Strings;

 Strings.isNullOrEmpty(""); // retorna true para vazia
 Strings.isNullOrEmpty("   ".trim()); // retorna true para string em branco

There are several other features for primitives, and other concepts such as the use of:

Precontitions:

Treatment of Boolean state of some condition without guava:

 if (estado!= Estado.INCOMPLETO) {
      throw new IllegalStateException(
              "Esse Objeto está em um estado " + estado);
 }

It would be simpler with Guava without using ifs:

import com.google.common.base.Preconditions;     

  Preconditions.checkState(
    estado == Estado.PLAYABLE, "Esse Objeto está em um estado  %s", estado
  );

CharMatcher:

Determines whether a character is a const such as:

  CharMatcher.WHITESPACE.matches(' ');
  CharMatcher.JAVA_DIGIT.matches('1');

Or using a specific factory method like:

  CharMatcher.is('x')
  CharMatcher.isNot('_')
  CharMatcher.oneOf("aeiou").negate()
  CharMatcher.inRange('a', 'z').or(inRange('A', 'Z'))

Stop many other features on a lib of only 2.1KB. That even had contribution of @Josh Block.

More information:
InfoQ Br - google-guava

    
27.03.2014 / 18:47
2

From Java 6, the most efficient and direct way to check if a String is not empty is to use the String.isEmpty() method. Example with% check%:

if (str == null || str.isEmpty()) {
    //é nula ou vazia
}

Including null :

if (str == null || str.trim().isEmpty()) {
    //é nula, vazia ou só contém caracteres de espaço, tabulação e quebras de linha
}

The implementation of trim() only checks the size ( isEmpty ) of the internal character vector of the class:

private final char value[];
public boolean isEmpty() {
    return value.length == 0;
}

Before Java 6 could be done like this:

if (str == null || str.length() == 0) {
    //é nula ou vazia
}

Including length :

if (str == null || str.trim().length() == 0) {
    //é nula, vazia ou só contém caracteres de espaço, tabulação e quebras de linha
}
    
11.04.2014 / 16:24