Created
March 6, 2012 01:40
-
-
Save programus/1982784 to your computer and use it in GitHub Desktop.
String initialization in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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