Heart containing Coding Chica Java 101

The Immutable Java String! Constructing a String When All Variables Known

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Concatenation
  4. String.format
    1. format
  5. Constants Vs. Instance Variables
  6. Appending to Existing Strings
  7. Summary

Introduction

Once created, a Java String object cannot be modified. If any changes to a String value must occur, a new object is created. This can be costly both in terms of slower performance and unnecessary work by Java to collect and clean up all of the no-longer-used Java String objects created by this process.

Concatenation

Every time we concatenate String values (using the + symbol) a new String object is returned. Imagine the following command:

System.out.println(“Hello, ” + name + “!  How are you today?”);

The Strings objects that would be created before invoking the println method are similar to:

  • “Hello, ”
  • “Hello, Maisy”
  • “Hello, Maisy! How are you today?”

No matter how the Java compiler implements concatenation under the covers, we will still be creating two additional objects that are almost immediately discarded. This causes additional cleanup work and can cause performance issues in our applications.

String.format

One approach to reducing the burden of this work on the system is to use the String.format method provided in most recent Java versions. This approach requires us to know all of the values we want to include in the resulting String all at once. It works well for the situation above, where a single variable, such as name is mixed in with other predefined text.

format

public static String format(String format, Object… args)

Returns a formatted string using the specified format string and arguments.

The locale always used is the one returned by Locale.getDefault(Locale.Category) with FORMAT category specified.

Parameters:

format – A format string

args – Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java Virtual Machine Specification. The behaviour on a null argument depends on the conversion.

Returns:

A formatted string Throws: IllegalFormatException – If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the Details section of the formatter class specification.

Since: 1.5

See Also:

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#format(java.lang.String,java.lang.Object…)

The example above, might be rewritten as:

System.out.println(String.format("Hello, %s!  How are you today?", name));

Here, all of the predefined content of the String is defined in one format String (as opposed to the two predefined Strings used in the prior section) and the internal Java implementation of the format method is left to do the combining of the name variable into the format string in the most efficient means possible.

Alternatively, we might format a String value that gets stored in a variable, such as in a prior post:

String expectedGreeting = String.format("Hello, %s!", name);

Constants Vs. Instance Variables

Similarly, if a String only contains predefined text that isn’t supposed to change, then referencing it as a variable inside of an Object instance will cause needless work during Java Object creation and destruction, which may slow down runtime performance and cause needless garbage collection work to occur. Instead, defining that String as a constant (AKA a static final variable) may help avoid the needless work that we would otherwise be asking the Java runtime to perform for that variable.

/**
 * The name of the root element we expect in our person XML structure.
 **/
private static final String PERSON_ROOT_ELEMENT_NAME = "person";

Appending to Existing Strings

If constructing a larger string from elements in an array or collection, there are a few different approaches you may take to achieve the construction of the desired string in a more efficient manner than String concatenation (+). However, those will be discussed in future posts.

Summary

As Strings are immutable (unchanging) in Java, each call to the concatenation (+) operator for Java Strings results in a new String object being created. This can result in unnecessary garbage collection and slower performance in our runtime Java code. If all of the values needed for a String object are known at a single point in time, then we can use the String.format method to generate the new String in a more efficient way.

The Immutable Java String! Constructing a String When All Variables Known

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.