String interpolation in Java
String interpolation in Java is an act where the placeholder characters are replaced with the variables or String. In principle, string interpolation is a concatenation methodology that helps to print the information dynamically and efficiently.
- String interpolation helps to make strings dynamic in Java.
- String interpolation helps to write a more compact or less cluttered code and eliminates the repetition of variables for displaying the output.
- String interpolation replaces the placeholders with the specified variables given to the strings, making it effective to write variables of large length.
- String interpolation enhances the readability of the code.
Example
Let us consider an example where we need to display the programming language.
“I am learning Java”
Now, we want to display another programming language, so the output would be as follows.
"I am learning Python."
For another programming language, the output would be.
“I am learning Ruby”
Here, it can be observed that the String “I am learning" is repetitive in all the output, and only the last value, which is a programming language, keeps on changing.
So, the changing part of the String can be substituted with a placeholder to avoid repetition and make the code more compact.
We can write it as given below.
“I am learning”
Now, here, the placeholder can be easily substituted with any of the programming languages, such as Java, Scala, Ruby, etc.
Note that the above syntax is just for understanding and is not the actual code for string interpolation.
Various approaches to implement String interpolation
String interpolation in Java can be implemented using 4 methods, which are mentioned below.
- Using the ‘+’ operator
- Using the String.format() method
- Using the StringBuilder class
- Using the MessageFormat class
Please go through the below section, where we have explained and implemented string interpolation in detail.
1. Using the ‘+’ operator
Using the '+' operator is the simplest approach to implement the string interpolation in Java. Here, we need to specify the '+' operator outside the statement, which we write inside using the double quotation mark. The variables are used before or after the '+' operator, depending on how the statement needs to be framed. The variable will be substituted with its respective value, resulting in string interpolation.
FileName: StringInterpolation1.java
// Java Program to demonstrate String Interpolation // using the + Operator import java.io.*; public class StringInterpolation1 { // main method public static void main(String[] args) { // Declare and initialize the variables for implementing string interpolation String cityName = "New Delhi"; String countryName = "India"; // Display the interpolated String using the ‘+’ operator System.out.println(cityName +" is the capital of " +countryName); } }
Output:
New Delhi is the capital of India
2. Using the String.format() method
The approach for implementing the string interpolation using the String.format() methods helps to keep the code less cluttered and simple. It is useful especially for small expressions or statements, as it separates the text from the statement and the variable name. The String.format() method takes in two parameters, the first parameter as the String and the second parameter as the variable name. The placeholder (%s for String) is placed in sequence in the expression to match the values of the variable name as specified. The count of the argument will be one more than the placeholders present in the String.
FileName: StringInterpolation2.java
// Java Program to demonstrate String Interpolation // using the String.format() method public class StringInterpolation2 { // main method public static void main(String[] args) { // Declare and initialize the variables for implementing string interpolation String programmingLanguage = "Java"; String feature1 = "Object oriented"; String feature2 = "Platform independent"; String feature3 = "Multithreaded"; String feature4 = "Robust"; // Display the interpolated String using the String.format() method System.out.println(String.format("%s is an %s, %s, %s, %s programming language ", programmingLanguage, feature1, feature2, feature3, feature4)); } }
Output:
Java is an Object-oriented, Platform independent, Multithreaded, Robust programming language
3. Using the StringBuilder class
In this approach of implementing string interpolation in Java, we make use of the StringBuilder class that creates a new object and invokes the append() method for adding the variable before the prepared expression. We can form a chain of n numbers of append() functions in the StringBuilder class. The approach of implementing string interpolation using StringBuilder class is not recommended as it increases the number of lines in the code and also affects the readability of the code.
FileName: StringInterpolation3.java
// Java Program to demonstrate String Interpolation // using the StringBuilder class import java.io.*; public class StringInterpolation3 { // main method public static void main(String[] args) { // Declare and initialize the variables for implementing string interpolation String programmingLanguage = "Java"; String platforms = "Web, desktop, mobile "; // Display the interpolated String using the StringBuilder class and the //append () function of that class System.out.println( new StringBuilder(programmingLanguage) .append(" can be used for developing ") .append(platforms) .append("applications")); } }
Output:
Java can be used for developing Web, desktop, mobile applications
4. Using the MessageFormat class
In this approach of implementing string interpolation, it is compulsory to import the MessageFormat class present in the java.text.package. The MessageFormat class gives us the format() method to implement the string interpolation. The format() method from the MessageFormat class is very similar to the format() method in the String class except for the writing format of the placeholders. In the format () method of the MessageFormat class, the placeholders are mentioned using the indexes written inside the curly brackets such as {0}, {1}, {2}, {3}. Note that the indexing starts from 0 and not from 1. The format() function of the MessageFormat class has an advantage as here; there is no need for repetition of the same variable again and again.
FileName: StringInterpolation4.java
// Java Program to demonstrate String Interpolation // using the MessageFormat class import java.io.*; // Import the MessageFormat class from the java.text package import java.text.MessageFormat; public class StringInterpolation4 { // main method public static void main(String[] args) { // Declare and initialize the variables for implementing String interpolation String a = "French"; String firstPrinciple = "liberty"; String secondPrinciple = "equality"; String thirdPrinciple = "fraternity"; // Display the interpolated String using the MessageBuilder class System.out.println(MessageFormat.format( "The three main principles of the {0} revolution are {1}, {2} and {3}.", a, firstPrinciple, secondPrinciple, thirdPrinciple)); } }
Output:
The three main principles of the French Revolution are liberty, equality and fraternity.