String isEmpty()

In a recent post, we have read about the String class in java. In this post, we will learn String isEmpty() and see how it works behind.

String isEmpty()

The string isEmpty() used to check whether the current string is empty or not. This method is widely used in java because before performing any operation we check the string is empty or not. The String isEmpty() method works based on the length of the string, It returns true if the length of the string is greater than 0 otherwise it returns false.

stringName.isEmpty()

stringName: The name of string in which you want to check whether it is empty or not.

class ExampleOfContains
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA GOAL";  			 
		boolean isStringEmpty =  name.isEmpty();
		System.out.println("Is String is empty = "+ (isStringEmpty));
		 
		String name2 = "";
		boolean isEmptyString =  name2.isEmpty();
		System.out.println("Is String is empty = "+ (isEmptyString));
	}
}  

Output: Is String is empty = false
Is String is empty = true

Let’s take one more example, where we will different cases of the empty() method.
1. If a String has space then it will not consider a blank string. If you want to consider it a black string then use trim() method.
2. The character \n is considered whitespace, so the trim() method would remove it along with any other trailing space in the String.

class JavaGoal
{
    public static void main(String[] args)
    {
        String stringOne = "JAVA GOAL";
        System.out.println("Is String is empty = "+ (stringOne.isEmpty()));

        String stringTwo = "";
        System.out.println("Is String is empty = "+ (stringTwo.isEmpty()));

        String stringThree = " ";
        System.out.println("Is String is empty = "+ (stringThree.isEmpty()));

        String stringFour = "\n";
        System.out.println("Is String is empty = "+ (stringFour.isEmpty()));

        String stringFive = "''";
        System.out.println("Is String is empty = "+ (stringFive.isEmpty()));

        String newCheck = "";
        String stringSix = new String(newCheck);
        System.out.println("Is String is empty = "+ (stringSix.isEmpty()));

        String stringSeven = "\n";
        System.out.println("Is String is empty = "+ (stringSeven.trim().isEmpty()));
    }
}

Is String is empty = false
Is String is empty = true
Is String is empty = false
Is String is empty = false
Is String is empty = false
Is String is empty = true
Is String is empty = true

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.