aspose file tools*
The moose likes Java in General and the fly likes how to check for empty strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to check for empty strings" Watch "how to check for empty strings" New topic
Author

how to check for empty strings

praveen kumar gowda
Greenhorn

Joined: Feb 20, 2012
Posts: 23
String name1="praveen";

String name2=new String(praveen);
if(name1=="")
{
}
if(name2=="")
{
}
my doubt is if i create string using new operator can we check against empty as shown in first if statment ..
William P O'Sullivan
Ranch Hand

Joined: Mar 28, 2012
Posts: 859

mostly No. Use compareTo() or equals()

WP
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Always use equals() to compare objects' states, not ==. This includes comparing Strings' contents.

Note, however, that String has an isEmpty() method.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

i agree sometimes == will work but you should use the String method equals()


SCJP
Visit my download page
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

isEmpty() certainly is better than equals("") thanks for that tip
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

William P O'Sullivan wrote:mostly No.


No "mostly" about it. It won't work.

Use compareTo() or equals


No, not compareTo(). It would be better to use equals() than compareTo(), and better to use length() == 0 than equals(), and best of all to use isEmpty().
William P O'Sullivan
Ranch Hand

Joined: Mar 28, 2012
Posts: 859

Try this ... It does work! ;)


Now, For the record I am very against using the "==" for Strings, and recommend NOT using it at all!

WP
Koen Aerts
Ranch Hand

Joined: Feb 07, 2012
Posts: 344

It works because "" goes into the string pool and so you're comparing the same "pointers" (i.e. same objects) with the ==. With that logic, the following would work, too:
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

William P O'Sullivan wrote:Try this ... It does work! ;)


The OP asked about
if i create string using new operator
. In that context (which I thought is what you were answering), it doesn't work at all.

And even in the context you posted, I wouldn't call it "working." The OP wants to compare the contents of 2 Strings. The code you posted doesn't do that. It happens to produce the same result for that particular case, but I don't call taht "working".
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: how to check for empty strings