Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer and String returned from a method doubt

 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the following code:
1. public class X {
2. public static void main (String[]args) {
3. string s = new string (�Hello�);
4. modify(s);
5. System.out.printIn(s);
6. }
7.
8. public static void modify (String s) {
9. s += �world!�;
10. }
11. }

The program runs and prints �Hello�.

But for the following code:

public class test {
public static void main (String[]args) {
StringBuffer s = new StringBuffer ("Hello");
modify(s);
System.out.println(s);
}
public static void modify (StringBuffer s) {
s.append("world!");
}

}

The program runs and prints �Hello world!�.

Why for StringBuffer it is getting updated and not for String??

pls help
regards,
gitesh
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuffer is mutable whereas String is immutable.
 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like to refer you this Article : StringBuffer versus String

hope it makes you more clear in it..
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
source: my brainchild

Another bouncer:

class test1{
static StringBuffer sb = new StringBuffer("sb");
void ssb(StringBuffer sb) {
sb=sb.append("modified");
//return sb;
}



static String s = "string";
void ss(String s) {
s+="modified";
//return s;
}



public static void main(String args[]){
test t = new test();
t.ss(s);
System.out.println(t.s);
t.ssb(sb);
System.out.println(t.sb);
}
}

The above question gives output as:

string
sb

But according to the discussion above it should give
string
sbmodified

I'm in doubt again

pls help,
gitesh
 
Alexsandra Carvalho
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Gitesh,
You are mistake. I have tested and the result is:

string
sbmodified
 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Alexsandra, I made a mistake. It is printing correctly.

Dout Cleared, thanks Ranchers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic