Different methods to perform String Interpolation in Java
As we know, Strings are immutable objects in Java, which means we cannot modify the part of the string. So, When there is need to build a String dynamically we can use this approach. String Interpolation is a process that replaces the placeholders with the values in a string literal. It helps in making the code more compact so as to avoid declaring variable just to print the output. String Interpolation replaces the placeholder with the mentioned variable names assigned to strings and hence makes it efficient to write large variable names or text.
We can perform String Interpolation in Java in several ways as listed below.
-
Using
String.format()
: Java's version of string interpolation. It allows placeholders in strings to be replaced by specified values. -
Concatenation using the
+
operator: Basic java string interpolation method using addition of strings, though not efficient for multiple interpolations. -
Using
StringBuilder
orStringBuffer
: Java's way to build or interpolate strings in a more memory-efficient manner, especially for large amounts of data. -
Java MessageFormat Class: Allows complex java string interpolation using patterns and can even handle localization.
-
Using the
printf
method: Similar toString.format()
, it's a java string interpolation method borrowed from C'sprintf
function. -
Apache Commons Text's
StringSubstitutor
: An external library for java string interpolation, providing a more flexible way to replace placeholders in strings. -
Template Engines (e.g., FreeMarker, Thymeleaf): External libraries/frameworks that allow java string interpolation, especially useful for web applications and generating dynamic content.
-
Java Expression Language in JSPs: Enables java string interpolation for web pages, allowing embedding Java directly into HTML pages.
-
SLF4J for Logging Interpolation: Java logging framework that supports string interpolation to embed values directly in log messages.
Method-1: Using + Operator
This is the simplest approach for string interpolation in Java. As we know, java uses + operator to concatenate the strings. We can also use it for string interpolation. When the variable name is placed outside the double quotes, it will be replaced by the value of that variable in the output string.
Example : In this example, we are scanning a name from user and then print the customized welcome message.
// Program to demonstrate the use of + operator
// Importing a package
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initializing variable
String name, l;
Scanner sc = new Scanner(System.in);
// Get name and programming language from the user
System.out.println("Enter your name");
name = sc.nextLine();
System.out.println("Enter which programming language you wish to learn");
l = sc.nextLine();
// Using + operator to concatenate the string
System.out.println("Hello " + name + ", Welcome to the world of " + l + " Programming");
}
}
Output
Enter your name Sweety Enter which programming language you wish to learn Python Hello Sweety, Welcome to the world of Python Programming
Method-2: Using format function
The format function is present in the String class of lang package in Java. We can use this approach for small strings and expressions. Here, the format method is used to formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers. The format specifiers begin with a "%
" sign followed by 1 or 2 character that specifies the kind of formatted output.
The following format specifiers are used based on variable type.
- d - formats an integer value
- f - formats a floating value
- n - outputs platform specific line terminator
- x - formats an integer as hexadecimal value
- s - formats value as a string
Example : In this example, we are using int and float value and evaluating an expression. We are also displaying the hexadecimal value of an integer variable.
// Program to demonstrate the format function
public class Main {
public static void main(String[] args) {
// Initializing the variables
int a = 155;
float f = 25.5 f;
// Using format function
System.out.println(String.format("Addition of %d and %f will be %f ", a, f, (a + f)));
System.out.println(String.format("Hexadecimal equivalent of %d is %x", a, a));
}
}
Output
Addition of 155 and 25.500000 will be 180.500000 Hexadecimal equivalent of 155 is 9b
Method-3: Using MessageFormat class
In Java, MessageFormat
class is present in java.text
package. The MessageFormat
class provides a means to produce concatenated messages or string interpolation in Java using format method. The format function of the MessageFormat
class is very similar to the format function in the String class. The difference between this is the way the placeholders are written. Here, The placeholder are written using the indexes starting from index 0 representing the index of the arguments passed. We can either pass an index of an argument or can add format type and format style along with that.
The MessageFormat
class uses the following patterns. We can use any of this three patterns.
- {Argument Index}
- {Argument Index, FormatType}
- {Argument Index, FormatType, FormatStyle}
Here, Argument Index represents the index of argument in the function starting from index 0.
- Format type can be number, date, time, or a choice.
- FormatStyle can be short, medium, long, full, integer, currency, percent.
Example : In this example, we will use format function with all the three patterns mentioned above to display a message.
// Importing a package
import java.text.MessageFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initializing a variables and objects
int r = 7;
String event = "an earthquake ";
// Using format function of messageformat class
String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} of {0,number,integer} Richter scale.", r, new Date(), event);
System.out.println(result);
}
}
Output
At 10:46:03 PM on Jan 10, 2022, there was an earthquake of 7 Richter scale.
Method-4: Using StringBuilder class
This is bit complicated, difficult and lengthy approach for string interpolation in Java. So, it is not widely used as the other approaches. Here, we will use append method of StringBuilder class to build the string. There is no limitations on number of times this function can be used. But, as the size of string increases, it becomes difficult to read the statement.
Example : In this example, we will use append method of StringBuilder class to build a message.
// Program to demonstrate the append function of Stringbuilder class
// Importing a package
import java.io.*;
public class Main {
public static void main(String[] args) {
// Initializing a variables and objects
int students = 70;
int teachers = 3;
String b = "There are ";
// Using append function of stringbuilder class
StringBuilder s = new StringBuilder(b).append(String.valueOf(students)).append(" students and ").append(String.valueOf(teachers)).append(" teachers in the class.");
System.out.println(s);
}
}
Output
There are 70 students and 3 teachers in the class.
Method-5: Using formatted method
From Java 15 or higher versions support formatted method of a string class. This method formats the string as the format string and argument. The argument passed must be of object type.
Example :
// Program to demonstrate the formatted function of string class
public class Main {
public static void main(String[] args) {
// Initializing string array
String x[] = {
"There are",
" students in the class."
};
// Using formatted function of string class supported from Java 15 or higher versions
String s = "%s 75 '%s' ".formatted(x);
System.out.println(s);
}
}
Output
There are 75 students in the class.
Summary
The knowledge of String Interpolation in Java is a very useful feature that allows building the strings in desired format by embedding variables, arithmetic expressions directly into another string. This helps in making the code compact and avoids the memory wastage. In this tutorial, we covered several ways for string interpolation. We learned in detail about the usage of built-in methods along with example. All in all, this tutorial, covers everything that you need to know in order to understand the string interpolation and choose an appropriate approach for your application.
References
Format Function
MessageFormat Class
StringBuilder Class
formatted Function