Hey, I think the out put is not very straight forward coz both "string" and "string" are 2 diff objects on a first look but d thing is dat java handles string objects (in d string pool) in such a way dat, if gc is not been run, den it makes d 2 diff reference refer to same object, when de wanna contain d same string value. So wat u get at last is dat both d references point to d same object, i.e. d bit patterns stored in both references is d same and hence u get d result. I hope diz answers ur question. Thank you. Bye. Kind regards, Anish Doshi.
This is a perfectly valid question. The Java programming language is specifically designed so that string literals such as this are always equal. It accomplishes this by "interning" the string during class loading in a pool of unique strings maintained by the String class. If the string already exists, the intern() method in the String class returns a reference to the existing object, else it adds the string to the pool. The two subjects you must study to fully understand this subject is the interning of strings and the definition of "computed strings". Computed strings (e.g. a string returned from a method), unlike string literals, are not automatically added to the pool of unique strings. They can, however, be added to the pool by invoking the intern() method yourself.
Download a copy of <a href="http://www.javarules.com" target="_blank" rel="nofollow"><i>"Mastering The Fundamentals of The Java Programming Language"</i></a>
hi when 2 string literals are created they denote the same object.this is the same as String s = "rajeev"; String s1 = "rajeev"; s == s1 ; // true But when u create an object of String then both of them doesnot denote the same object String s = new String("rajeev"); String s1 = new String("rajeev"); s == s1 ; // false but s.equals(s1) ; // true coz they check the values hope this solves the problem
Rajeev Sachdev<br />(Sun Certified Java Programmer 1.4)<p>"Research is to see what everyone sees and thinking what no one has thought of"
Joined: Aug 03, 2003
I thought the String(String original) constructor would come up in response to this post. It is the "copy constructor" for the String class, and is specifically designed to return a different object than the one passed. Here are the API docs: Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.