Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created June 22, 2019 14:35
Show Gist options
  • Save Audhil/14dfccb866c6d02e1bf8fdecd253da1a to your computer and use it in GitHub Desktop.
Save Audhil/14dfccb866c6d02e1bf8fdecd253da1a to your computer and use it in GitHub Desktop.
String is immutable - practical check-up
String t = "foo"; // newer obj created and added string pool
System.out.println("hashCode of t: " + t.hashCode());
t = "foo"; // shares the same memory location - same hashCode()
System.out.println("hashCode of 2 t: " + t.hashCode());
t = "fuc"; // newer value added - newer obj created and added string pool - different hashCode()
System.out.println("hashCode of 3 t: " + t.hashCode());
t = new String("foo"); // shares the same memory location - same hashCode()
System.out.println("hashCode of 4 t: " + t.hashCode());
t = new StringBuilder("foo").toString(); // shares the same memory location - same hashCode()
System.out.println("hashCode of 5 t: " + t.hashCode());
// o/p is
hashCode of t: 101574
hashCode of 2 t: 101574
hashCode of 3 t: 101748
hashCode of 4 t: 101574
hashCode of 5 t: 101574
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment