Possible Duplicate:
Why is there no String.Empty in java?
Is there a JDK constant for an empty String, something like String.EMPTY, equaling ""? I can't seem to find it. I would prefer using that rather than "".
Thanks
Possible Duplicate:
Why is there no String.Empty in java?
Is there a JDK constant for an empty String, something like String.EMPTY, equaling ""? I can't seem to find it. I would prefer using that rather than "".
Thanks
No, there isn't. But since the entire world (well, almost) uses Jakarta Commons-Lang, you can, too. Use StringUtils.EMPTY
: http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#EMPTY
What's wrong with ""
? It behaves like a constant, it's taken from the string pool and it's really short to write, much shorter than String.EMPTY
.
Also, if what you need is to test if a string is empty, just do this:
myString.isEmpty();
UPDATE
If the string can be null, better use either isEmpty()
or isNotBlank()
from Apache Common's StringUtils class.
Apache Commons does exactly what you want. It has a constant named StringUtils.EMPTY. If you want to take a look, here is the link to the library: http://commons.apache.org/lang/
Others have already pointed out the .isEmpty() function, so I'll go one further. I wanted tell if a string is Null or Empty or Whitespace (ie spaces and/or tabs). So I wrote my own method to do it.
//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 these, you would do something like
String myString = "whatever";
if(stringIsNullOrWhiteSpace(myString))
{
doSomething();
}
Good luck!
There is nothing in the default JDK that I am aware of. You may need to define your own constant, or import a third party library that has one.
If your intention is to check for empty string you could try the following.
YOUSTRING.isEmpty();
However note that isEmpty is not Null safe, and not in all versions of the JDK.
To be null safe, use "".equals(YOURSTRING);
However this adds empty string into the HEAP each time you do it. Thus it is best to point to a public static final
constant, so that there is only ever one on the heap.