File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question based on pass by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question based on pass by reference" Watch "Question based on pass by reference" New topic
Author

Question based on pass by reference

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Hello friends ,
I found in one mock exam that the output of the following code is
Compilation and output of either "vandeleur", "vandeleur 0", "vandeleur 0 1" "vandaleur 0 1 2" or "vandaleur 0 1 2 3"


Code :

The variable "sName" is passed to the method "piggy(String)" since sName is a string it should be passed by reference. so the first line in the method should modify the value of the static variable to "vandeleur wiggy" then the run method should get executed and produce the result "vandeleur wiggy 0" "vandeleur wiggy 0 1" "vandeleur wiggy 0 1 2" "vandeleur wiggy 0 1 2 3"

Can any one guide me where am i going wrong ?


Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Nikhilesh Fonseca
Ranch Hand

Joined: Aug 23, 2004
Posts: 57
hey
I tried using the System.out .println in the run()
public class Tux extends Thread{
static String sName = "vandeleur";
public static void main(String argv[]){
Tux t = new Tux();
t.piggy(sName);
System.out.println(sName);
}
public void piggy(String sName){
sName = sName + " wiggy";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
System.out.println(sName);//Here
}
}
}

This is out puti got
vandeleur
vandeleur 0
vandeleur 0 1
vandeleur 0 1 2
vandeleur 0 1 2 3
Its like your main System.out.println works b4 your run method...
Any inputs.?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

since sName is a string it should be passed by reference.


Java is strictly pass by value.
This applies to all data types, primitives and reference types (of which String is one).

http://www.xdweb.net/~dibblego/java/faq/answers.html#q21


Tony Morris
Java Q&A (FAQ, Trivia)
Nikhilesh Fonseca
Ranch Hand

Joined: Aug 23, 2004
Posts: 57
Hey dude
Chk this out
public class Tux extends Thread{
static String sName = "vandeleur";
public static void main(String argv[]){
Tux t = new Tux();
t.piggy(sName);
System.out.println(sName+" Main");
}
public void piggy(String sName){
this.sName = sName + " wiggy";
//'this' so
//aceess the global Sname other wise u are creating a local Snam
//ratherthan acessing the global one
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
System.out.println(sName);
}
}
}
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Thanks friends i'll try this & let me post if i have any doubts.

I got confused after reading This Article
[ February 17, 2005: Message edited by: srini vasan ]
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Thanks to Nikhilesh and Tony .. i got it cleared.
Nikhilesh Fonseca
Ranch Hand

Joined: Aug 23, 2004
Posts: 57
hey Dude
I'm confused now!!.What exactly did u understand??
it looks like when u pass the string refrence it creates a local copy..
But since ur passing the object refrence itself it shouldnt do so
So what exactly is happening...
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Originally posted by Nikhilesh Fonsca:
hey Dude
I'm confused now!!.What exactly did u understand??
it looks like when u pass the string refrence it creates a local copy..
But since ur passing the object refrence itself it shouldnt do so
So what exactly is happening...


I got confused since the variable name in the method piggy is same as the static variable name .

So the first line in the method piggy ( sName = sName + " wiggy" ) when executed modifies only the local variable sName.
Aruna Agrawal
Ranch Hand

Joined: Jan 27, 2005
Posts: 66
to make it further clear try this
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
if sName were a StringBuffer or a char[], you would get "vandeleur wiggy", etc. But since strings are immutable, "sName = sName + " wiggy";" in method piggy() works by creating a new string, "vandeleur wiggy", and changing sName to point to it.

Since the sName formal parameter in method piggy() is just a copy of the sName field in class Tux, the original sName still refers to the original string "vandeleur".

BTW, what is a vandeleur?


Mike Gershman
SCJP 1.4, SCWCD in process
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Nice explanation.
But i dont know whats "vandeleur" .. i found this piece of code in one mock exam.
Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
Originally posted by Mike Gershman:
if sName were a StringBuffer or a char[], you would get "vandeleur wiggy", etc. But since strings are immutable, "sName = sName + " wiggy";" in method piggy() works by creating a new string, "vandeleur wiggy", and changing sName to point to it.

Since the sName formal parameter in method piggy() is just a copy of the sName field in class Tux, the original sName still refers to the original string "vandeleur".

BTW, what is a vandeleur?



So is it right to say that at one point in time or another, there were two String objects named sName, the first one points to "vandeleur" and the other one points to "vandeleur" + " wiggy"?

[ February 22, 2005: Message edited by: Paulo Aquino ]

Be Afraid...Be very Afraid...
Animesh Shrivastava
Ranch Hand

Joined: Jul 19, 2004
Posts: 298
One sName is in the heap pointing to "vandeleur" and other sName is in the stack pointing to "vandeleur wiggy".
These both are references to string objects.

Let me know if i am wrong
Nagendra Murthy
Greenhorn

Joined: Feb 23, 2005
Posts: 3
Mike, Strings are immutable...but that is not the point here.

Variable 'sName' declared within the method 'piggy' is local to the method.
so this variable will loose its scope when the method terminates, so value "vandeleur" will be retained by instance variable 'sName'.

You can try this by declaring 'sName' as int with some integer value.
Hope I made my point clear.

Thanks
Nagendra
Nagendra Murthy
Greenhorn

Joined: Feb 23, 2005
Posts: 3
more info....

