final doesn’t work that way. It locks out variable changes, effectively being a const for
int and all other primivite types (and as such those variables will be optimised away by a decent compiler), but won’t have the effect you think when the variable is an object or an array - which remains totally modifiable. It’s a constant pointer to a non constant object in that case. The object still has to exist somewhere -in this case that means both the
String and its contents- and be usable and elligible for garbage collection like any other one. If that’s a root variable, like a
static final, then the garbage collection won’t touch it of course, that is, until the VM shutdowns.
String are immutable by design, some something could be done there.
Edit: Now that I think about it, it might be best to just automatically declare any string literals as
static final String literal_01 ="Hello"; in a
AllStrings class and use
"Hello" is encountered.
operator<<(T value) has a major difference over
printf‘s format: it simply cannot be changed after compile time. It’s a strength (great performance and sturdiness) and a flaw depending on the context. Java’s own string format also includes indexes for parameters, which means they can be changed on the fly - a great asset for simple internationalization.
Also, for end users (especially translators), something like
"Hi, %1$s! How are you doing? I'm %2$s, nice to meet you!".format(protagName, opponentName) could be more useful than
<< "Hi, " << protagName << "! How are you doing? I'm " << opponentName << ", nice to meet you!".
And if you need to change the order because it looks best in another language, you could just replace the format string and voila -
"Bonjour, je suis %2$s ! Vous êtes bien %1$s, si je ne me trompe pas ? Enchanté !".format(protagName, opponentName).
It all boils down to what you want to achieve in the end. C++’
operator<<() is great for machines and fixed formats, but it’s more discutable for humans and their pesky languages. Altough, even the most machine-like human e.g. sys admins still love changing a log format from time time. Also, if you can transform code into data, it’s best to do so, right?
I read somewhere that the equivalent of
printf could be safely build with stream things, with safe template support too. But I doubt it’d support parameters swapping unfortunately, so it might be only syntax sugar (or salt).
Edit: Could be relatively easy to do actually, a string-swappable format by using template-based detection to determine the type of the argument at compile time to use the appropriate handler, and just keeps the formatting flags and parameters in place for adjusting the format itself. Then the format string will not control anymore which type it’s encountering, fixing the many security issues of
Yet another edit:
Could be great to have a minimal version of StringBuilder actually!