-4

As I know == basically compares memory location, So I totally understand that line 1 is returning true. But we have not overridden the equal method in class , then why line 2 is returning true?

private String category = "procedura1";
public static void main(String[] args) {
    Lang obj1 = new Lang();
    Lang obj2 = new Lang();
    if (obj1.category == obj2.category) {  ///  Line 1
        System.out.println("Equal");
    } else {
        System.out.println("Not equal");
    }
    if (obj1.category.equals(obj2.category)) {  /// Line 2
        System.out.println("Equal");
    } else {
        System.out.println("Not equal");
    }
}

And Why line 3 of following returning false?

    String a1 = new String("String 1");
    String a2 = new String("String 1");

    if (a1 == a2) {      // Line 3
        System.out.println("True");
    } else {
        System.out.println("False");

    }

    if (a1.equals(a2)) {
        System.out.println("True");
    } else {
        System.out.println("False");

    }
Robin Paul
  • 13
  • 3

4 Answers4

2

The category is of type String which uses the String equals() implementation.

nitishagar
  • 9,038
  • 3
  • 28
  • 40
0

This is because you're overlooking the custom object entirely and going to a field that has an equals method defined.

If you were doing something like this instead:

if(obj1.equals(obj2))

...you would have an issue if equals isn't defined on Lang. But, as we know, equals is indeed defined on String, so you would see it working just fine.

This is, of course assuming that category actually is String; I'm only inferring it for now.

Makoto
  • 104,088
  • 27
  • 192
  • 230
0

The value of the category field is a String literal, which is interned, so every instance's category refers to the same String object, hence they are equal according to ==.

The contract for equals() is that it return true when called on itself, and you can rely on classes from the JDK honouring this contract.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

It's true 'cause you're basically comparing the two thing properties.. That's equivalent to:

public static void main(String[] args) {
    String str1 = "procedura1";
    String str2 = "procedura1";

    if (str1.equals(str2)) {
        System.out.print("Both String objects represent the same sequence of characters");
    }
}

But if you may compare it this was:

public static void main(String[] args) {
    Lang obj1 = new Lang();
    Lang obj2 = new Lang();

    if (obj1.equals(obj2)) {
        System.out.println("Both Lang objects are equal.");
    }
}

You won't get any message.. hope this helps ;)

albi9
  • 13
  • 4