velxundussa
velxundussa

Reputation: 101

Java character not recognized correctly

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");

Upvotes: 0

Views: 1121

Answers (2)

Jean-François Savard
Jean-François Savard

Reputation: 21004

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.

Upvotes: 2

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

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.

Upvotes: 2

Related Questions