2 ms·
To less informed readers, "smart enough" hear means: Imagine you have two Java Strings: a and b If you write the Java code: String c = a + b; The Java c
by throwaway2037 3y ago
To less informed readers, "smart enough" hear means:
Imagine you have two Java Strings: a and b
If you write the Java code:
String c = a + b;
The Java compiler will roughly replace this code with:
String c = new StringBuilder(a).append(b).toString();
I'm not sure I would say this is "smart". Rather, it is just a hack to allow Strings to override the plus (+) operator. Normally, Java does not allow operator overidding, like C++.
- masklinn 3y agoTwo things: First, it has nothing to do with overriding the + operator, the operation is statically decidable so the compiler is perfectly aware that this is a string concatenation (not a numerical addition) and string is a special builtin, the compiler can generate anything it wants. Which is exactly what it does, they just originally decided to implement string concatenation as stringbuffer/stringbuilder ops. Meanwhile the addition of integers, longs, floats, and doubles are (or were anyway) different bytecode ops. This does not require general purpose operator overloading support. Builtins are not limited to the language’s user level semantics. And second OpenJDK has not done that since Java 9 (JEP 280), the compiler now emits generic “string concatenation” bytecode for the runtime / jit to deal with.