Open In App

Java Program to Illustrate String Interpolation

Last Updated : 21 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

String Interpolation is a process in which the placeholder characters are replaced with the variables (or strings in this case) which allow to dynamically or efficiently print out text output. String Interpolation makes the code more compact and avoids repetition of using variables 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.

String Interpolation in Java can be done in several ways with some concatenation operator or built-in functions or classes.  

Methods:

Some ways to perform string interpolation in Java are as follows:

  1. Using the ‘+’ operator
  2. Using  format() function
  3. Using MessageFormat class
  4. Using StringBuilder Class

Let us discuss them individually to a certain depth 

Method 1: Using the ‘+’ operator

We can use the + operator in the expression outside the double quotation marks, to work with strings. The variable or string name should be used before or after the + operator depending on the condition or scenario. The variable will be replaced with its value and hence we achieve interpolation or concatenation of strings.

Example

Java




// Java Program to Illustrate String Interpolation
// Using the + Operator
 
// Importing input output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Input string
 
        // String 1
        String name = "Geeks for Geeks";
 
        // String 2
        String field = "coding";
 
        // Print and display the string Interpolated
        System.out.println(
            name + " is the best platform to learn "
            + field);
    }
}


Output

Geeks for Geeks is the best platform to learn coding

 Output explanation:

In the following code example, the string variables name and field were interpolated or concatenated using the + operator between the actual text to be printed by plugging in the variable name. This is one of the easiest and convenient ways to concatenate strings as it can be customized as per the requirements. The operator can be used without the text in quotes as well. 

Method 2: Using the format() function

This method separates the text with the expression and variable name keeping it a bit compact and easy to use for small sentences or expressions. The placeholders(%s for string) are used sequentially to fit in the values of the variables provided at the end of the expression as the format() function accepts the string as the first parameter and followed by the variables. So the number of parameters will be one more than the placeholders in the string. 

Example

Java




// Java Program to Illustrate String Interpolation
// Using the format() method
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Custom input strings
 
        // String 1
        String name = "Geeks for Geeks";
 
        // String 2
        String field = "Data Structures";
 
        // Print and display the interpolated string
        System.out.println(String.format(
            "%s is the best platform to learn %s .", name,
            field));
    }
}


Output

Geeks for Geeks is the best platform to learn Data Structures .

Output explanation:

In the above code example, we have used the function format() to arrange the string by using the %s operator which works as a placeholder for a string. The sequential strings must be added after the end of the print string which will replace the placeholders.

Method 3: Using MessageFormat class

In this method, we have to import the MessgeFormat class which gives us the format function. The format function in the MessageFormat class is almost identical to the format function in the String class except the placeholders are written in a different manner. The placeholder in this function is written using the indexes such as {0},{1},{2}.. and so on. This can have some good advantages over the format function in the string class as it can avoid repetition of using the same variable again and again.

Example 

Java




// Java Program to Illustrate String Interpolation
// Using MessageFormat class
 
// Importing input output class
import java.io.*;
// Importing MessageFormat class from java.text package
import java.text.MessageFormat;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Custom input strings
 
        // String 1
        String a = "Democracy";
 
        // String 2
        String b = "people";
 
        // Print and display the interpolated string
        System.out.println(MessageFormat.format(
            "{0} is a government of the {1}, for the {1} and by the {1}.",
            a, b));
    }
}


Output

Democracy is a government of the people, for the people and by the people.

Output explanation:

In the above code example, it is quite clear that the format function in the MessageFormat class is quite effective compared to the String class function.  We have used the variable b thrice by just writing the placeholder thrice instead of writing the whole variable name thrice or many times in a particular case. This function is quite efficient in large text printing or complex systems.

 

Method 4: Using StringBuilder Class 

This method is quite lengthy and not very commonly used for the same reason. We use the StringBuilder class to instantiate a new object and call the append function to add in the variable before the formatted text in the append function. There could be as many as append functions chained up in the StringBuilder class. Though it disorients the readability of the code.

Example

Java




// Java Program to illustrate String Interpolation
// Using StringBuilder class
 
// Importing input output libraries
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Custom inout strings
 
        // String 1
        String a = "Geeks for Geeks";
 
        // String 2
        String b = "Data Structure and Algorithms";
 
        // Print an display the interpolated string
        // using the StringBuilder class and append() method
        System.out.println(
            new StringBuilder(a)
                .append(" is the best portal to learn ")
                .append(b)
                .append("."));
    }
}


 
 

Output

Geeks for Geeks is the best portal to learn Data Structure and Algorithms.

 Output explanation:

In the above code, the StringBuilder optionally accepts the parameter as a variable in this case a string, then we can chain the append function to interpolate the strings with the required text.

Conclusion: Thus, from the above 4 methods, the best one will be dependent on the balance between scalability and readability of the code. There might be other methods out there, be sure to explore them. The above methods are the most common ones, so you can get up and running with minimal code and an understanding of the syntax.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads