How to Check If a String Is Empty in Java


In this example, let’s us see how to determine if a string is null or invalid in order to rule out those null-pointer exceptions.

Source Code

package com.beginner.examples;

public class CheckStringIsEmptyExample {

	public static void main(String[] args) {
		
		System.out.println(isEmpty(""));
		
		System.out.println(isEmpty(null));
		
		System.out.println(isEmpty("ABC"));
	}

	public static boolean isEmpty(String str)
	{
		//Determine whether STR is empty
		//The isEmpty() method throws a null pointer exception if str isEmpty
		if(str==null||str.isEmpty())
		{
			return true;
		}
		
		return false;
	}
}

Output:

true
true
false
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments