In this article, we will look at the concept of String Interpolation. We will look at its description, the need for String Interpolation. Also, we look at different techniques to perform String Interpolation with implementation in Java.
String Interpolation is a process where we evaluate a String containing one or more Placeholders (Temporary Name or Substitute) by replacing it with their corresponding values. It allows to dynamically print out text output. So, in short String Interpolation allows us to put variables right inside the String. These variables are then replaced with their actual values at runtime.
Need of String Interpolation
String Interpolation is an easier way to concatenate strings together without excessive syntax. Replacing the variable with their actual values avoids repetitive use of variables while printing the text output. Hence, it makes our code readable, compact, and efficient in writing large variable names or text. Consider this example:
public class NoStringInterpolation { public static void main(String args[]) { String studName = "Sean Henry"; String schoolName = "St. Palestine School"; String address = "501 Cannaugh Street"; String city = "California"; String pinCode = "900012"; System.out.println("Student Details:"); System.out.println("Student Name: "+studName+", School: "+schoolName+ "Address: "+address+", City: "+city+", PinCode: "+pinCode); } }
Here, we print the Student Details, we use the ‘+’ operator to concatenate the variables with the Text Strings while printing the details and it makes the code look messy. If we have more than 10 variables the code will become less readable when we concatenate all of them using the ‘+’ operator and print them. So, this is a perfect example where we could use String Interpolation.
Ways to Implement String Interpolation in Java
In Java, String Interpolation can be done in the following ways:
- Using the format() method of String class.
- Using MessageFormat Class.
- And, Using StringBuilder or StringBuffer Class.
Let us look at each in detail:
Using String.format() Method
The String class in Java provides a format() method to format String literals or objects. Its use is that it separates the text with the expression and variable name. Let us look at the general syntax for the method which we wi.
public static String format(String text, Object Parameters)
The Parameters to the method will be the variable name which will be replaced with the placeholders. The Placeholders(%s for string) in the input String text must sequentially fit in relative to the values of the variables provided at the end of the expression. The method returns a string so we can use it to format the String first then print it. But, for simplicity, we use it in a simple Print Statement. Now, let us understand this with an example:
public class StringInterpolation { public static void main(String args[]) { String studName = "Sean Henry"; String schoolName = "St. Palestine School"; String address = "501 Cannaugh Street"; String city = "California"; String pinCode = "900012"; System.out.println("Student Details:"); System.out.println(String.format("Student Name: %s, School: %s, Address: %s, City: %s, PinCode: %s", studName,schoolName,address,city,pinCode)); } }
Output:
Student Details: Student Name: Sean Henry, School: St. Palestine School, Address: 501 Cannaugh Street, City: California, PinCode: 900012
Explanation: Here, we use the format method to replace the string by using the %s operator which works as a placeholder for a string. We can also perform this for other data types like %d for int, %f for float, etc. For more details on the method refer here.
Using MessageFormatClass
In Java, the MessageFormat Class present in java.text package provides another implementation of the format method. The implementation here is a bit different than we saw above. The difference lies in the arrangement of placeholders. The placeholders in this method are written using the indexes such as {0},{1},{2}.. and so on. Let us look at the syntax of this method:
public static String format(String text, Object Parameters)
For Example: Consider this text: ” {0} is Fun to Learn”, Here {0} denotes the placeholder to replace we can pass any variable in Parameters. Like we can have a variable name=”Java” and we can place it. The text will be now: Java is Fun to Learn.
Note: The Indexing starts from 0. The first variable in arguments will replace it 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. Also, we can use this method in the same way for integers or other data types.
Let us look at the implementation.
import java.text.MessageFormat; public class StringInterpolation { public static void main(String args[]) { String studName = "Sean Henry"; String schoolName = "St. Palestine School"; String address = "501 Cannaugh Street"; String city = "California"; String pinCode = "900012"; System.out.println("Student Details:"); // {0} {1} {2} {3} {4} indicate the placeholder to be replaced with variable name in sequential way. System.out.println(MessageFormat.format("Student Name: {0}, School: {1}, Address: {2},City: {3}, PinCode: {4}", studName,schoolName,address,city,pinCode)); } }
Output:
Student Details: Student Name: Sean Henry, School: St. Palestine School, Address: 501 Cannaugh Street,City: California, PinCode: 900012
So, it is quite clear that the format method of MessageFormat class is more efficient than the format method of String. Because we can use a variable name more than once by just writing its placeholder index more than once and write it only once in Parameters.
Using append() Method
This method can be quite longer than the methods discussed above. The idea is to append a String or a Variable (Any data type) to the StringBuilder object after instantiating it. We can use both StringBuffer and StringBuilder as the append method have the same implementation. Here we do not replace, rather we append so for a large number of variables we will need many append methods chained together which will make our code less efficient and less readable. Hence, it is not commonly used for such purposes.
Still, we have a look at their code implementation in brief.
public class StringInterpolation { public static void main(String args[]) { String studName = "Sean Henry"; String schoolName = "St. Palestine School"; //using StringBuilder System.out.println(new StringBuilder(studName).append(" is a Student of ").append(schoolName)); // using StringBuffer System.out.println(new StringBuffer(studName).append(" studies in ").append(schoolName)); } }
Output:
Sean Henry is a Student of St. Palestine School Sean Henry studies in St. Palestine School
So that’s it for the article you can try each of the methods discussed above with different examples in code and let us know your doubts in the comment section below.
Its mindblowing that java really lacks $(“This is a variable: {var_a}”) syntax in 2023 and instead uses 2000 times more complex workarounds just to avoid implementing an objectively more productive method…
Overall this has to be one of the most counterproductive language I ever had the misfortune to be force to use…