Java Reference
In-Depth Information
method main method inc
i = 2000
initially: i = 2000
after i++: i = 3000
location 3000:
location 2000:
FIGURE 7.1: Passing an immutable object to a method.
You can create an object that belongs to an immutable class. However, this object
cannot be modified. If you try to modify an immutable object, then a new object is au-
tomatically created. Examples of immutable Java classes include Integer , Character ,
Double ,and String .
Since the existing object at location 2000 cannot be modified, a new object will be
created, say, at location 3000. The variable i inside the inc method will now be equal to
3000. However, the variable i inside the main method will still be equal to 2000. The reason
is that a Java method cannot change the content of the input parameter. When the control
returns to the main method, the object at location 2000 will be displayed and therefore the
number 3 will be printed. In other words, the result will be exactly the same as if we used a
variable of type int . Therefore, one cannot use the class version of a primitive type in order
to allow a method to modify the input. In general, any changes to a variable of a primitive
type or a wrapper class for a primitive type (e.g., Integer , Double , etc.) by a method will
not be seen by the calling method. The reason is that Java passed values to a method by
value and all wrapper classes are immutable.
In order to complete the example, suppose that we created our own MyInteger class
that stores an integer. Since this class will now be a regular class (and not immutable), the
result of our example will be different. Here is our new program.
import java . util . ;
class Test {
public static void inc (MyInteger i ) {
i . setValue( i . getValue()+1);
public static void main(String [] args) {
MyInteger i = new MyInteger (3) ;
inc( i ) ;
private int i;
public MyInteger( int i)
class MyInteger
this .i=i;
Search WWH ::

Custom Search