File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Empty string

Amrita Dole

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

Joined: Jul 08, 2003
Posts: 24195

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:
subject: Empty string
jQuery in Action, 3rd edition