File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Strings

 
gobburi saikrishna
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
method(sb);
System.out.println(sb);
}
}
Answers
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
saikrishna
 
Nadeem Khan
Ranch Hand
Posts: 108
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"!!
 
gobburi saikrishna
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Nadeem
 
Sowjanya Choudhary
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sowjanya,
your right, i have compiled and checked.

thanks a lot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic