CSS font stacks & developer FAQs with Web standards
Site navigation below

One of hundreds of answers available with our premium content service.

Part answer

A: Two identical string literal assignments would create two separate string references, but they would both refer to the same string object. This is a special optimisation case that is supported by the fact that string objects are immutable in Java. Once a Java String object is created it cannot be changed, so it is safe for any number of identical string literal references to point to a single String object.

The Java compiler marks string literals in a way that the Java Virtual Machine can identify and add to its String Literal Pool, a collection of references to Java string objects. If identical string literals are found at runtime the String Literal Pool provides a reference to the first instance of the string, and no duplicate String object is created. That means that two identical string literals refer to the same Java object.

This optimisation does not apply to strings declared with the new String() constructor, as the examples below demonstrate.

… full answer hidden

Click for full answers

Premium members click below for full answer
How many objects are created for identical strings?

Home · Web fonts · Font stacks · FAQs · Java · CSS · Javascript · HTML · Site manager