0

I do not understand why the following code:

public Image getLetter(String letterToGet)
{
    System.out.println("é" == "e");

    System.out.println("Received: " + letterToGet);

    if("\u00e9" == letterToGet.toLowerCase()); {
        letterToGet = "SPECIALACCTAIGUESPECIAL";
    }
    if("\u00e8" == letterToGet.toLowerCase()) {
        letterToGet = "SPECIALACCTGRAVESPECIAL";
    }

    System.out.println("searching for " + letterToGet + " in the hashmap");
    return languageMap.get(letterToGet.toLowerCase());
}

Can return the following ouput

Traduction following ArrayList: [e, é, è]
Received: e
searching for SPECIALACCTAIGUESPECIAL in the hashmap
Received: é
searching for SPECIALACCTAIGUESPECIAL in the hashmap
Received: è
searching for SPECIALACCTAIGUESPECIAL in the hashmap

Following this logic, why does this line return false?

System.out.println("\u00e9" == "e");
velxundussa
  • 91
  • 1
  • 10
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Nir Alfasi Apr 19 '15 at 19:16

2 Answers2

2

Remember that e!=é and u00e9=é, this would return true :

System.out.println("\u00e9" == ("é"));//Notice é instead of e

Note that even if this will work in that case because we compare character literal (as @Pshemo explained in comments), make sure you compare longer strings with .equals.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • pardon, "u00e9" == "e" was a typo in my question, the actual code has the necessary "\u00e9" for it to work, will edit question, tahnks for pointing it out! – velxundussa Apr 19 '15 at 19:18
  • @velxundussa My answer still explain why it doesn't output true. – Jean-François Savard Apr 19 '15 at 19:19
  • 2
    "This not the proper way to compare string, you must use `equals`" actually *must* is too strong here, `"\u00e9" == "é"` will be also evaluated to `true` since compiler will change `"\u00e9"` to ` "é"` literal. And since all literals come from String pool these string will represent same object from string pool which means that `==` will return true. But as you noticed correctly one of the problems here was that OP was comparing `\u00e9` with `e` and not `é`. – Pshemo Apr 19 '15 at 19:24
2

The reason for the unexpected output is the extra semi-colon after the first if.

Currently, you have

if("\u00e9" == letterToGet.toLowerCase()); {
    letterToGet = "SPECIALACCTAIGUESPECIAL";
}

in which the assignment to letterToGet is outside of the scope of the if, so it will run, regardless of the value of letterToGet.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110