Java isblank vs isempty

www.lautt‮.iru‬com
Java isblank vs isempty

In Java, the String class provides several methods that can be used to check the contents of a string. Two of these methods are isBlank() and isEmpty(), which are used to check if a string is empty or contains only whitespace characters.

The isBlank() method was introduced in Java 11 and returns true if the string is empty or consists of only whitespace characters. Whitespace characters are characters that are used to separate words or indicate the end of a line in text, such as spaces, tabs, and newlines.

Here is an example of how to use the isBlank() method:

String s1 = "";
String s2 = " ";
String s3 = "   ";
String s4 = "hello";

System.out.println(s1.isBlank()); // Outputs true
System.out.println(s2.isBlank()); // Outputs true
System.out.println(s3.isBlank()); // Outputs true
System.out.println(s4.isBlank()); // Outputs false

The isEmpty() method, on the other hand, returns true if the string is empty, which means it has a length of 0. It does not consider whitespace characters when checking if the string is empty.

Here is an example of how to use the isEmpty() method:

String s1 = "";
String s2 = " ";
String s3 = "   ";
String s4 = "hello";

System.out.println(s1.isEmpty()); // Outputs true
System.out.println(s2.isEmpty()); // Outputs false
System.out.println(s3.isEmpty()); // Outputs false
System.out.println(s4.isEmpty()); // Outputs false

As you can see, the isBlank() method considers whitespace characters when checking if a string is empty, while the isEmpty() method does not.

In general, you should use the isBlank() method if you want to check if a string is empty or contains only whitespace characters, and use the isEmpty() method if you want to check if a string is empty and does not contain any characters.

For more information on the isBlank() and isEmpty() methods and other methods provided by the String class in Java, you can refer to the Java documentation or other online resources.

Created Time:2017-11-03 23:27:14  Author:lautturi