5

I observed a strange behavior == operator in java. I am trying to print the out put as follows

String str1 = "Rajesh";
String str2 = "Rajesh";
System.out.println("Using equals() str1 and str2 Equals :"
            + str1.equals(str2));
System.out.println("Using == str1 and str2 Equals :" 
            + str1 == str2);

The first SOP statement printing

Using equals() str1 and str2 Equals :true

and the next SOP printing only false .

I tried compiling in both eclipse and Net Beans but result is the same . I am so confused why

Using == str1 and str2 Equals :

is not printing

Help me out in this

Thanks in advance,

Raj

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Raj
  • 2,463
  • 10
  • 36
  • 52
  • Did you try encapsulating the condition in parenthesis? It's possible the first condition is added to your string then evaluated with str2. – Josh Feb 09 '12 at 06:17
  • 2
    `"Using == str1 and str2 Equals :" + str1 == str2` will be the equivalent of `"Using == str1 and str2 Equals :" + "Rajesh" == "Rajesh"`. Because `+` has a higher precedence than `==` (`2 + 2 == 4`), we'll have the equivalent of `"Using == str1 and str2 Equals :Rajesh" == "Rajesh"`, which will be `false`. – Tom Hawtin - tackline Feb 09 '12 at 06:20
  • 1
    possible duplicate of [Java String.equals versus ==](http://stackoverflow.com/questions/767372/java-string-equals-versus) – Michael Petrotta Feb 09 '12 at 06:21
  • @Josh reat comment thanks you so munch – Raj Feb 09 '12 at 06:22
  • When you don't use any parentheses, the `==` operator is evaluated last. – Sam Dufel Feb 09 '12 at 06:22

10 Answers10

12

it's the same as ("Using == str1 and str2 Equals :" + str1) == str2 and this is false, of course. Expression is parsed from left to right and so at first it concatenates "Using == str1 and str2 Equals :" and str1, then applies == operator.

shift66
  • 11,760
  • 13
  • 50
  • 83
7

See http://bmanolov.free.fr/javaoperators.php for a table of operator precedence in Java.

The + operator is higher precedence than the == operator.

So, in effect, your code is equivalent to the following:

System.out.println( ("Using == str1 and str2 Equals :" + str1) == str2);

Note the placement of the parentheses that I added. It evaluates to this:

System.out.println( (str_x + str1) == str2);

And then to this:

System.out.println( str_y == str2 );

And then to this:

System.out.println( false );

In order to get the result you want, you must use parentheses to specify that you want the == operator to be resolved BEFORE the + operator:

System.out.println( "Using == str1 and str2 Equals :" + (str1 == str2));

Notice the new placement of the parentheses.

Aaron Johnson
  • 795
  • 1
  • 8
  • 16
4

Because + has higher priority compare to = and if you use bracket(str1 == str2) then this result give true because highest priority is (. So First it checks bracket inside data.

String str1 = "Rajesh";
        String str2 = "Rajesh";
        System.out.println("Using equals() str1 and str2 Equals :"
                + str1.equals(str2));
        System.out.println("Using == str1 and str2 Equals :" 
                + (str1 == str2));

Output:

Using equals() str1 and str2 Equals :true
Using == str1 and str2 Equals :true
Suresh
  • 1,494
  • 3
  • 13
  • 14
2

Maybe an order of operations thing? Try:

System.out.println("Using == str1 and str2 Equals :" + (str1 == str2));
Oleksi
  • 12,947
  • 4
  • 56
  • 80
2

Try surrounding it with () like this:

System.out.println("Using == str1 and str2 Equals :" + (str1 == str2));
Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73
0

equals method returns true if and only if x and y refer to the same object.Follwoing is the Object class implementation of equals method.

public boolean equals(Object obj) {
    return (this == obj);
    }

In String class this method has overridden as following.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    } 

And if you use == operator it just check both references are having same object. Similar to the Object class equals method.

Eshan Sudharaka
  • 607
  • 2
  • 9
  • 16
-1

The reason is that you cannot compare strings in Java using ==.

In C++ or C# (or other languages supporting operator redefinition), you can overwrite the == operator to provide that functionality. Java does not support that.

Abrixas2
  • 3,207
  • 1
  • 20
  • 22
  • 1
    You mean overload, not overwrite (or override). And yes, you *can* compare string references using `==` in Java. It will compare the references, not the objects, but that would work fine in this particular case, if it had been used correctly. – Jon Skeet Feb 09 '12 at 06:25
  • Yes, I meant overload. And thanks for pointing on that reference thing. I just did not know that. – Abrixas2 Feb 09 '12 at 06:28
-1

str1.equals(str2) returns true because the equals() function compares the content of the string variables, where as == operator compares the instances. Since str1 and str2 are two differences of instances of String class, it returns false

Sunil Kumar B M
  • 2,735
  • 1
  • 24
  • 31
  • 2
    Here, `str1` and `str2` will be identical references to the same string though, due to the way the language handles compile-time string constants. – Jon Skeet Feb 09 '12 at 06:33
-1

In Java == operator matches the two objects i.e their address while .equals() method mathces the values of both objects, thats why you are getting true for equals() and false for == as both are different objects.

Kamran Ali
  • 5,904
  • 2
  • 26
  • 36
-2

== can only be used to compare primitive datatypes. To compare objects you need to use equals method. Using a == operator on objects actually compares there addresses instead of values.

Husain Basrawala
  • 1,757
  • 15
  • 21
  • 2
    Well, it compares the values - but those values are references. It's incorrect to say that `==` *can only be used to compare primitive datatypes* when it can also be used to test for reference equality. In this case, as we're dealing with two occurrences of the same string constant, `==` would work fine - if it were being used correctly. – Jon Skeet Feb 09 '12 at 06:23
  • Bearing in mind that the vast majority of objects out there do not override equals and simply return the result of ==. It's a fairly common mistake I see for people to just assume "I used .equals so this will work right." – Affe Feb 09 '12 at 06:23