Java Reference
In-Depth Information
What will be the content of
s1
at #4?
String
is a reference type in Java. At #1,
s1
is referencing a
String
object
whose content is
"hi"
. When the
changeString(s1)
method is called,
s1
is passed to
s2
by reference value. At #2,
s1
and
s2
are referencing the same
String
object in memory whose content is
"hi".
When
s2 = s2 + " there"
statement is executed, two things happens. First,
s2 + " there"
expression is evaluated, which creates a new
String
object in memory with content of
"hi there"
returns its reference. The reference returned by the
s2 + " there"
expression is assigned to
s2
formal parameter. At this time, there are two
String
objects in memory: one with the
content of
"hi"
and another with the content of
"hi there"
. At #3, the actual parameter
s1
is referencing the
String
object with the content of
"hi"
and the formal parameter
s2
is referencing the
String
object with content
"hi there"
.
When the
changeString()
method call is over, the formal parameter
s2
is discarded. Note that the
String
object with
content
"hi there"
still exists in memory after the
changeString()
method call is over. Only the formal parameter
is discarded when a method call is over and not the object to which the formal parameter was referencing. At #4,
the reference variable
s1
still refers to the
String
object with content
"hi"
. Listing 6-25 has the complete code that
attempts to modify a formal parameter of
String
type.
Listing 6-25.
Another Example of Pass by Reference Value Parameter Passing in Java
// PassByReferenceValueTest2.java
package com.jdojo.cls;
public class PassByReferenceValueTest2 {
public static void changeString(String s2) {
System.out.println("#2: s2 = " + s2);
s2 = s2 + " there";
System.out.println("#3: s2 = " + s2);
}
public static void main(String[] args) {
String s1 = "hi";
System.out.println("#1: s1 = " + s1);
PassByReferenceValueTest2.changeString(s1);
System.out.println("#4: s1 = " + s1);
}
}
#1: s1 = hi
#2: s2 = hi
#3: s2 = hi there
#4: s1 = hi
■
a
String
object is immutable, meaning that its content cannot be changed after it is created. If you need to
change the content of a
String
object, you must create a new
String
object with the new content.
Tip