Question of the Week #68
Which mechanisms does Java provide for concatenating Strings with other variables?
15 messages · Page 1 of 1 (latest)
Which mechanisms does Java provide for concatenating Strings with other variables?
String concatenation is the mechanism of combining a String with another variable in order to get another String containing both the original String and the other variable.
Java allows doing that using the + operator:
String s = "Hello ";
String t = "World ";
int i = 1337;
String result = s + t + i;
System.out.println(result);//Hello World 1337
Other than that, the String class provides a concat method that can concatenate two Strings:
String s = "Hello ";
String t = "World";
String result = s.concat(t);
System.out.println(result);//Hello World
It is also possible to use String.format which allows printf-like format specifiers:
String s = "Hello";
String t = "World";
int i = 1337;
String result = String.format("%s %s %d", s, t, i);
System.out.println(result);//Hello World 1337
Aside from that, String templates, which are currently (as of Java 22) a Preview feature, allow doing that as well:
String s = "Hello";
String t = "World";
int i = 1337;
String result = STR."\{s} \{t} \{i}";
System.out.println(result);//Hello World 1337
Java provides + operator to concatenate the string with other variables
Like
int a = 3;
String str = "times";
System.out.print(a+str);
// 3times
We can also use stringbuilder for optimised concatenation as strings are immutable in java for larger string we use stringbuilder
Usually you can concatenate with String + var1
For concatenation of string with other variables addition "+" mechanism is provided by java
The use of the ‘+’ operator allows the concatenation of various data types to string types. For example
str = “Hello” and x = 1
str + x = Hello1
Using the StringBuilder class and using .append() has the same effect though StringBuilder has more methods to use
For example StringBuilder
Or method .concat for string object
In the worst case "s += i" or s = "s + i"
I'll give code example later if needed
In java we can use an empty string
Eg:
class hi{
void hello{
String a=“hi”
String B=“world”
String c=a+B}}
@thorny anchor
int age = 25;
String message = "Hello, my name is " + name + " and I am " + age + " years old.";
System.out.println(message);```
2. Also String.format() is available.
```String name = "Cutie";
int age = 25;
String message = "Hello, my name is %s, and I am %d years old.";
System.out.println(message);```
3. StringBuilder is another option.
```String name = "Cutie";
int age = 25;
StringBuilder builder = new StringBuilder();
builder.append("Hello, my name is ").append(name).append(" and I am ").append(age).append(" years old.");
String message = builder.toString();
System.out.println(message);```