Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
fooMonster Avatar asked Jul 13 '11 16:07

fooMonster


People also ask

Are strings immutable in Java?

The String is immutable, so its value cannot be changed. If the String doesn't remain immutable, any hacker can cause a security issue in the application by changing the reference value. The String is safe for multithreading because of its immutableness.

Is String mutable or immutable in Java?

String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type.

How is String implemented in Java?

String str = "Hello World"; In this method, using the double quotes (") is mandatory. Whenever you pass a command to create a new string using the literal string method, the Java Virtual Machine(JVM) will search for the String in the String Pool. If the String exists, then JVM will return the reference to the String.

What does it mean strings are immutable?

When you create a string, it is immutable. That means it is read-only. When something is immutable or read-only, it means it cannot be changed at a later time.


1 Answers

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.

like image 200
Sanjay T. Sharma Avatar answered Sep 21 '22 11:09

Sanjay T. Sharma