Reputation: 347
Consider the following
log.info("very long string {}, " + " another string {}", a, b)
vs
log.info("very long string {}, another string {}", a, b)
In java specification https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5
String literals are stored in compiler constant and create in compile time
String x = "very long string " + "another string"
is equal to
String y = "very long string another string"
Both x
and y
share the same reference because they are literals that are evaluated at compile time.
But is that true if the string are part of perameter calls?
Upvotes: 0
Views: 40
Reputation: 178303
Yes, you have a constant expression, according to the JLS, Section 15.29.
Constant expressions of type
String
are always "interned" so as to share unique instances, using the methodString.intern
.
Your expression is made of string literals and the +
operator, which are in the list of things allowed in constant expressions.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type (§3.10.1, §3.10.2, §3.10.3, §3.10.4), string literals (§3.10.5), and text blocks (§3.10.6)
(snip)
- The additive operators
+
and-
(§15.18)
There is no mention of any limitations based on context as to whether it's a constant expression, so even it's being passed to a method, it's still a constant expression, and it's still stored in the interned string pool.
Upvotes: 1