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!
CodePudding user response:
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.
CodePudding user response:
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);
CodePudding user response:
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.