Java String Interpolation

javaprogramstring

Interpolation of strings is not very intuitive in Java compared to Python. But there are hacks for it:

1. String Concatenation

String Concatenation is probably the most intuitive way. Use the + operator to concatenate strings and variables. Remember that the + operator is overloaded for both numbers and strings:

String name = "Alice";
int age = 25;
String message = "My name is " + name + " and I am " + age + " years old.";
System.out.println(message);

2. String.format() Method

Java provides a very powerful method, String. format(), which is very similar to printf() in C.

String name = "Alice";
int age = 25;
String message = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(message);

3. MessageFormat Class

For more advanced formatting, including localization, you can make use of the java.text class MessageFormat.

import java.text.MessageFormat;

String name = "Alice";
int age = 25;
String message = MessageFormat.format("My name is {0} and I am {1} years old.", name, age);
System.out.println(message);

4. String Templates (Java 21+)

Since Java 21, you can use the preview feature string templates for interpolation natively.

String name = "Alice";
int age = 25;
String message = STR."My name is \{name} and I am \{age} years old.";
System.out.println(message);

Before Java 21, the way most of you may know is by using the String.format() method.


Copyright © 2024 MakeItCoder