Page 312 - ComputerScience_Class_11
P. 312
The setLength() Method
We use the setLength() method to set the length of the StringBuffer variable. This also truncates the extra characters
if a string of more characters is entered. The syntax of the method is:
StringBuffer string_object.setLength(Number of characters);
Let us see the below example:
Program 27 Write a program to set the length of a StringBuffer and print the result.
1 class setLength
2 {
3 public static void main(String[] args)
4 {
5 StringBuffer s1= new StringBuffer("I am not going to play");
6 s1.setLength(10);
7 System.out.println(s1);
8 }
9 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
I am not g
Since 10 characters can accommodate, the StringBuffer object will contain “I am not g” and the rest will truncate.
The reverse() Method
We use the reverse() method to reverse the characters in the given string. The syntax of the method is:
StringBuffer_object.reverse();
Let us see the examples below:
Write a program to reverse a string using the reverse() method in a StringBuffer and print
Program 28
the result.
1 class stringReverse
2 {
3 public static void main(String[] args)
4 {
5 StringBuffer st= new StringBuffer("Computer");
6 st.reverse();
7 System.out.println(st);
8 }
9 }
310 Touchpad Computer Science (Ver. 3.0)-XI

