Junior — Middle
Explain how multiple string values can be concatenated in programming.
sobes.tech AI
Answer from AI
In Java, the most common way to concatenate multiple string values is using the + operator or the concat() method. For example:
String s1 = "Hello, ";
String s2 = "world!";
String result = s1 + s2; // "Hello, world!"
// or
String result2 = s1.concat(s2); // "Hello, world!"
For more efficient concatenation of a large number of strings, the StringBuilder class is used:
StringBuilder sb = new StringBuilder();
sb.append("Hello, ");
sb.append("world!");
String result = sb.toString();
StringBuilder is preferred for multiple concatenation operations because it is mutable and does not create new string objects with each concatenation.