Thank you for pointing to this. It can be really helpful - even if I quite don't like the first line for == and objects: "Compares references, not values." (in bold!). Hm... == compares values here, too. The values of the two references. (And next in this cinema: Does Java "call by value" or "call by reference, sometimes" ).

Hauke Ingmar Schmidt
Rancher

Joined: Nov 18, 2008
Posts: 433

2

posted Sep 14, 2010 03:47:35

0

Ramakrishna wrote:What does the == operator do?
== operator compares two references of a string.

Generally speaking, it compares two primitive values. If the type is int, the primitive value itself represents the value, so it this is the same as a comparision of the contents (i.e 4==5 is a comparision of primitive types).

When used with objects it is like the identity operator. When used with reference variables it checks if both point to the same object (i.e. "object at heap position 4"=="object at heap position 5").

What is a String? Where in memory does it live?
String is a set/combinations of characters.

String s; s="ab"; //this will store in stack
String s= new String("ab"); //this will store in heap
.............
this is my expectation
.................

String s="ab"; could be seen just a shortcut for s=new String("ab"); Strings are often used, so they have some extra syntax, that other objects don't have. You can add two String objects with +. That is operator overloading, not possible for other objects.

And now the catch: s="ab" does a little more magic than only replace it with s=new String("ab"), which is where you problems occur.

What do you want to do with the two Strings?
just i want to compare two strings.

You want to compare the content. You don't want to check the identity. And as we saw == used on Objects is the identity operator. Strings are always Objects.

my doubt is
String s6 = "change ";
String s7 = s6+"me";
s4==s7
should be true....
but it is getting false....what would be the reason.......

And this is where the magic I mentioned before kicks in.

The Java virtual machine holds a cache for Strings. If you do a:

String a = "one";
String b = "one";

than there will be no object created for the second String. It will be reused from the cache. So a and b point to the same object, the identity operator seems to work.

"Ramakrishna" it is not possible to send you a private message to warn you about the naming policy, but you are still in violation of it.
Correct your displayed name to match the policy, or we shall withdraw your privilege of using this website.

sorry for voilating rules.
could you please explain the naming policy rules....

Campbell Ritchie wrote:"Ramakrishna" it is not possible to send you a private message to warn you about the naming policy, but you are still in violation of it.
Correct your displayed name to match the policy, or we shall withdraw your privilege of using this website.