Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String Buffer" Watch "String Buffer" New topic

String Buffer

sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
Posts: 71

Output: String Buffer

Output:String BufferAdded

What is the effect of " sb = new StringBuffer("Hai");"?
As the output differs in the two code above.

Ravikanth kolli
Ranch Hand

Joined: Feb 10, 2008
Posts: 179

public static void method(StringBuffer sb){
creates a new sb reference variable and it refers to the object from main. When a new assignment is made in the next line, a new string buffer object is created and is assigned to sb. Thus anymore changes done to sb are done on the new object rather than the one in main.

In the second case, you are first appending the stringbuffer with a value, so here the stringbuffer object from main is changed first. sb then references to another object created by new.

We can always think of object references are passed by reference while variables are passed by value (though it is specified that arguments are just passed by value in java). Since any changes made to the variables in methods are not reflected in the actual values, while the changes made to the objects are reflected.

sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
Posts: 71
Thanks Ravikanth.
I got it .
[ March 04, 2008: Message edited by: sandhi mridul ]

Joined: Jan 24, 2008
Posts: 26
class Test{ 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); }}

Answer:String Buffer

we can apply the any operations in the method.that operations are valied only that method.not outside.This is the main point.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: String Buffer
It's not a secret anymore!