String Interpolation in Java Explained [Practical Examples]


Written By - Sweety Rupani
Advertisement

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.

In Java, We can perform String Interpolation in several ways as listed below.

  • Using + operator
  • Using format function
  • Using MessageFormat class
  • Using StringBuilder class
  • Using formatted function

 

Method-1: String Interpolation - 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: String Interpolation - 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

Advertisement
Addition of 155 and 25.500000 will be 180.500000
Hexadecimal equivalent of 155 is 9b

 

Method-3: String Interpolation - 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 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: String Interpolation - Using StringBuilder class

This is bit complicated, difficult and lengthy approach for string interpolation. 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: String Interpolation - 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 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

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment