This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

The difference of String and StringBuffer?  RSS feed

 
Gary Kevin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,guys,I have two codes and I can't understand why they produce different results:

public class Test {
public static void main(String[] args) {
String a=new String("A");
String b=new String("B");
oper(a,b);
System.out.print(a+","+b);
}
static void oper(String c,String d){
c.concat("B");
d=c;
}
}
results:A,B


public class Test {
public static void main(String[] args) {
StringBuffer a=new StringBuffer ("A");
StringBuffer b=new StringBuffer ("B");
oper(a,b);
System.out.print(a+","+b);
}
static void oper(StringBuffer c,StringBuffer d){
c.append("B");
d=c;
}
}
results:AB,B
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The "d=c" statement doesn't have an affect after the method returns, as Java uses pass by copy (of the reference).



Again, the "d=c" statement doesn't have an affect after the method returns -- same reason.

The concat() method also doesn't have an affect on the "c" string. Strings are immutable, the concat() method doesn't change the string. Instead, it returns a new string, which in this case, is ignored.

Henry
 
Lucas Lee
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A String cannot be changed and returned as a method parameter,but a StringBuffer can be.
So do not use method like this,but return the result explicitly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!