Java 8 – How to check whether a String is empty or not ?

In this article, we will understand with a Java program on how to check whether a String is empty or not in Java 1.8 version

Already in one of the previous article, we discussed how to check whether a String is empty or not using earlier versions of Java like 5 or 7, etc.

Check String is Empty:

  • isEmpty() method of String
    • Checks whether invoking String is empty or not
    • Returns true, if invoking String is empty otherwise false
    • If invoking string is null, then java.lang.NullPointerException is thrown

CheckStringIsEmpty.java

package in.bench.resources.java8.string.methods;

import java.util.stream.Stream;

public class CheckStringIsEmpty {

	public static void main(String[] args) {

		// 1. string
		String str1 = "Habibi, Come to Dubai";


		// 1.1 checking string is empty
		boolean bool1 = Stream.of(str1).anyMatch(s -> s.isEmpty());
		System.out.println("Whether (" + str1 + ") is Empty = " + bool1);


		// 2. Empty string
		String str2 = "";


		// 2.1 checking string is empty
		boolean bool2 = Stream.of(str2).anyMatch(s -> s.isEmpty());
		System.out.println("Whether (" + str2 + ") is Empty = " + bool2 + "\n\n");


		// 3. null string
		String str3 = null;


		// 3.1 checking empty on null string
		boolean bool3 = Stream.of(str3).anyMatch(s -> s.isEmpty());
		System.out.println("Whether (" + str3 + ") is Empty = " + bool3);
	}
}

Output:

Whether (Habibi, Come to Dubai) is Empty = false
Whether () is Empty = true


Exception in thread "main" java.lang.NullPointerException: Cannot invoke 
"String.isEmpty()" because "s" is null
	at in.bench.resources.java8.string.methods.CheckStringIsEmpty.lambda$2(CheckStringIsEmpty.java:32)
	at java.base/java.util.stream.MatchOps$1MatchSink.accept(MatchOps.java:90)
	at java.base/java.util.stream.Streams$StreamBuilderImpl.tryAdvance(Streams.java:397)
	at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
	at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
	at java.base/java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:230)
	at java.base/java.util.stream.MatchOps$MatchOp.evaluateSequential(MatchOps.java:196)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.anyMatch(ReferencePipeline.java:632)
	at in.bench.resources.java8.string.methods.CheckStringIsEmpty.main(CheckStringIsEmpty.java:32)

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to get length of a String ?
Java 8 - How to check whether particular String startsWith specific word/letter ?