This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Empty string

 
Amrita Dole
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic