How to know null and empty in String in Java

Asked 2 years ago, Updated 2 years ago, 42 views

I searched Google, but it didn't come out, so I'm asking you a question. Is there any method in the Java Standard Library that allows you to know that the string is empty or null?

java string

2022-09-22 15:57

2 Answers

In Java's default built-in library, there is no utility method like the one you asked. You can implement it yourself You can use the StringUtils class that belongs to the Apache commons library.

Note: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

If you want to check with blank characters, you can use String.isBlank method.

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false


2022-09-22 15:57

I think you can use isEmpty and isBlank method of StringUtils class. isEmpty returns whether the string is null or not, and isBlank returns true if the string is filled with only spaces.


2022-09-22 15:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.