StringBuffer sb = new StringBuffer("Hello World!"); System.out.println("Before setLength() - " + sb.toString()); // output: Before setLength() - Hello World! sb.setLength(5); System.out.println("After setLength() - " + sb.toString()); // output: After setLength() - Hello
StringBuffer sb = new StringBuffer("Hello"); System.out.println("Before setLength() - " + sb.toString()); // output: Before setLength() - Hello sb.setLength(10); System.out.println("After setLength() - " + sb.toString()); // output: After setLength() - Hello\0\0\0\0\0In this example, we again create a new StringBuffer object with the value "Hello". We then use the setLength() method to pad the string to a length of 10. The resulting string buffer contains the value "Hello" followed by five null characters. The StringBuffer class is part of the Java.lang package library.