0

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;
}
Crenshaw
  • 13
  • 5

1 Answers1

1

Use

if (firstLetter.equals("D"))
             capDCounter++;

instead of

if (firstLetter == "D") 
          capDCounter++;

.equals() method should be used here as you want to compare the values of strings.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29