Hi, String name; if(name is an empty line (with the Enter key hit) ) do something. How would I code this? I tried the following but none seemed to work. if(name == null) do something. if(name.equals(null)) do something. if(name.startsWith(" ")) do something. What can I do for the above?
also worth noting: print out the String you want to check for like: System.out.println( ">" + string + "<" ); Once you know exactly what you're looking for, it's not too hard to setup an equals() statement.
HI Lucky, The safest way to check if a String is empty would be to do:
This will "do something" only if the name object has not been created OR the constructed name has not be populated. Just ask if you need any help understanding the reason why it is safer to check that the object is null first Chris.
author and iconoclast
name.length() can't ever be less than 0; it can be exactly zero, or else name is not empty; and the trick I showed above putting the String literal first lets you write the whole thing more simply, and is an established idiom. I humbly suggest my earlier recommendation is better.
This assumes that if a string contains only whitespace (spaces, tabs, newlines, etc.) it should be considered blank. Which is not always what you want - but in my experience, it often is. Sometimes it doesn't matter because a string with just whitespace will never occur - but then if probably will occur sometime when you're not expecting it. Regardless of what code you use here, I recommend putting it a separate method like this. (Quite possibly private rather than pulic, but that depends on the nature of your project.) Even though it's really short code anyway, "isBlank()" will make the methods that use it more readable. And if you later decide that you want to change the policy about whether spaces should be considered blank, you can make the change in just one place. [ February 18, 2004: Message edited by: Jim Yingst ]
Jim, I spot a small typo... you need to use a || rather than | in the above code, so it short-cuts. Otherwise you'll get a NullPointerException if you pass in null.
Joined: Jan 30, 2000
Yes, fixed now. I don't think I've ever done that in "real" code (i.e. something I actually compiled and ran, not just posted) - I always use || and && unless there's a darn good reason to use | or &. But maybe the mind is starting to fail...
Joined: Sep 21, 2003
Thanks for pointing out my mistake. It has been one of these days!!!