Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String and StringBuffer

 
Gunjaan Agarwal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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');
//System.out.println(text);
}

public static void bufferReplace (StringBuffer text) {
text = text.append ("C");
//System.out.println(text);

}

}

output is javajavac
 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every thing in java is pass by value. u can check previous discussion on this topic.
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes reference is passed, but it is passed by value
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Always Pass By Value in Java.
 
Ramasubbhu Allur Kuppusamy
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java uses pass by value. The value of the reference will be passed in the case of objects.
 
S Thiyanesh
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
So in JAVA there is ONLY PASS BY VALUE.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic