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

Asked

Viewed 29,445 times

4

I went through this problem implementing a simple library of database queries in and would like to share the solution with the community, I believe it will be useful since I have penetrated until finding a simple solution.

In the implementation it was necessary to know whether the String of where era null or empty or if it was one String blank, and the verification of null and empty was simple the problem was the empty string.

And how to do that?

3 answers

3

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

An example of use 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 functionalities for primitives, and other concepts such as the use of:

Precontitions:

Boolean state treatment 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:

  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'))

Detre many other features in a lib of only 2.1KB. That even had contribution from @Josh Block.

More information:
Infoq Br - google-Guava

  • Very good your contribution, I saw in your reference that it was integrated with the Google Collection. +1 by aggregation.

3

Starting from Java 6, the most efficient and direct way to verify that a String is not empty is by using the method String.isEmpty(). Example with the verification of null:

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

Including the trim():

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 isEmpty just checks the size (length) of the class internal character vector:

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

Before Java 6 could be done so:

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

Including the trim():

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

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 of use:

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’s of great use to you, as it is to me.

Source: http://alvinalexander.com/blog/post/java/java-method-test-string-null-or-blank

  • 1

    I’m no expert on Android, but you can not use the Apache Commons-lang? I think it’s better than "reivent" the wheel. Here’s the API of Stringutils Commons-lang.

  • @Ricardogiaviti Maybe I didn’t know that API. I just "reinvented" the wheel because I didn’t know this one API. But anyway for those who don’t want to matter a whole API for your project, I shared a difficulty I had. But thanks for the tip, it seems like a good alternative ready to use. Very useful your caveat.

  • I agree with you @Fernando. It wouldn’t be worth importing all of Commons-lang for a single validation. The cool thing about the API is that it has a lot of solutions to these simple problems that we face on a day-to-day basis and we don’t have to keep cracking our heads. I believe the whole Apache Commons that’s how it is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.