wood burning stoves 2.0*
The moose likes Java in General and the fly likes string declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "string declaration" Watch "string declaration" New topic
Author

string declaration

Gajendra Kangokar
Ranch Hand

Joined: Dec 25, 2012
Posts: 65


what is the difference in s2 and s3 declaration?
here hashcode value of s1,s2,s3 is same.
but s1==s2 returns true and
s1==s3 returns false
does hashcode value play any role in the object identity check?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4240
    
    7

Gajendra Kangokar wrote:does hashcode value play any role in the object identity check?


No. It shouldn't even play a role in an equals() check, although it should be consistent with that.

As you've seen, s3 forces the creation of a new String, whereas s2 allows the reuse of an existing String as an optimisation. The other important difference is that there's never any reason to use the s3 style.
Tim Cooke
Rancher

Joined: Mar 28, 2008
Posts: 526
    
  23

There was a pretty detailed discussion on the topic of String comparisons last week
http://www.coderanch.com/t/614460/java/java/string-comparision


Tim Driven Development
Gajendra Kangokar
Ranch Hand

Joined: Dec 25, 2012
Posts: 65

what is the actual use of hashcode..?
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3054
    
  33

Gajendra Kangokar wrote:what is the actual use of hashcode..?

The documentation of hashCode method in Object class says:

This method is supported for the benefit of hash tables such as those provided by {@link java.util.HashMap}


which indicates that the hashMap is used in whenever some object is used as a key in the Map.


Mohamed Sanaulla | My Blog
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3054
    
  33

And if two objects have equal hasCode doesn't indicate that the two objects are equal. One can always override hasCode() method to return constant value for any object of a given class something like:
drac yang
Ranch Hand

Joined: Apr 19, 2013
Posts: 60
in String's overridden hashCode and equals method, actually i didn't find direct relation between hashCode and equals, they seem to be independent with each other.



but they two do have relations in String class, that is the content of the string, i.e. the internal char array. only if every chars are same, they would have same hashCode and true equality.

and generally, for Object, only if the two objects have same hashCode, could they equal.


science belief, great bioscience!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string declaration
 
Similar Threads
==, why is it so ?
Doubt in Strings
this keyword usage
Why String Constructor exists in the API
Using the String