'Java - How to shorten a lengthy String.format so that it is <120 chars

I tried searching for similar threads, but I am not finding much.

I am trying to shorten the following statement so that it is under 120 characters (currently 145):

return (String.format("I am driving a %s and I love it. It has a top speed of %d miles per hour and it is worth %d", carMake, topSpeed, value));

Thank you!



Solution 1:[1]

You can break the string literal in some lines:

return String.format(
        "I am driving a %s and I love it. " + 
        "It has a top speed of %d miles per hour and " + 
        "it is worth %d", 
        carMake, topSpeed, value);

The format can be changed as desired, but note the empty space on the end of each line (but the last).

The concatenation of string literals is done by the compiler, so there is no performance loss involved when splitting string literals in that way.

Solution 2:[2]

You can also do it like this if you want multiline output. It became an official construct in Java 15.

String carMake = "Ferrari";
int topSpeed = 100;
int value = 250000;

String s = 
        """
        I am driving a %s and I love it.
        It has a top speed of %d miles per hour and
        it is worth $%,d.
        """.formatted(carMake, topSpeed, value);

System.out.println(s);

prints

I am driving a Ferrari and I love it.
It has a top speed of 100 miles per hour and
it is worth $250,000.

Solution 3:[3]

Store the string in a variable

String strToFormat = "I am driving a %s and I love it. It has a top speed of %d miles per hour and it is worth %d";
return String.format(strToFormat, carMake, topSpeed, value);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 azro