Difference Between String and StringBuilder in Java?
String
Every time you modify s, a new String object is created, which consumes more memory.
Example:
String s = "Hello";
s = s + " World"; // Creates a new object
System.out.println(s); // Output: Hello World
StringBuilder
StringBuilder modifies the same object, so it's faster and more efficient for operations like loops or repeated concatenation.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies same object
System.out.println(sb); // Output: Hello World