Garbage Collection for String Class in Java -


in code have declared initialized string variable , printed hashcode, reinitialized value , invoked garbage collector clear dereferenced objects.

but when reinitialize string variable original value , print hashcode, same hashcode getting printed. how?

public class testgarbage1 {      public static void main(string args[]) {          string m = "java";            system.out.println(m.hashcode());                  m = "java";         system.gc();         system.out.println(m.hashcode());         m = "java";         system.out.println(m.hashcode());     } } 

hash code relates object equality, not identity.

a.equals(b) implies a.hashcode() == b.hashcode() 

(provided 2 methods have been implemented consistently)

even if gc taking place here (and weren't referencing strings in constant pool), wouldn't expect 2 string instances same sequence of chars not equal - hence, hash codes same.

string = new string("whatever"); string b = new string(a); system.out.println(a == b); // false, not same instance system.out.println(a.equals(b)); // true, represent same string system.out.println(a.hashcode() == b.hashcode()); // true, represent same string 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

post - imageshack API cURL -

dataset - MPAndroidchart returning no chart Data available -