What happens after the following code is compiled/executed?

1.import static java.lang.System.*;
2.public class A {
3.    public static void main(String[] args){
4.        B b1 = new B("one","two");
5.        B b2 = new B("one", "two");
6.        B b3 = b1;
7.        out.println(b1 == b2);
8.        out.println(b1 == b3);
9.        out.println(b2 == b3);
10.       out.println(b1.equals(b2));
11.       out.println(b1.equals(b3));
12.       out.println(b3.equals(b2));
13.  }
14.}

class B {
    public B(String prop1, String prop2){
        this.prop1 = prop1;
        this.prop2 = prop2;
    }
    String prop1 = null;
    String prop2 = null;
}
Explanation
Operator == checks whether objects are located in the same memory. Therefore, lines 7 and 9 return false. Since b3 and b1 point to the same object, line 8 returns true.
Same checks are performed for lines 10, 11, and 12 since equals() method is not overridden in class B.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты