Computer Applications
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);
}
}
Java
User Defined Methods
4 Likes
Answer
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
Working
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.

Answered By
3 Likes
Related Questions
What is the role of void keyword in declaring functions ?
How is call-by-value way of function invoking different from call-by-reference way ? Give appropriate examples supporting your answer.
Write a function that takes two char arguments and returns 0 if both the arguments are equal. The function returns -1 if the first argument is smaller than the second and 1 if the second argument is smaller than the first.
Write a complete Java program that invokes a function satis() to find whether four integers a, b, c, d sent to satis( ) satisfy the equation a3 + b3 + c3 = d3 or not. The function satis( ) returns 0 if the above equation is satisfied with the given four numbers otherwise it returns -1.