简体   繁体   中英

In Java, is the immutability of Strings considered in the implementation of String.format()?

Since Strings in Java are immutable, I've always used StringBuilder or StringBuffer to concatenate Strings. Does the String.format() method handle this issue as well as StringBuilder or StringBuffer? In other words, does String.format() manage memory as well as StringBuffer or StringBuilder?

Based on the source code of Oracle JDK, it seems that the implementation creates a new Formatter for each String#format call which in turn allocates a fresh StringBuilder for each call. So yes. But as mentioned by the comment to your question, this is very much implementation specific though common sense entails that it would choose the most efficient way of doing things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM