Java Program to Illustrate String Interpolation


String interpolation is a concatenation technique considered to display output text dynamically or effectively by replacing the placeholder characters with variables (or strings in the subsequent examples).

String interpolation restructures the code and prevents the need to repeatedly use variables to produce the output. It makes it efficient to write lengthy variable names or text just by replacing the placeholder with the variable names allocated to strings.

There are several ways in Java to perform String Interpolation with the help of the concatenation operator and library function or class.

Here, we will discuss four different methods of String Interpolation.

  • By means of the ‘+’ operator

  • By means of the format () method

  • By means of MessageFormat class

  • By means of StringBuilder Class

Using the ‘+’ operator

In the statement outside of the double quote marks, we can operate with strings by using the + operator. Depending on the circumstance or context, the variable or string name should come either before or after the + operator. We achieve interpolation or concatenation of texts by replacing the variable with its value.

Example

The following program is written to demonstrate the usage of String Interpolation using the + operator.

A class named StringInterpolation1 is created within which three string variables namely str1, str2, and str3 are declared and are assigned values – “Let us make the world”, “to live” and “in.” respectively.

The final string gets displayed on the screen by concatenating them via the + operator. A part of the final string is also written inside the output statement, however, this is optional.

Thus, it is an easy-to-use method for string interpolation.

// Java Program to Illustrate String Interpolationb By the means of the + Operator
import java.io.*;
public class StringInterpolation1 {
   // Main method
   public static void main(String[] args){
      // String 1
      String str1 = "Let us make the world";
      // String 2
      String str2 = " to live ";
      // String 3
      String str3 = " in. ";
      // display the Interpolated string
      System.out.println(
      str1 + " a better place "
      + str2 + str3);
   }
}

Output

Let us make the world a better place  to live  in.

Using the format () method

This approach keeps the text compact and simple to use for short sentences or expressions by separating the content from the expression and variable name. As the format () method receives the string as the first parameter and the variables as the second, the placeholders (%s for string) are utilized sequentially to fit in the values of the variables provided after the expression. Hence, there will be one more argument than there are string placeholders.

Example

The following program is written to demonstrate the usage of String Interpolation using the format () method.

// Java Program to Illustrate the working of String Interpolation
// by the means of the format () method
public class StringInterpolation2 {
      public static void main(String[] args){
      // String 1
      String str1 = "Let us make the world";
      // String 2
      String str2 = "to live ";
      // display the interpolated string
      System.out.println(String.format("%s a better place  %s in.", str1,str2));
   }
}

Output

Let us make the world a better place  to live  in.

In the above code, a class named StringInterpolation2 is created within which two strings namely str1 and str2 are declared and are assigned values “Let us make the world” and “to live” respectively.

The final string is displayed by the usage of the format method which takes two arguments −

  • A string containing a placeholder

  • String values to be interpolated

Here, the method contains two placeholders which get replaced by the string value provided in str1 and str2 respectively.

Using the MessageFormat Class

We must import the MessageFormat class, which provides the format function, in this method. Apart from how the placeholders are written, the format function in the MessageFormat class and the format method in the String class are nearly similar. In this function, the placeholder is written using indexes like "0," "1," "2," and so on. As it can prevent the repetitive use of the same variable, this can have some positive advantages over the format method in the string class.

Example

The following program is written to demonstrate the usage of String Interpolation using MessageFormat class.

// java program to illustrate string interpolation by the means of MessageFormat class
import java.io.*;
// Import MessageFormat class from the java.text package
import java.text.MessageFormat;
public class StringInterpolation2 {
   // Main method
   public static void main(String[] args) {
      // assigning value in String 1
      String str1 = "Have";
      // String 2
      String str2 = " working hard ";
      // String 3
      String str3 = "will";
      // String 4
      String str4 = "into";
      // display the interpolated string
      System.out.println(MessageFormat.format("{0} faith, keep {1} everything {2} fall {3} line.",	str1, str2, str3, str4));
   }
}

Output

Have faith, keep  working hard  everything will fall into line.

In the above program, four string variables namely, str1, str2, str3, and str4 are declared and are initialized with the values "Have", "working hard", "will", and "into", respectively.

The interpolated string is displayed via MessageFormat.format() method that takes two arguments −

  • A string that contains placeholders for the values to be interpolated,

  • The values to be interpolated.

In this case, the string contains four placeholders {0}, {1}, {2}, and {3}, which are replaced by the values of str1, str2, str3, and str4, respectively. The four placeholders get sequentially placed and the final output is displayed.

This method is considered better than the above two discussed methods.

Using the StringBuilder Class

Due to its length and low usage, this strategy is relatively uncommon. We create a new object using the StringBuilder class, then we use the append function to add the variable before the prepared text. The StringBuilder class allows for the chaining of as many append procedures as necessary. Yet, it makes the code difficult to read.

Example

The following program is written to demonstrate the usage of String Interpolation using the StringBuilder class.

// Java Program to illustrate String Interpolation
// by the means of StringBuilder class
import java.io.*;
public class StringInterpolation4 {
   public static void main(String[] args) {
      // String 1
      String str1 = "Tutorials Point ";
      // String 2
      String str2 = "is a website that";
      // String 3
      String str3 = "in technical as well as non technical domain";
      //display the interpolated string through
      //StringBuilder class and append() method
      System.out.println(
      new StringBuilder(str1)
      .append(str2)
      .append(" offers vast range of topics ")
      .append(str3)
      .append("."));
   }
}

Output

Tutorials Point is a website that offers vast range of topics in technical as well as non technical domain.

In this program, three string variables namely, str1, str2, and str3 are declared and initialized with the values "Tutorials Point", "is a website that", and "in technical as well as non technical domain", respectively.

The final string is displayed on the screen by using a new StringBuilder object which is created with the initial value of str1. Further, the append () method of the StringBuilder class is invoked four times to append the values of str2, a string literal " offers a vast range of topics ", str3, and a full stop at the end of the string, respectively.

Conclusion

This article threw light on the demonstration of String Interpolation in Java. The article began with a discussion of the term String Interpolation. Further, four methods and their implementation were discussed to perform interpolation of the strings.

Updated on: 12-Apr-2023

559 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements