jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Empty string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Empty string" Watch "Empty string" New topic
Author

Empty string

Amrita Dole
Greenhorn

Joined: Nov 12, 2003
Posts: 20
Hi,
How do you check whether a string is empty or not in Java?
Eg. string-
String str = "hello";
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,
Welcome to JavaRanch!
There are two different kinds of "empty" you might be talking about. One is zero-length; i.e., the String might be "" . The best way to test for this is to use the length() method -- i.e.,
if (s.length() == 0) ...
The other definition is that there's no String object at all -- s might be null, like a null pointer in C. The test for this looks like
if (s == null) ...

If this is possible, then be sure to test for null before calling any methods on the String; if you don't you'll get an exception.
if (s != null && s.length() > 0) ...
I'm going to have this thread moved to "Java in General -- Beginner" where it's on-topic.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Empty string