String Vs. StringBuffer

G

gaurav v bagga

hi,

method(){
String a="";
String c="";
}


method(){
StringBuffer a=new StringBuffer();
StringBuffer c=new StringBuffer();;
}

will String a,c get garbage collected after method
what about StringBuffer ?

regards
gaurav
 
A

Abhi

gaurav said:
hi,

method(){
String a="";
String c="";
}


method(){
StringBuffer a=new StringBuffer();
StringBuffer c=new StringBuffer();;
}

will String a,c get garbage collected after method
what about StringBuffer ?

regards
gaurav

Gaurav u cannt access String a,c after method 1 as their scope is
limited to that method only.as for garbage collectn u dont hav to
worry.it runs periodically so u cannt say xactly when they will be
garbaged.

Regards........
 
C

Chris Dollin

gaurav v bagga wrote:

(call this method A)
method(){
String a="";
String c="";
}

(call this method B)
method(){
StringBuffer a=new StringBuffer();
StringBuffer c=new StringBuffer();;
}

will String a,c get garbage collected after method
what about StringBuffer ?

When (A) has finished, the variables `a` and `b` vanish.
The variables are not garbage collected, but their values
might be. However, "" is a string literal, hence interned,
hence it doesn't go away until the JVM finishes.

When (B) finishes, it's `a` and `b` vanish and their values
become eligible for garbage collection. Since there are no
other references to these StringBuffers, eventually (perhaps
for very small values of "eventually", perhaps for large ones)
they will be reclaimed.

If, in (A), you had say written

String a = new String( "" );

then you would have made a /copy/ of the empty string, and once
this (A) finished, that copy can be reclaimed. (Off-hand I can't
remember whether the copy has a copy of the underlying char[].)
 
A

Alex Hunsley

Abhi said:
Gaurav u cannt access String a,c after method 1 as their scope is
limited to that method only.as for garbage collectn u dont hav to
worry.it runs periodically so u cannt say xactly when they will be
garbaged.

You what?
 
A

Adam Maass

Chris Dollin said:
String a = new String( "" );

then you would have made a /copy/ of the empty string, and once
this (A) finished, that copy can be reclaimed. (Off-hand I can't
remember whether the copy has a copy of the underlying char[].)

One of the uses of the String(String) constructor is that it constructs a
brand-new non-shared char[] just large enough to hold the characters
comprising the String. It's an implementation detail, but important enough
that it is worth remembering.

-- Adam Maass
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top