Java Reference
In-Depth Information
StringBuffer s =
new
StringBuffer(
"hello"
);
removeFirstCharacter(s) ;
System. out . println ( s ) ;
}
}
In the example, the
removeFirstCharacter
method removes the first character of the
string. Note that if the method took as input a
String
instead of a
StringBuffer
,thenit
would be impossible for the method to modify the string and the changes to be seen inside
the
main
method. The
setCharAt
method changes the character at the position that is
specified as the first parameter. The
setCharAt
method is part of the
StringBuffer
class,
but not the
String
class. The reason is that the
String
class is immutable and therefore
cannot be modified. The
charAt
method is part of both classes and returns the element at
the specified position.
It is worth examining the method
removeFirstChracter
in detail. When
i=1
,the
method reads the character at position 1 and places it at position 0. Then it reads the
character at position 2 and places at position 1 and so on. In other words, all the characters
except for the first character are shifted to the left by one position. Note that if we first
shifted the last character one to the left, then the whole string will contain just the last
character. Therefore, it is important that we started shifting characters from left to right
and not from right to left. The
deleteCharAt
method is used to delete the last character.
If the method was not executed, then we would have two copies of the last character at
the last two positions of the string (i.e., gotten the string
"elloo"
instead of the string
"ello"
). The smart reader has probably noticed that the method
removeFirstCharacter
can be significantly shortened.
public static void
removeFirstCharacter(StringBuffer s)
{
s . delteChraAt(0) ;
}
However, we chose the longer version in order to demonstrate how an element of a list
can be deleted by moving elements.
Note that we cannot use the following syntax for the
StringBuffer
s.
s=
"dog"
;
To put it differently, the
String
class behaves similar to a primitive type. It can be directly
assigned a value and we do not need to use the
new
keyword to crate a new string. However,
this is not the case for the
StringBuffer
class. A new
StringBuffer
can be created by
passing a string to its constructor.
StringBuffer s =
new
StringBuffer(
"dog"
);
As we saw, once a
StringBuffer
is created, we cannot simply change its value. However,
we can use the
append
method to append more characters to the
StringBuffer
.Consider
the following code.
s . append(
"cat"
);
It will append the string
cat
to the
StringBuffer s
. In other words, the
StringBuffer s
will now be equal to
dogcat
.