1

Possible Duplicate:
Java String.equals versus ==

I have a string called DomainType which usually holds values like "edu,com,org..etc" from a url. I used an if else statement to help check the data type and output a JOptionPane. For some reason whenever you type any domain type, It gives you the last option.

Here is a Snippet from the code I wrote:

DomainType = URL.substring(URLlength - 3, URLlength);

if (DomainType == "gov") {
    JOptionPane.showMessageDialog(null, "This is a Government web address.");
}
else if (DomainType == "edu") {
    JOptionPane.showMessageDialog(null, "This is a University web address.");
}
else if (DomainType == "com") {
    JOptionPane.showMessageDialog(null, "This is a Business web address.");
}
else if (DomainType == "org") {
    JOptionPane.showMessageDialog(null, "This is a Organization web address");
}
else {
    JOptionPane.showMessageDialog(null, "This is an unknown web address type.");
}

so the DomainType gives me edu or com no problem but i think it's my if statement I'm not doing right.

Community
  • 1
  • 1
Alen
  • 45
  • 3
  • 5
    I wonder how many millions of hours have been wasted due to the Java designers deciding to use == this way... We'll probably see the same questions pop up for ever... sigh – JRL Oct 01 '11 at 14:24
  • Yep really an annoying limitation. Oh well – Voo Oct 01 '11 at 14:29
  • Why should the "==" operator work differently for `String` than any other object? That would be stupid... even more stupid than the string concatenation operator looking the same as the arithmetic addition operator. – erickson Oct 01 '11 at 14:52

3 Answers3

4

When comparing strings, never use ==, use equals. So, instead of

DomainType == "org"

use

DomainType.equals("org")

Why? == will compare references. That means: memory values. And they may not be equal for your strings. equals will compare values, and that is what you want.

darioo
  • 46,442
  • 10
  • 75
  • 103
1

To compare content use equals, not == (which compares references):

if (DomainType.equals("gov")) {
MByD
  • 135,866
  • 28
  • 264
  • 277
0

On a side note, a mega-if is probably not the most elegant way to do that - http://www.antiifcampaign.com/ - sorry, just being pedantic.

The .equals() method is the right way to compare objects indeed.

Savino Sguera
  • 3,522
  • 21
  • 20