Week 68 — Which mechanisms does Java provide for concatenating `String`s with other variables?
Question of the Week #68
Which mechanisms does Java provide for concatenating
String
s with other variables?11 Replies
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:
Other than that, the String
class provides a concat
method that can concatenate two String
s:
It is also possible to use String.format
which allows printf
-like format specifiers:
Aside from that, String templates, which are currently (as of Java 22) a Preview feature, allow doing that as well:
📖 Sample answer from dan1st
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
Submission from rahulsaini_1957
Usually you can concatenate with
Submission from ogbudsz
For concatenation of string with other variables addition "+" mechanism is provided by java
Submission from dead_pool4
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
Submission from _draws
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
Submission from matieuu
In java we can use an empty string
Eg:
class hi{
void hello{
String a=“hi”
String B=“world”
String c=a+B}}
@JavaBot
Submission from juanisrockingx
1. We can use '+' operator.
2. Also String.format() is available.
3. StringBuilder is another option.
⭐ Submission from cutie.joy
**
Possible answer:
1) + operator is used to concatenate two strings.
2) StringBuilder also gives us the capability to concatenate strings and other variables.
**
1) Code:
String s1 = "java ";
String s2 = "week";
System.out.println(s1 + s2);
Output:
-> java week
*
2) Code
String str = "java week ";
int a = 1;
StringBuilder stb = new StringBuilder();
stb.append(str);
stb.append(a);
System.out.println(stb.toString());
Output:
-> java week 1
⭐ Submission from sk001