0

I am fairly new to java, and I cannot figure out for the life of me why this piece of code is not working, I am trying to see if a word is an adverb, and hence if it ends in "ly" or not (they will always be lowercase). This is my code:

    String str = "evenly";
    int a = str.length()-2;
    int b = str.length();
    String res = (String)str.substring(str.length()-2,str.length());
    System.out.println(res + " == ly -> " + (res == "ly"));

I am testing it here: http://ideone.com/4FuBwj The output is: ly == ly -> false
Which means that, res = "ly" but res == "ly" is false?
Why is this happening?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Goulash
  • 3,708
  • 6
  • 29
  • 48

1 Answers1

2

As @Kon has stated in the comments, you shouldn't be comparing the Strings with the == operation, it should be done with the String.equals() method. You could possibly even use the String.equalsIgnoreCase() method if you're wanting to ignore case sensitivity between the values.

System.out.println(res + " == ly -> " + (res.equals("ly")));

or as above

System.out.println(res + " == ly -> " + (res.equalsIgnoreCase("ly")));

Hope this helps!

user2277872
  • 2,963
  • 1
  • 21
  • 22