-1

I am unable to understand why this code doesn't work

if(value=="imperial"){
   high=high*1.8 + 32;
   low=low*1.8 + 32;
        }

But when I use the equals() method then it works fluently....

if(value.equals(getString(R.string.imperial))){
                high=high*1.8 + 32;
                low=low*1.8 + 32;}

where value is a string and R.string.imperial refers to the string "imperial".

Nitish Chopra
  • 273
  • 1
  • 4
  • 11
  • `==` compares actual objects I think. Try `.equals("imperial")` – Uroc327 Jul 11 '15 at 19:34
  • 2
    `==` vs `.equals()` : A `String` is an object, so you're comparing the location in memory of `value` against the location in memory of the `String` literal `"imperial"`. Their memory locations are different, thus `==` fails while `.equals()` is overriden by the `String` class to compare the `char` values. So if `value = "imperial"` then `value.equals("imperial")` is `true`. Note: some people use `"imperial".equals(value)` instead, this removes the possibility of a `NullPointerException`. – Jonny Henly Jul 11 '15 at 19:35
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jonny Henly Jul 11 '15 at 19:46

2 Answers2

2

Generally speaking you should use .equals when you want to test if two strings are equal. == tests reference equality, while .equals test value equality.

For a more in depth answer, take a look at the question How do I compare strings in Java?

Community
  • 1
  • 1
Jake
  • 228
  • 1
  • 2
  • 14
0

See this related stackoverflow question: Java String.equals vs ==

From an answer to that question by @Alnitak:

Use the string.equals(String other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

Community
  • 1
  • 1
varesa
  • 2,399
  • 7
  • 26
  • 45