StringBuilder sb = new StringBuilder("Hello World!"); sb.setLength(5); System.out.println(sb.toString());
StringBuilder sb = new StringBuilder(); sb.append("This is a sample sentence."); sb.setLength(10); System.out.println(sb.toString());Output: "This is a" In this example, the length of the StringBuilder object sb is set to 10. The output of the code will be the first 10 characters of the string, "This is a sample sentence.". Overall, the StringBuilder setLength method is used to modify the length of the StringBuilder object. It is useful for manipulating strings in different ways based on specific requirements.