JDK constant for empty string

Possible duplicate:
Why is there no String.Empty string in java?

Is there a JDK constant for an empty string, something like String.EMPTY, equal to "? It seems I can not find it. I would prefer to use this rather than" ".

thanks

+4
source share
5 answers

No no. But since the whole world (well, almost) uses Jakarta-Common-Lang, you can too. Use StringUtils.EMPTY : http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#EMPTY

+7
source

What happened to "" ? It behaves like a constant taken from a string pool, and it is very short to write, much shorter than String.EMPTY .

Also, if you need to check if the string is empty, just do the following:

 myString.isEmpty(); 

UPDATE

If the string can be null, it is better to use isEmpty() or isNotBlank() from the Apache Common StringUtils class.

+3
source

Apache Commons does exactly what you want. It has a constant called StringUtils.EMPTY. If you want to see, here is a link to the library: http://commons.apache.org/lang/

+2
source

Others have already specified the .isEmpty () function, so I will go further. I need to indicate if there is a Null or Empty line or Whitespace (i.e. spaces and / or tabs). So I wrote my own method for this.

 //Check to see if a string is null or empty public static boolean stringIsNullOrEmpty(String s) { return (s == null) || (s.isEmpty()); } //Check to see if a string is null or empty or whitespace public static boolean stringIsNullOrWhiteSpace(String s) { return (s == null) || (s.trim().isEmpty()); } 

To use them, you would do something like

 String myString = "whatever"; if(stringIsNullOrWhiteSpace(myString)) { doSomething(); } 

Good luck

+1
source

There is nothing in the default JDK that I know of. You may need to define your own constant or import a third-party library that has it.

If you intend to check for an empty string, you can try the following.

YOUSTRING.isEmpty();

However, note that isEmpty is not Null safe, and not in all versions of the JDK.

To be safe, use "".equals(YOURSTRING);

However, this adds an empty string to HEAP every time you do this. Thus, it is best to specify the public static final constant, so there is only one on the heap.

-1
source

Source: https://habr.com/ru/post/1438772/


All Articles