Interview question
What are different ways to concatenate strings in Java? Java में strings को concatenate करने के कितने तरीके हैं?
Answer
String result = "Hello" + " " + "World";
String s1 = "Hello".concat(" World");
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.append("Number ").append(i);
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
String joined = String.join(", ", "Apple", "Banana", "Cherry");
String formatted = String.format("Name: %s, Age: %d", "John", 30);String Concatenation Methods:
1. + operator
2. concat()
3. StringBuilder
4. String.join()
5. String.format()
StringBuilder is preferred in loops for performance.Was this answer clear?