ICSE Class 10 Computer Applications Question 35 of 43

User-Defined Methods — Question 35

Back to all questions
35
Question

Question 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);
    }
}
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
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:

What is the output of the following program ? Justify your answer. User Defined Methods, Sumita Arora Computer Applications Solutions ICSE Class 10

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:

What is the output of the following program ? Justify your answer. User Defined Methods, Sumita Arora Computer Applications Solutions ICSE Class 10

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.

What is the output of the following program ? Justify your answer. User Defined Methods, Sumita Arora Computer Applications Solutions ICSE Class 10