0

I'm new to programming, so this could be a complete oversight on my part. But I can confirm (down below) that the two values in the If tag are equivalent, but it is not returning my value.

public static LANGUAGESTRING toLangString(String text) {

    for (LANGUAGESTRING lang : LANGUAGESTRING.values()) {
        String langStr = lang.toString();
        System.out.println(langStr);
        System.out.println(text);
        if (text == langStr) {
            return lang;
        }
    }
    return null;
}

Here is what was printed out. This is not my entire LANGUAGESTRING enum, but you can get the point from here. It should return the languagestring, right? Seeing as how the 5th and 6th line are the same? And even if it was returning it, it would break the loop, right?

[14:41:45] GodToBelieverPrayerWhenNoItemNeed
[14:41:45] GodToBelieverPrayingWeak
[14:41:45] GodToBelieverPrayerTooSoon
[14:41:45] GodToBelieverPrayingWeak
[14:41:45] GodToBelieverPrayingWeak
[14:41:45] GodToBelieverPrayingWeak
[14:41:45] EnterHolyLandInfoYourGod
[14:41:45] GodToBelieverPrayingWeak
moonrobin
  • 213
  • 2
  • 9

2 Answers2

1

Use .equals instead of ==.

if(text.equals(langStr))
satnam
  • 10,719
  • 5
  • 32
  • 42
  • I'll give it a go! Thanks for the fast help! Can you explain to me why that is by chance? – Kayle Heideman Jun 22 '16 at 20:30
  • == is checking if two variables point to the same "reference" of an object. The equals() method checks to see if the two objects are the same. So, the reference check is looking to see if two things are in the same memory location, whereas the method checks to see if the data is the same or not. – satnam Jun 22 '16 at 20:31
  • Also, see here: http://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java – satnam Jun 22 '16 at 20:32
  • Alright! :) Sorry for the simple question, but I didn't exactly know what to search for! Anyways, it works! Thanks again, and I'll take a look a the link. – Kayle Heideman Jun 22 '16 at 20:33
1

The String equals() method should be used instead of ==. This is due to the that == checks for reference equality (i.e. if the two variables are pointing to the same memory address). You are instead interested in content equality (i.e. if the contents of what's stored in those memory addresses are equal)

This post explains this difference in more depth.

Community
  • 1
  • 1
moonrobin
  • 213
  • 2
  • 9