aspose file tools*
The moose likes Beginning Java and the fly likes please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please help" Watch "please help" New topic
Author

please help

Joywish Manampadi
Greenhorn

Joined: Jan 23, 2009
Posts: 6



---------- Interpretation(Java) ----------
S1 Before Append :Hello
S1 After Append :Hello how are you
S1 after s1=s2 :doing
Hello how are you

Output completed (0 sec consumed)



Question1: why iam not getting Output on the lastline as "doing"
Question2:As s1 in main() and s1 in mybuf are different why append is changing the value of s1 in main
Question3:am i passing the value of s1 and s2 by ref or not ,i suppose i am passing value as refrence as s1 and s2 are objects. not values then how come value iam changing in testbuffer2 class is not propagated to my main class.
[edit]Add code tags, remove some smilies. CR[/edit]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Welcome to JavaRanch
Please don't simply write "please help" as a thread title: look at this FAQ. And please use the CODE button. I have edited your post and you can see how much better it looks.

As you say, Java is entirely "pass by value." I wrote about that yesterday, and have a look at this old thread, and this JavaRanch FAQ. They might be helpful. Look at the links I quoted in that old thread.

You have s1 and s2 in your main method, then you pass copies of their location to the myBuf method. So the myBuf method has values, which it calls s1 and s2. When you reassign them in myBuf, you are only reassigning the local copies. Remember pass-by-value cannot change the values passed, so the original locations of the two StringBuffers are unchanged. So when you go back to the main method, you go back to the original s1 there.

Try changing the names of the parameters in myBuf to s3 and s4. You might then find it easier see that changing s3 doesn't change the original s1.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Question 2: When you pass the original reference to s1, you are allowing your myBuf method access to a mutable class. You cannot change the reference pointed to, but you can manipulate the object in that reference. In this case you are using its append method, which does not change which object you are using. But it does alter the state of that object.

By the way: use StringBuilder rather than StringBuffer unless you specifically need synchronization.
Praveen Pagi
Greenhorn

Joined: Feb 17, 2009
Posts: 6
Thanks Bartender

Praveen
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: please help