r/programming • • Jun 05 '18

Code golfing challenge leads to discovery of string concatenation bug in JDK 9+ compiler

https://stackoverflow.com/questions/50683786/why-does-arrayin-i-give-different-results-in-java-8-and-java-10
2.2k Upvotes

355 comments sorted by

View all comments

Show parent comment

3

u/evaned Jun 06 '18

It's not an implementation detail though.

Incrementally appending to a string (if the compiler didn't or doesn't optimize it into a StringBuilder) is O(n^2) as a result of this. By comparison, incrementally appending to a std::string in C++ is O(n). (n is the number of appends.)

Or take a visible aspect:

string s1 = "foo";
string s2 = s1;
....
.... // s2 never mentioned
....
println(s2);

no matter what happens in the ellipsis, you know s2 will not change, and println(s2) will print foo. That's because of a combination of these things: (1) s2 itself isn't changed to point at another object because it's never mentioned (and Java provides no other way to do it), and (2) the string it points to can't be changed.

By contrast:

ArrayList<Integer> a1 = new ArrayList<Integer>();
ArrayList<Integer> a2 = a1;
a1.add(5);
println(a2.size());

that prints 1, because now a2 is the list [5].

(The above may be almost-Java; it's been a while since I wrote any.)