StringBuilder sb = new StringBuilder(); sb.append("Hello "); sb.append("World"); String str = sb.toString(); System.out.println(str); // Output: Hello World
String name = "John"; int age = 25; StringBuilder sb = new StringBuilder(); sb.append("My name is ").append(name).append(" and I am ").append(age).append(" years old."); String sentence = sb.toString(); System.out.println(sentence); // Output: My name is John and I am 25 years old.In this example, a StringBuilder object is used to construct a sentence by appending variables containing name and age using the append() method. The StringBuilder object is then converted to a String object using toString() method, and the output is printed to the console. Package library: java.io