-3
public static void main(String[] args) {
    Integer i = new Integer(4);
    System.out.println(i.toString());
    if (i.toString() == i.toString()) {
        System.out.println("true how");
    } else {
        System.out.println("false how");
    }

}

While executing above code, I am getting output as "false how".

Can you explain how Jvm treats this object?

Prabhu
  • 13
  • 2
  • 1
    Because the `==` operator tests for *object identity* not *equality*. `Integer.toString` need not return identical objects on multiple invocations. – 5gon12eder Dec 23 '14 at 07:16
  • 1
    [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Michaël Dec 23 '14 at 07:17
  • @5gon12eder thanks .. so Integer.toString creates new object every time. while exectuing if (i.toString() == i.toString()) this line, totally two objects created. My understanding is right? thanks in advance. – Prabhu Dec 23 '14 at 07:26
  • It may or may not create new objects. As you've tested above code, it seems to have created two different objects. You just cannot rely on it. – 5gon12eder Dec 23 '14 at 07:33

2 Answers2

2

You must compare objects with equals() method.

i.toString().equals(i.toString())
Tkachuk_Evgen
  • 1,334
  • 11
  • 17
2

toString() creates a new string object every time and your code is actually checking if both references are the same, which is never the case so it runs the else case. If you try

i.toString().equals(i.toString()) 

you'll get the desired output.

Syed Mauze Rehan
  • 1,125
  • 14
  • 31