• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pass by reference

 
Atul Sawant
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Please read the following question...

What will the following program print?


public class TestClass
{
static String str = "Hello World";
public static void changeIt(String s)
{
s = "Good bye world";
}
public static void main(String[] args)
{
changeIt(str);
System.out.println(str);
}
}

Select 1 correct option.
a "Hello World"

b "Good bye world"


c It will not compile.


d It will throw an exception at runtime.


e None of the above.

The answer is "a". I thought it would be "b" since String is an object and it is passed by reference in method changeIt and when it changes its value the original object's value is also changed.

Kindly let me know your inputs on this.

Thanks!
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All parameter passing in Java is by value. When the String reference is used as a parameter to the method, a copy of the reference is sent to the method. So changing where the formal parameter in the method points has no effect on where the original reference points.
 
Paul Casal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

Java is not really using pass by reference, it is using pass a copy of the reference. Thus, what the called code was really doing is changing where the copy of that reference is pointing, leaving the original reference (held by the caller) intact.
 
ashni Prakash
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are passing class level static variable(str=hello world)to the changeIt method as a parameter in main method.The passed parameter value(hello world) is overwriting the declared value of changeIt methods variable s thats the output is option A .Even i got option A as output when i ran your program.To get the output you are expecting the code should be as below:

public class TestClass
{
public static String str = "Hello World";
public static void changeIt()
{

String str1="God bless you:";
System.out.println(str1);

}
public static void main(String[] args)
{


changeIt();
System.out.println(str);
}
}

the output for above code is:

God bless you
hello world

[ December 05, 2006: Message edited by: ashu prakash ]
[ December 06, 2006: Message edited by: ashu prakash ]
 
hardikjava shah
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The only reason

"Sting object is immutable"

After changing, you have to reassign it to reference to see the change.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic