-3

I have a string variable where the value is often "0" it is also often not "0".

Whenever I update this value, it needs to be parsed. I know that this string, when it is zero it cannot be parsed.

However I do not understand why the if statement comparing two strings isn't working, there must be some logic behind it that I do not understand and I would appreciate it if someone could explain what I'm missing.

I have solved the issue by using .equals("0"), but I have no idea why this method works and the other one doesn't. Thank you in advance.

if (x == "0") {
  integer = 0;
} else {
  integer = Integer.parseInt(x);
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
adjawsdaw
  • 11
  • 4
  • 1
    The way you have it now is a reference comparison, but you want value comparison. – Mr. Polywhirl May 28 '20 at 05:09
  • 3
    @SPlatten Java != JavaScript – Mr. Polywhirl May 28 '20 at 05:10
  • 1
    Because "==" compares [object references](https://stackoverflow.com/questions/12565037/what-exactly-is-a-reference-in-java), not string values. You can read more here: https://www.geeksforgeeks.org/difference-equals-method-java/ – FoggyDay May 28 '20 at 05:10

2 Answers2

1

You need to use .equals() when comparing strings:

x.equals("0") 

To avoid problems with x being null you can do the following:

"0".equals(x) // or Objects.equals(x, "0") as suggested by @knittl

This will work correctly:

// x == "0" is reference comparison
// this is value comparison
if (x.equals("0")) {
  integer = 0;
} else {
  integer = Integer.parseInt(x);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
bhristov
  • 3,137
  • 2
  • 10
  • 26
  • 2
    And to avoid problems with x being null, make it `"0".equals(x)` or `Objects.equals(x, "0")` – knittl May 28 '20 at 05:10
  • Im i right in thinking that the "0" before the number is a default value? if the .equals cannot return a value due to X being null, it will return "0"? – adjawsdaw May 28 '20 at 05:19
  • @adjawsdaw No, "0" is a String object. We call the member function .equals on it to compare it to the value inside x. If the values match .equals returns true; if they don't match .equals returns false. I hope that this makes sense. Please let me know if I can clarify this further. – bhristov May 28 '20 at 05:22
1

I have solved the issue by using .equals("0"), but I have no idea why this method works and the other one doesn't.

== in Java compares reference (similar to "pointer" in C), String.equals() is an overriden method that will compare the content.

Geno Chen
  • 4,916
  • 6
  • 21
  • 39