File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String and StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String and StringBuffer" Watch "String and StringBuffer" New topic

String and StringBuffer

Gunjaan Agarwal

Joined: Jun 07, 2006
Posts: 11
How is String passed in method call(ref or value)??
Kindly explain me the below program output

public class Test{

public static void main(String [] args) {
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java");
stringReplace (textString);
bufferReplace (textBuffer);
System.out.println (textString + textBuffer);

public static void stringReplace (String text) {
text = text.replace ('j' , 'i');

public static void bufferReplace (StringBuffer text) {
text = text.append ("C");



output is javajavac
Shiaber Shaam
Ranch Hand

Joined: Jun 16, 2006
Posts: 252
In general non primitives are passed by references only.. since string objects are immutable their originak values cant be changed... and string buffer are mutable and hence value gets changed...

Am i right... Do send more Explanations...

Amit Goyal
Ranch Hand

Joined: Feb 21, 2006
Posts: 95
Every thing in java is pass by value. u can check previous discussion on this topic.
S Thiyanesh
Ranch Hand

Joined: Mar 19, 2006
Posts: 142
Java uses only pass by value.
In case of the String, the new Object is created inside the stringReplace but it doesn't affect the original String object in the calling method.
In case of StringBuffer, the object state is modified and hence the change is reflected in the calling method.
joshua antony
Ranch Hand

Joined: Jun 05, 2006
Posts: 117
yes reference is passed, but it is passed by value
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Always Pass By Value in Java.
Ramasubbhu Allur Kuppusamy
Ranch Hand

Joined: Sep 16, 2005
Posts: 120
Java uses pass by value. The value of the reference will be passed in the case of objects.

Regards,<br />Ram.<br />SCJP 1.4
S Thiyanesh
Ranch Hand

Joined: Mar 19, 2006
Posts: 142
Pass by reference means you should be able to change the value stored in the reference variable also.
But in JAVA only the objects pointed by the reference variable is changed not the reference variable itself.
I agree. Here's the link:
subject: String and StringBuffer
It's not a secret anymore!