vendredi 20 avril 2018

Why does my switch case work here, but if does not?

I am learning how to use Lists, and in my following example the switch case works but (what I deem as) the equivalent if statement does not. Can you tell me why?

public class Kapitel14 {

public static void main(String[] args) {

    ArrayList<String> testList = new ArrayList<String>();
    testList.add("Cousin");
    testList.add("Doof");
    testList.add("Dorf");
    testList.add("Dortmund");
    testList.add("Franz");
    System.out.println(listCount(testList));
}

public static int listCount(ArrayList<String> newList) {

    int capDCounter = 0;
    for (String element : newList) {
        String firstLetter = Character.toString(element.charAt(0));
        switch (firstLetter) {
            case ("D"):
                capDCounter++;
                break;

            default:
                continue;
        }

        //if I use this instead it returns wrong results:
        //if (firstLetter == "D") 
        //  capDCounter++;
    }
    return capDCounter;
}

Aucun commentaire:

Enregistrer un commentaire