User-Defined Methods — Question 35
Back to all questionsQuestion 33
What is the output of the following program ? Justify your answer.
class Check {
public static void chg (String (nm) ) {
nm = "Aamna" ; // copy "Aamna" to nm
}
public void test( ) {
String name= "Julius";
System.out.println (name);
chg(name);
System.out.println(name);
}
}The program has a syntax error in the chg method parameter definition. The correct syntax would be public static void chg(String nm), without the parentheses around nm.
Assuming this error is fixed, then the output of the program will be as follows:
Julius
Julius
Explanation
In Java, String objects are treated differently because String objects are immutable i.e., once instantiated, they cannot change. When chg(name) is called from test() method, name is passed by reference to nm i.e., both name and nm variable point to the same memory location containing the value "Julius" as shown in the figure below:

Inside chg() method, when the statement nm = "Aamna" ; is executed, the immutable nature of Strings comes into play. A new String object containing the value "Aamna" is created and a reference to this new object is assigned to nm as shown in the figure below:

The variable name still holds the reference to the memory location containing the value "Julius". After chg() finishes execution and control comes back to test() method, the value of name is printed as "Julius" on the console.