t.piggy(sName);

When you pass a value by reference, only the copy of the reference is sent not the actual reference.

if you want to change the actual value then change the code

from sName = sName + " wiggy";
To Tux.sName = sName + " wiggy";

Basically we need to understand the difference b/w instance variable and automatic variables and changing the value by reference.

Hope this will solve your confusion, let me know if you still have one....
[ February 23, 2005: Message edited by: Nagendra Murthy ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

When you pass a value by reference,
...
Hope this will solve your confusion, let me know if you still have one....


I think you may have created more confusion, it is impossible to pass anything by reference.

It is possible to pass a reference by value.
It is possible to pass a primitive by value.
Java has no other fundamental data type and no other form of argument passing.

If you repeatedly say the above three statements to yourself, it might sink in - as a lecturer, I'm aware of the illusion that you might make an observation such that it appears an argument is passed by reference.
I assure you that this is not the case, and is impossible - it is merely an illusion.
[ February 23, 2005: Message edited by: Tony Morris ]
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Hi,
This is what my understanding when a Object is passed as a reference.
Guide me if i'm wrong anywhere.

A Copy of reference is passed to the method being called.

So when even there is a change in the member varibles of the object being passed it gets reflected in the original object. But when the object as a whole is modified through a assignment like myObj = null; or any other assignment, it will not get reflected. The perfect example is the code for swapping.

In the above String object is passed to a method & it gets modified in the method. Since String objects are mutable a new object is created & nothing gets reflected in the original object being passed to the method.
Bill davis
Greenhorn

Joined: Feb 24, 2005
Posts: 1
Srinivasan,

I completely agree with Nagendra Murthy
------------------------------------------------
Variable 'sName' declared within the method 'piggy' is local to the method.
so this variable will loose its scope when the method terminates, so value "vandeleur" will be retained by instance variable 'sName'.
-------------------------------------------------------------
AND
-----------------------------------------------------------------
if you want to change the actual value then change the code

from sName = sName + " wiggy";
To Tux.sName = sName + " wiggy";

Basically we need to understand the difference b/w instance variable and automatic variables and changing the value by reference
-----------------------------------------------------------------------
Hopefully this should clear your doubts and confusion...In case if you still have confusion, I suggest you to read Java 2 by Bill Brogden and make yourself clear with basic fundamentals of java.

Thanks
Bill
Nagendra Murthy
Greenhorn

Joined: Feb 23, 2005
Posts: 3
Tony,

We can pass object reference as an argument to a method
but only a copy of the reference is passed, not the actual reference

Thanks
Nagendra
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

We can pass object reference as an argument to a method
but only a copy of the reference is passed, not the actual reference


Yes, this is called "passing by value".
The data type is called a reference (VM Spec. somewhere), it is passed by value - a copy is made.

There is no possible way to pass by reference using Java.
On a similar note, there is no possible way to pass by reference using C.
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
I wish I were a student of semantics so I could show this thread in class.

I went over the posts carefully and everybody is saying the same thing, but everyone thinks the other person disagrees with him.

In a sense, Java lets you pass objects by reference. If you pass a reference to a mutable object to a method and the method changes the object, not the reference, the object stays changed when the method returns.

In another sense, Java cannot let you pass by reference. If you pass a reference to an object to a method and the method changes the reference itself to refer to a different object, when the method returns the change will not have affected the original reference.

Strings are unusual. Any time you change a String, you are really creating a new string and changing the String reference to refer to the new string. So when you pass a String to a method, the method can never change the string by manipulating the formal parameter.

One way around this is to create a single element String array, S. If you always refer to S[0] in your code, but you pass S to the method, changes to S[0] will stay changed when the method returns. You have just passed an argument by reference in a Java program. Don't let James Gosling catch you.
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
Hi Bill,
Thats what i have mentioned in my post. May be i should have put that in a different manner.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

I went over the posts carefully and everybody is saying the same thing, but everyone thinks the other person disagrees with him.

In a sense, Java lets you pass objects by reference.


Everyone almost agrees.
Java does not permit passing by reference, not even "in a sense". Passing a reference by value is not merely a semantic difference between passing by reference.

In any case, I'm over it - believe what you will, the truth prevails.
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
Originally posted by Mike Gershman:
In a sense, Java lets you pass objects by reference. If you pass a reference to a mutable object to a method and the method changes the object, not the reference, the object stays changed when the method returns.


Tony is right. Java is strictly pass-by-value, just like in C. But people often thought that by simulating a pass-by-reference, just like pointers or pointer-to-pointers (handles) in C, is the same as pass-by-reference, when technically it is not.
[ February 24, 2005: Message edited by: Alton Hernandez ]
D'Angelis Grant
Greenhorn

Joined: Feb 24, 2005
Posts: 9
Mike, Strings are immutable...but that is not the point here.


As a java newb I think that this is an important point. Unless you understand that does not change that value of the string refered to by sName you will get the question wrong.

Is it true that before the assignment, sName and this.sName are both refering to the same string object?

When I were a lad we 'ad to implement us own string classes wi' nowt but a char array and a pointer. In fact we didn't even 'av real char arrays just a pointer to a bit of memory. I'll bet more than one String + operator returned the left hand operand with the right hand one appended to it. I bet most += operators did.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Question based on pass by reference