Tuesday, October 25, 2005

Tips I

1. String literal are not garbage collected until that class is unloaded. (This is true for even the literals defined inside the methods)
but strings created unsing new String("some string"); are GCed.

2. Also Strings created by xyz.toString() etc are also candidates for GC

3. Drag and Drop questions in SCJP go reaset if u try to review them so.. pls keep them 4 last .. n answer them in one attempt.

4. nice example on string
String str1 = "Lions and Tigers and Bears!";
String str2 = "Lions and Tigers and Bears!";
String str3 = str2;
String str4 = new String("Lions and Tigers and Bears!");
String str5 = " Oh my!";
String str6 = "Lions and Tigers and Bears! Oh my!";
String str7 = str1 + str5;
String str8 = (str1 +" Oh my!").intern();

Comparison output:
str1 == str2 -> true // the str2 literal existed ("interned")
str1 == str3 -> true // hold the same reference
str1 == str4 -> false // str4 explicitly created
str2 == str3 -> true // hold the same reference
str2 == str4 -> false // str4 explicitly created
str3 == str4 -> false // str4 explicitly created
str6 == str7 -> false // str7 computed at runtime
str6 == str8 -> true // explicit use of intern() at runtim

Prtected methods and protected member variables:
Protected method is accessible to subclass to execute but protected member / constructor is not accessible from subclass (which is not in same package.)

No comments: