VOOZH about

URL: https://www.geeksforgeeks.org/java/java-string-isempty-method-example/

⇱ Java String isEmpty() Method with Example - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java String isEmpty() Method with Example

Last Updated : 20 Nov, 2024

In Java, the String isEmpty() method checks if a string is empty (length is zero). This method returns true if the string is empty and false otherwise. It is useful for validating strings in our applications.

In this article, we will learn how to use the isEmpty() method in Java along with examples to demonstrate its functionality.

Example:

In this example, we will see whether a given string is empty.


Output
true
false

Syntax of isEmpty() Method

boolean isEmpty()

Return Value:

  • It returns true if the string length is 0.
  • Returns false otherwise.

Java Programs to Demonstrate String isEmpty() method

1. Validate User Input using isEmpty()

To ensure that the user input is not empty before processing it, we can use isEmpty() method of String class.

Example:


Output
Enter a username: No input provided.


2. Check Multiple Strings using isEmpty()

We can use isEmpty() method to validate multiple strings.

Example:


Output
Is string at index 0 empty? false
Is string at index 1 empty? true
Is string at index 2 empty? false


3. Using isEmpty() with Conditional Logic

To handle different scenarios, combine isEmpty() with conditional checks.


Output
The message is empty.

Explanation:

The above example checks if the m string is empty using the isEmpty() method and prints the message.

Comment