0

I have a problem with Integer.toString conversion. This code outputs "ololo". Why? And how can I convert integer to string right?

 String str1= "1";
 String str2=Integer.toString(1);
 if (str1!=str2)Log.d("myLogs","ololo");    
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Sergey Shpad
  • 111
  • 1

4 Answers4

2

You must compare Strings using equals method, not == nor != operators since they will compare the String object references.

if (!str1.equals(str2)) {
    Log.d("myLogs","ololo");
}

Note that when you use Integer#toString you're creating a new String that is not in the String JVM pool, thus getting the error described.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

String comparison must be done with equals.
if (!str1.equals(str2))...

When you use != you get reference equality (inequality)

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
0

Try String.valueOf(1); to change Integer to String.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

use !str1.equals(str2) instead.

You shouldn't use == or != for String

nKandel
  • 2,543
  • 1
  • 29
  • 47
Nicholas Kadaeux
  • 2,671
  • 2
  • 14
  • 11