wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer Doubt 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 "StringBuffer Doubt" Watch "StringBuffer Doubt" New topic
Author

StringBuffer Doubt

Chinmay Kant
Greenhorn

Joined: Feb 04, 2008
Posts: 20
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


Thanks and Regards,
Chinmay
Rohit Garg
Ranch Hand

Joined: Feb 05, 2008
Posts: 30
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.


Regards,
Rohit.
ansuman mohapatra
Greenhorn

Joined: Mar 04, 2008
Posts: 27
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".


Cleared SCJP.....
Nadeem Khan
Ranch Hand

Joined: Nov 27, 2007
Posts: 108
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!


<i>If there were no Exceptions (not Errors!), Life would have kinda sucked!!</i>
ansuman mohapatra
Greenhorn

Joined: Mar 04, 2008
Posts: 27
got it now..thanks for clearing.
 
 
subject: StringBuffer Doubt