Skip to content

Instantly share code, notes, and snippets.

@programus
Created March 6, 2012 01:40
Show Gist options
  • Save programus/1982784 to your computer and use it in GitHub Desktop.
Save programus/1982784 to your computer and use it in GitHub Desktop.
String initialization in Java
import java.lang.ref.WeakReference;
/**
* Class to research strings.
* constant string like "AAA" won't be reclaimed while instance created by new will.
* when you new a String by a constant string, there will be two memory field stored the same value.
* so initialize a String by constant String is recommended.
* @author Programus
*/
public class NewOrNot {
public static void main(String[] args) {
String a = "AAA";
String b = new String("AAA");
WeakReference wra = new WeakReference(a);
WeakReference wrb = new WeakReference(b);
a = null;
b = null;
System.gc();
System.out.println(wra.get());
System.out.println(wrb.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment