3

How come the first condition is false and the second is true? I was sure they were both true.

System.out.println(Integer.toString(3) == "3");
System.out.println(Integer.parseInt("3") == 3);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
stuski
  • 199
  • 1
  • 11

1 Answers1

5

Integer.parseInt converts a String to a primitive int and primitives can be compared with ==. However, Integer.toString produces a String object and == for objects checks that they are the exact same reference; use String#equals instead to compare the values of the Strings.

System.out.println(Integer.toString(3).equals("3"));
System.out.println(Integer.parseInt("3") == 3);

The above code outputs:

true
true
Unmitigated
  • 76,500
  • 11
  • 62
  • 80