Java:
Об'єднання рядків
How to: (Як це зробити:)
public class StringConcatenationExample {
public static void main(String[] args) {
String greeting = "Привіт";
String who = "Світ";
String exclamation = "!";
String sentence = greeting + ", " + who + exclamation;
System.out.println(sentence); // Вивід: Привіт, Світ!
// Alternatively, using StringBuilder for better performance with many concatenations.
StringBuilder sb = new StringBuilder();
sb.append(greeting).append(", ").append(who).append(exclamation);
System.out.println(sb.toString()); // Вивід: Привіт, Світ!
}
}
Deep Dive (Поглиблений Розгляд):
Originally, strings in Java were concatenated using StringBuilder
or StringBuffer
for thread-safe operations. These classes provide methods to append strings efficiently. Directly using the +
operator for string concatenation is actually converted by the Java compiler to a StringBuilder
operation.
Why care about alternatives? Concatenating with +
is fine for a few strings, but for many, it’s less efficient. Each concatenation creates a new String
object because strings are immutable in Java. StringBuilder
is more memory-efficient for multiple concatenations and should be used in loops or when building large strings.
From a performance viewpoint for complex operations, String.format()
and MessageFormat
offer ways to create formatted strings, which internally also optimize string creation.
Java’s history has shown continuous improvements in string handling, and JDK updates often include optimizations for these operations.
See Also (Дивіться також):
- Oracle Docs on Strings
- StringBuilder JavaDoc
- Effective Java by Joshua Bloch - See the section on strings and their performance.
- Java Performance Tuning Guide - Go here for in-depth performance tuning with Java strings.