if (s instanceof String) {
if (s == "a string");
if (s.equals("a string"));
}
what is the difference between s.equals and s == ???
When I use s == "something", many times if s == "something", returns false!
Instead s.equals works correct always.
Is there something that I dont know?
If you've ever worked with C or C++, it might actually be easier to
think of this in terms of pointers. Though Java doesn't have pointer
arithmetic, you can think of an object, such as the String s, as a
variable name (in this case s) pointing to the actual object. So, if
you compare two Strings as follows:
String s1 = new String("foo");
String s2 = new String("foo");
if(s1==s2)
System.out.println("equal");
else
System.out.println("not equal");
"not equal" will be the output, because s1 and s2 are not equal: they
point to different String objects.
If, however, you change it to:
String s1 = new String("foo");
String s2 = new String("foo");
if(s1.equals(s2))
System.out.println("equal");
else
System.out.println("not equal");
you'll get the expected output ("equal"), because the equals method is
overloaded to do a lexical comparison on the two String objects (in the
case of the String class, other objects can have their equals method
overloaded to do the appropriate comparison).
Often you'll want to overload the equals method for classes of your own
when you want to compare them to determine whether two objects should be
considered to have equal value regardless of whether they are in fact
pointing to the same instance. E.g., if you have a class with two
fields, and instances of that class can be considered equal when the
first field in the first object is the same as the first field in the
second object, and the second field in the first object is the same as
the second field in the second object, you'd override the equals method
to check for that condition and then return true if and only if that is
the case.
Hope that helps. I know it could be a somewhat confusing explanation
since it's often said that Java doesn't use pointers (and it's true that
it doesn't do pointer arithmetic at all). But it is often useful to
think of an object variable as a pointer to the object in memory (you
even have to use "new" to allocate the object; you can't just declare an
object on the stack the way you can a primitive such as int), even if
only for semantic purposes when thinking about the way the program will
work.