String.Equals Versus ==

String.equals versus ==

Use the string.equals(Object other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

if (usuario.equals(datos[0])) {
...
}

NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.

What is the difference between == and equals() in Java?

In general, the answer to your question is "yes", but...

  • .equals(...) will only compare what it is written to compare, no more, no less.
  • If a class does not override the equals method, then it defaults to the equals(Object o) method of the closest parent class that has overridden this method.
  • If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the Object#equals(Object o) method. Per the Object API this is the same as ==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality.
  • Always remember to override hashCode if you override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.

Which one is better string.Equals() or == , in case of checking the equality of two strings in c#?

I would suggest string.Equals as equality(==) operator internally use string.Equals first check for references equality and then for value equality, hence it would be better to use string.Equals than == in case of string variables.

String.Equals vs String.Compare vs == in Action. Explanation needed

Why does the first comparison (string.compare) work and the other two
comparison methods does not work in THIS PARTICULAR CASE

There are invisible characters (particularly, a Left-to-Right mark (Thanks @MatthewWatson)) in your code. You can view them with any hex editor:

Sample Image

This is over-looked by string.Compare, while it isn't with string.Equals. You can see it in the docs:

Notes to Callers:

Character sets include ignorable characters. The
Compare(String, String) method does not consider such characters when
it performs a culture-sensitive comparison.
For example, if the
following code is run on the .NET Framework 4 or later, a
culture-sensitive comparison of "animal" with "ani-mal" (using a soft
hyphen, or U+00AD) indicates that the two strings are equivalent.

How do I compare strings in Java?

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for null before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

// These two have the same value
new String("test").equals("test") // --> true

// ... but they are not the same object
new String("test") == "test" // --> false

// ... neither are these
new String("test") == new String("test") // --> false

// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true

You almost always want to use Objects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

From JLS 3.10.5. String Literals:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Similar examples can also be found in JLS 3.10.5-1.

Other Methods To Consider

String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.

String.contentEquals() compares the content of the String with the content of any CharSequence (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.

Java, what's the difference between == and equals

Yes, == with objects is a reference comparison* (checks if the operands are references to the same object), while equals is whatever the class involved defines it to mean (within the requirements documented for equals). Some classes define equals as being the same as ==, including Java's arrays. (Because they don't override the default implementation from Object.equals, which uses ==.)

If you want to compare Java arrays based on the equality of their contents, you use Arrays.equals instead.

Your experiment would have worked if you used a class that defined equals in a useful way, you were just unlucky picking arrays. It's a bit tricky to find a class in the JVM to use for this experiment, because so many either don't implement equals (like arrays) or could be confusing because there are several immutable classes which may reuse instances (although not if you explicitly use new; but I don't want to go down a path of having you use new with something you probably shouldn't, like String; more on that here). I'm going to give up on picking a good example and use the slightly old class SimpleDateFormat:

DateFormat a = new SimpleDateFormat("yyyy-MM-dd");
DateFormat b = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");

That outputs


== Different
equals Same

because SimpleDateFormat defines equals to check that the other object is also a SimpleDateFormat with the same formatting.

Live example


Re your comment on the question:

I have someone the answer points but I only get the == part, if .equals is checking the content, how come the code didnt print "same" for the second if

Because equals doesn't, necessarily, check content. It only does if a class overrides the default Object.equals (which just uses ==) and implements a content check. Arrays don't. (One could argue that they should have, but they don't.) Other classes, like SimpleDateFormat and String and Integer and HashMap do.

In essence: == is always a reference comparison. equals may or may not be a contents comparison, depending on what class you're using it on.

So for instance, say we have this class:

class Example1
{
private int content;

Example1(int content) {
this.content = content;
}

public static void main (String[] args) throws java.lang.Exception
{
Example1 a = new Example1(42);
Example1 b = new Example1(42);
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");
}
}

Since that class doesn't override equals, you'll get the same answer ("Different") for both == and equals. Live Example.

But if we override equals to define what it would mean for two instances to be equal (in this case: because they have the same content):

class Example2
{
private int content;

Example2(int content) {
this.content = content;
}

@Override
public boolean equals(Object obj) {
if (obj == null || !obj.getClass().equals(this.getClass())) {
return false;
}
Example2 other = (Example2)obj;
return this.content == other.content;
}

@Override
public int hashCode() {
return this.content;
}

public static void main (String[] args) throws java.lang.Exception
{
Example2 a = new Example2(42);
Example2 b = new Example2(42);
System.out.println(a == b ? "== Same" : "== Different");
System.out.println(a.equals(b) ? "equals Same" : "equals Different");
}
}

Now equals says two instances with the same content are the same, because the class defines what that means. Live Example. (Also note that when overriding equals, you must override hashCode, which is why I've done so above.)


* More generally, == tests if the values of its operands are the same. The value in the case of reference types is an object reference, and two object reference values are only the same when they refer to the same object are are only different when they refer to different objects (or one of them is null; not referring to an object at all).

Strings in Java : equals vs ==

First of all String.toString is a no-op:

/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}

Second of all, String constants are interned so s1 and s2 are behind the scenes changed to be the same String instance.

==' vs string.equals c# .net

string == string is entirely the same as String.Equals. This is the exact code (from Reflector):

public static bool operator ==(string a, string b)
{
return Equals(a, b); // Is String.Equals as this method is inside String
}

Using == or Equals for string comparison

I wouldn't use:

aa.Equals(bb)

unless I knew aa couldn't possibly be null. I might use:

string.Equals(aa,bb)

But I'd mainly use that it I wanted to use one of the specific StringComparison modes (invariant, ordinal, case-insensitive, etc). Although I might also use the StringComparer implementations, since they are a bit easier to abstract (for example, to pass into a Dictionary<string, Foo> for a case-insensitive ordinal dictionary). For general purpose usage,

a == b

is fine.



Related Topics



Leave a reply



Submit