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

Doubt in Strings

gobburi saikrishna
Ranch Hand

Joined: Jan 21, 2008
Posts: 52
Hello ranchers

The question below is from Java Beats mock exam

public class Test16{
public static void method(StringBuffer sb){
sb = new StringBuffer("Hai");
sb.append(" Added");
public static void main(String a[]){
StringBuffer sb = new StringBuffer("String Buffer");
1) String Buffer
2) String Buffer Added
3) Hai
4) Compiler Error

Answer for the above question is String Buffer, my doubt is why its not String Buffer Added, please Help me to understand this question.

Thanks In Advance
Nadeem Khan
Ranch Hand

Joined: Nov 27, 2007
Posts: 108
Because in this case both method() and main()have their own "sb". When you call method, its own "sb" is created and when method returns to main(), its local variables get destroyed!! Hence when you are accessing in main(), its referring to main()'s local "sb"!!

<i>If there were no Exceptions (not Errors!), Life would have kinda sucked!!</i>
gobburi saikrishna
Ranch Hand

Joined: Jan 21, 2008
Posts: 52
thanks Nadeem
Sowjanya Choudhary

Joined: Feb 22, 2008
Posts: 1
To my knowledge,
'sb' in method() and main() points to the same object, when 'sb' is passed to method().
But in line, sb = new StringBuffer("Hai");
you are creating new object for 'sb' and assigning it to that. So the changes made to 'sb' in method() doesn't reflect for 'sb' in main().

However, if you comment that line and run the code you will get "String Buffer Added". because , even in method() you modify the same object using other reference.
gobburi saikrishna
Ranch Hand

Joined: Jan 21, 2008
Posts: 52
Thanks Sowjanya,
your right, i have compiled and checked.

thanks a lot
Consider Paul's rocket mass heater.
subject: Doubt in Strings
It's not a secret anymore!