my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Pass By Reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Pass By Reference" Watch "Pass By Reference" New topic
Author

Pass By Reference

JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
I think I understand the difference between "pass by value" and "pass by reference". And it is pass by reference when it comes to OBJECT.
But, the case listed below:
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 );
}
}
I thought that String was an object, and therefore, "Good bye World" would be printed. On the contrary, "Hello World" is the answer. Is it because there is a different rule for String objects?
greg philpott
Ranch Hand

Joined: Nov 10, 2000
Posts: 73
Jen
You should read this: http://javaranch.com/campfire/StoryPassBy.jsp
Remember that java is "pass by value" always, for primitive's and for objects.
With primitives the value is an actual copy of the primitive.
With Objects the value is an actual copy of the reference to that object.
I hope that clears it up for you.
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
I understand the concept of "pass by value" and "pass by reference". With respect to the posted example, I think it is a "pass by reference" case because we are dealing with String object. But the output shows just the opposite. I still wish somebody could explain it.
shree vijay
Ranch Hand

Joined: Sep 18, 2000
Posts: 208
Originally posted by JiaPei Jen:

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 );
}
}
I thought that String was an object, and therefore, "Good bye World" would be printed. On the contrary, "Hello World" is the answer. Is it because there is a different rule for String objects?

Hi,
Take a closer look at what actually happens in the code. You are calling changeIt(str).
Now the method definition of changeIt is:
changeIt(String s) -- that is now you have two references str and s both pointing to the string literal "Hello world". s is actually a copy of the reference str. Therefore s and str 'contain' the same address (that of the string literal) but they are located at two different addresses.
Now if you say, s="Goodbye world", you are making the object reference s to point to a different stringliteral. That is, you are changing the 'content' of s. But str remains unchanged.
So, if you print str in main, the string which it points to, Hello,world is printed. The expln. would be better with a simple picture. But i guess this would help. You can look in the RHE too, it has a good explanation.(with a Button)

------------------
Regards,
Shree


Regards,<BR>Shree
Kirti Dhingra
Ranch Hand

Joined: Dec 13, 2000
Posts: 32
I think strings are just treated as primitive types while
passing to functions.
I modified your code just a bit and it works
public class TestClass {
static String str[] = {"Hello World "};
public static void changeIt(String s[]) {
s[0]="Good bye World";
}
public static void main( String [] args ) {
changeIt( str);
System.out.println( str[0] );
}
}
output is Good Bye World
K Singh
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
Thanks Kirti. It has always been in my mind that the String objects follow the rule of pass by value (like primitive data type), although they are objects.
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3315
    
    8
Nothing is passed by reference in Java. Everything is passed by value. In case of a primitive, the value that is passed is the value of the primitive itself and in case of an Object (INCLUDING String) the value that is passed is the value of the reference pointing to that object.
You question has nothing to do with String as such. It will happen to any object. The output that you got is not because str is a String.
For more details you may want to read this: http://enthuware.com/jqplus/FAJQuestions.html#PARAMETERPASSING
HTH,
Paul.
------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
Vijayakumar Ramakrishnan
Greenhorn

Joined: Dec 16, 2000
Posts: 24
I think thats bcoz of the immutability concept and anything passed to the method as an array is changed.
(ref : SimonRoberts etal)
Vandanam
vijay
Sandeep Nachane
Ranch Hand

Joined: Dec 06, 2000
Posts: 57
This link has a nice article on pass by val/ref. http://www.javamain.com

------------------
Visit my homepage : www.tipsmart.com


<A HREF="http://www.tipsmart.com" TARGET=_blank rel="nofollow">www.tipsmart.com</A>
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
I head is spinning now.
Listed below are two questions from Mr. Bill Brogden's Exam Cram:
First Question:
Given the following method in an application
public String setFileType( String fname ) {
int p = fname.indexOf( '.' );
if (p > 0 ) fname = fname.substring( 0, p );
fname += ".txt";
return fname;
}
and given that another part of the class has the following code
String TheFile = "Program.java";
File F = new File( setFileType(The File) );
System.out.println( "Created " + TheFile );
The answer is that
Created Program.java
will be printed.
Second Question:
What happens when this method is called with an input of "Java rules"?
public String addOK( String S ) {
S += " OK!";
return S;
}
The answer is that the mehtod will return
Java rules OK!

I believe that the setFileType method in the first question returns Program.txt, but the String object TheFile remains intact.
Is it true that passing a String object (or the reference to that object) to a method is similar to passing primitive type of data to a method? Just leave alone whatever gets cooked in the method?
Tanveer Rameez
Ranch Hand

Joined: Dec 11, 2000
Posts: 158
hi
Strings are immutable. So when you create a string:
String s=new String("hello");
then the object reference 's' point to a location in memory
holding the string "hello".Now if you append something:
s=s+" how are you?";
then object reference 's' will point to a new location holding the string "hello how are you?". There will be no appending with the earlier string "hello". The earlier string "hello" is now eligible for garbage collection since there is no reference to it(the object reference 's' point to a new string,remember).
Coming to your first problem......
So when you pass a string str through a method changeIt():
static String str = "Hello World";
changeIt( str);
then a copy of str is passed and accepted as s in the method:
public static void changeIt(String s) {
s="Good bye World";
}
note that the string "Hello World" is not passed, nor a copy of it is passed.Only a copy of object reference str is passed. This copy is accepted as 's'.We may imagine that the value stored in str ( we may consider the value in str as the address of the memory location of "Hello World"), being copied into s.So s holds the address of the locaiton of the string.
So object reference 's' points to the same location as pointed by str i.e. both point to "Hello World".
Now when you make s="Good bye World", you are making s point to a new location holding the new string. But str still points "Hello World";
hope you get the concept.
Tanveer

Author of JPhotoBrush Pro (www.jphotobrushpro.com)
greg philpott
Ranch Hand

Joined: Nov 10, 2000
Posts: 73
good answer Tanveer.
I'd like to clarify things further.
Jen, saying "pass by reference" is not right. If you insist on not saying "pass by value" you should instead say "pass by copy of reference" or "pass object reference by value".
going further back in the thread: . . .
public class TestClass {
static String str[] = {"Hello World "};
public static void changeIt(String s[]) {
s[0]="Good bye World";
}
public static void main( String [] args ) {
changeIt( str);
System.out.println( str[0] );
}
}

Question: What is happening here? (You are probably wondering why this works and your original code doesn't, right?)
Answer:

  1. the method changeIt takes a copy of the reference to the object array, s (which is a copy of the object reference str)
    (Make sure you note that each element of the object array is (another)reference to another object)
    So the references are 2 levels deep (it would help if you drew yourself a picture of this)
  2. Now the following line is executed: s[0]="Good bye World";
    It is very important to see exactly what happens here. What happens is that the reference to the object of the 0th element of the object array is changed to point to a new String.
    We have changed the underlying object that both references s and str are pointing to !
  3. So finally when we execute: System.out.println( str[0] );
    str still references the array object, and the 0th element references the new string "Good bye World", so that is what is printed.

  4. if the method looked like this:
    public static void changeIt(String s[]) {
    s = new String[];
    s[0]="Good bye World";
    }
    then the quoted program would print out "Hello World", why?
    because, and say it with me Jen, Java is "pass by value" not "pass by reference".
    [This message has been edited by greg philpott (edited December 19, 2000).]
JiaPei Jen
Ranch Hand

Joined: Nov 19, 2000
Posts: 1309
Many many thanks for the wonderful responses provided by all of you.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Pass By Reference