Since Java constructs strings as references of type Object.Also, string constants are implemented as objects.
No, in Java strings are implemented as string objects. These, of course, are objects. And internal objects are manipulated by reference. And string constants are again implemented as strings.
Regarding "This is a String" + "This is another String" , I'm not sure that the Java language specification requires compilers to handle this in a certain way, but you can safely expect some decent decent compiler to evaluate this at compile time, which means it will most likely be equivalent to "This is a StringThis is another String" .
Adding a variable between string constants, of course, matters because now the expression cannot be evaluated at compile time, so the compiler will have to generate two separate string objects, one for "This is a String" and the other for "This is another String" . (Unless, of course, i is a constant, in which case it can still be evaluated at compile time.)
But I would suggest that all this is nonsense, with little impact on performance, so even if itβs good to know how they work, itβs not good to let this knowledge make you program different from what would be most natural for you to encode and understand your code.
source share