Java Reference
In-Depth Information
method main method inc
i = 2000
initially: i = 2000
after i++: i = 2000
3
location 2000:
FIGURE 7.2:
Passing a mutable object to a method.
}
public int
getValue ()
{
return
i;
}
public void
setValue(
int
i)
{
this
.i=i;
}
public
String toString()
{
return
i+
""
;
}
}
Figure 7.2 shows the new configuration. As before, the number 2000 will be passed to
the
inc
method. The difference now is in the statement:
i.setValue(i.getValue()+1)
.
Since the
i
object is mutable, the variable inside the object will be changed from 3 to 4.
Now, when control returns to the
main
method, the variable
i
will still be equal to 2000.
However, this time the content at location 2000 has changed from 3 to 4 and therefore the
program will print the number 4.
7.3 The
StringBuffer
Class
Most immutable classes do not have a mutable version. For example, there is no class
in a Java library that is similar to the
MyInteger
class. This is intentional because this
will break the rule: “If you pass a variable of type integer to a method, then the calling
method will not see any changes to the variable”. The only exception is the
String
class.
Sometimes, we want to modify the characters of a
String
without creating a new
String
object. The mutable version of the
String
class is
StringBuffer
. Below is an example of
how it can be used.
public class
Example
{
public static void
removeFirstCharacter(StringBuffer s)
{
for
(
int
i=1;i
<
s . l e n g t h ( ) ; i ++)
{
s . setCharAt( i
−
1, s . charAt( i ) ) ;
s . deleteCharAt(s . length ()
−
1) ;
}
public static void
main(String [] args)
{