0

Trying to split a string of space separated integers in java. To save time not converting the values to integers I wanted to do splitIntegers[i] == splitIntegers[i + 1]. However, I was unable to get any == to come out true even using splitIntegers[i] == "6", since 6 is the first integer stored in the array.

String sixString = "6 6 6";
String[] contains6 = sixString.split(" ");
boolean isSix = contains6[0] == contains6[1]; // is false was expecting true since should both be "6" and if I convert them to integers the values are allowed to be equal
boolean isSixString = contains6[0] == "6"; // is false
boolean areSixes = "6" == "6"; // is true, and can store "6" in a variable and get true

So something weird happens when you split a string in Java.

I am translating my knowledge of javaScript where my attempted solution works. Somehow I have an array of strings of 6 that do not equal a string litteral "6" or each other.

I am passing half the tests, and am sure I could speed things up If I did not have to convert the values I split into integers.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • 3
    Are you asking [how to compare String in java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)? – OH GOD SPIDERS Aug 25 '23 at 14:07
  • 1
    Arrays don't have a value-based equals method. There's a method to do that instead: `Arrays.equals` – Jorn Aug 25 '23 at 14:07
  • 1
    *"I am translating my knowledge of javaScript"* - despite the similar names the two languages are vastly different, so you should ignore your knowledge of JS when working in Java – UnholySheep Aug 25 '23 at 14:11

1 Answers1

1

boolean isSix = contains6[0] == contains6[1];

Is false was expecting true since should both be "6" and if I convert them to integers the values are allowed to be equal.

If you convert them to ints they will be equal because that is how you compare primitives.

If they are Objects they must be compared with equals. In the case of "6" they would be strings.

If the objects are Integers (not ints) then they may be compared using == depending on how they were allocated or assigned since Integer's cache values between -127 and 128 inclusive. However, in that case you are only comparing references, not the actual values.

Best practice is to compare Objects using equals and primitives using ==.

WJS
  • 36,363
  • 4
  • 24
  • 39