Hi all,
I will try my best to clear your all doubts...there are 3-4 questions here :
1) What Paul said is correct: Every object has its unique address (hashcodes) on heap
So String str1 = "java"; and String str3 = "ranch"; will have different addresses hence hashcodes on heap.
and we need something to reach objects on heap and that something is refrence variable of the class ( or of its super class) of which object we are trying to reach. Now we can have many refrence variables with different names but refrering to same object on heap.So
String str1 = "java";
String str2 = "java";
Both str1 and str2 are refering to same object on heap which is "java" .
Now the question is why no two different objects were created above ?
Because of m/m saving purposes , JVM maintains a pool of constant strings and wheneevr encounters any new refrence for these strings , just point them to alraedy existing constant strings in pool , now suppose if you write further
String str7 = "java"; , it will also refer to same object..
one more trick to remeber is this : whenevr you see object is being created thru new keyword that means new object will be creted as below :
String str1 = new String("java");
String str2 = new String("java");
Now strings str1 and str2 will have different addresses on heap and hence hashcodes...
2) About == : It returns true if two objects have same address..same expalination as above.
3)About Sheetal's doubt : Object creation is done at run-time , so everytime you run the program you will get different hash-code , depending on m/m on heap available and also on JVM mood
Hope this makes clear....
Thanku..
Vishal