beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java String isEmpty() method with example

By Chaitanya Singh | Filed Under: String handling

Java String isEmpty() method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. In other words you can say that this method returns true if the length of the string is 0.
Signature of isEmpty() method:

public boolean isEmpty()

Java String isEmpty() method Example

public class Example{  
   public static void main(String args[]){  
	//empty string
	String str1="";  
	//non-empty string
	String str2="hello";  

	//prints true
	System.out.println(str1.isEmpty());  
	//prints false
	System.out.println(str2.isEmpty());  
   }
}

Output:

true
false

Java String isEmpty() method Example to check if string is null or empty

As we have seen in the above example that isEmpty() method only checks whether the String is empty or not. If you want to check whether the String is null or empty both then you can do it as shown in the following example.

public class Example{  
   public static void main(String args[]){  
	String str1 = null; 
	String str2 = "beginnersbook";  

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

Output:

String str1 is empty or null
beginnersbook

Reference

String isEmpty() method – JavaDoc

Related Posts

  1. Java String intern() method
  2. Java String format() method
  3. Java String substring()
  4. Java 8 – StringJoiner Example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorials

  • Learn Java
  • OOPs Concepts
  • Java Collections

Java String

  • Java String

Java String Methods

  • String charAt()
  • String compareTo()
  • String compareToIgnoreCase()
  • String contains()
  • String concat()
  • substring
  • String valueOf()
  • String startsWith()
  • String equals()
  • String format()
  • String endsWith()
  • String indexOf()
  • String lastIndexOf()
  • String length()
  • String replace()
  • String split()
  • String trim()
  • String intern()
  • String isEmpty()
  • String matches()
  • String regionMatches()
  • String contentEquals()
  • String toCharArray()
  • String getBytes()
  • String join()
  • String getChars()
  • String copyValueOf()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap