Java Reference
In-Depth Information
change the string, you might think that you have changed the string assigned to the actual
parameter. But this does not happen. The string of the actual parameter remains
unchanged; a new string is assigned to the formal parameter. The following example
further illustrates this concept.
EXAMPLE 7-9 String OBJECTS AS PARAMETERS
Consider the following program:
// This program illustrates how String objects as parameters work.
public class StringObjectsAsParameters
//Line 1
{
//Line 2
public static void main(String[] args)
//Line 3
{
//Line 4
String str = "Hello";
//Line 5
System.out.println("Line 6: str before "
+ "calling the method "
+ "stringParameter: "+ str);
//Line 6
stringParameter(str);
//Line 7
System.out.println("Line 8: str after "
+ "calling the method "
+ "stringParameter: " + str); //Line 8
} //end main
//Line 9
public static void stringParameter(String pStr)
//Line 10
{
//Line 11
System.out.println("Line 12: In the method "
+ "stringParameter");
//Line 12
System.out.println("Line 13: pStr before "
+ "changing its value: "
+ pStr);
//Line 13
pStr = "Sunny Day";
//Line 14
System.out.println("Line 15: pStr after "
+ "changing its value: "
+ pStr);
//Line 15
} //end stringParameter
//Line 16
}
//Line 17
Sample Run:
Line 6: str before calling the method stringParameter: Hello
Line 12: In the method stringParameter
Line 13: pStr before changing its value: Hello
Line 15: pStr after changing its value: Sunny Day
Line 8: str after calling the method stringParameter: Hello
Search WWH ::




Custom Search