Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer Doubt

 
Chinmay Kant
Greenhorn
Posts: 20
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code:-
------------------------------------------------------------------------------------------------------------------------------------------------------
public class Test15{
public static void method(StringBuffer sb){
sb.append(" Added");
sb = new StringBuffer("Hai");
}

public static void main(String a[]){
StringBuffer sb = new StringBuffer("String Buffer");
method(sb);
System.out.println(sb);
}
}
What is output?
A1 String Buffer
A2 String Buffer Added
A3 Hai
A4 Compiler Error
------------------------------------------------------------------------------------------------------------------------------------------------------

Here the O/p is String Buffer Added.

My Doubt is if it can append the String "Added" on the same Object, when it is set to new, why it does not change to newly created StringBuffer"Hai"

Thanks in Advance
 
Rohit Garg
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

There are two things in your case, the stack and the heap. You must be knowing till now that variables are stored on stack and objects on heap.

Now, if you call the append function, you are actually modifying the actual object on heap which will get reflected even outside the method.

If you try to call the new StringBuffer() method, you are trying to change the sb variable which is not reflected outside the method. (The arguments sent to a method are a copy of the bits in the variable and not the actual variable itself)

Hope that helps!

Regards.
 
ansuman mohapatra
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
even Im confused with this..in the above static method sb is getting a new instance with string "Hai". So how come its showing the output as "String Buffered Added".
 
Nadeem Khan
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just keep one point in mind and then think about it:
Whatever variables are used in a method, they are its own local!! And when you exit a method, those variables get destroyed!
 
ansuman mohapatra
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it now..thanks for clearing.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic