Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

java - How many Strings are created in memory?

Say I have this String expression

String hi = "Tom" + "Brady" + "Goat"

I know that the String pool "allows a runtime to save memory by preserving immutable strings in a pool" String Pool

How many strings will be created in the string pool?

My initial guess was 5 - "Tom", "Brady", "Goat", "TomBrady","TomBradyGoat", because of the order of operations of String concatenation (left to right?) or is it only the final result, "TomBradyGoat", that is stored in the String pool?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you have here is a constant expression, as defined by the JLS, Section 15.28.

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 and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)

  • Casts to primitive types and casts to type String (§15.16)

  • The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)

  • The multiplicative operators *, /, and % (§15.17)

  • The additive operators + and - (§15.18)

(other possibilities)

The compiler determines that the expression "Tom" + "Brady" + "Goat" is a constant expression, so it will evaluate the expression itself to "TomBradyGoat".

The JVM will have only one string in the string pool, "TomBradyGoat".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...