CSC300: Python to Java: Objects and equality [39/40] Previous pageContentsNext page

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
package algs11;
import stdlib.*;
import java.util.*;
public class Hello {
  public static void main (String[] args) {
    //Trace.showBuiltInObjects (true);
    //Trace.drawSteps ();
    //Trace.run ();
    Integer x = 3000;
    Integer y = 3000;
    StdOut.println ("x=" + x + ", y=" + y);
    StdOut.println ("                  x==y : " + (x == y));
    StdOut.println ("           x.equals(y) : " + (x.equals(y)));
    StdOut.println ("   Objects.equals(x,y) : " + (Objects.equals(x,y)));
  }
}

In Java, the == operator checks object identity on object types. That is, the two operands refer to the same object. More concretely: the two operands evaluate to the same address in memory.

Unlike other languages (such as C++) this behavior cannot be changed.

Objects all have an equals method. The behavior of equals varies from class to class. The default method, defined in java.lang.Object, tests identity, just like ==. Many of java's builtin classes override this default behavior to check value equality rather than object identity.

The java.util.Objects class provides some handy utilities, like Objects.equals. You can see the code here

Try some variations on java.lang.Integer

Try java.lang.Object

Try java.lang.String

Try arrays, with utility functions in java.util.Arrays

Previous pageContentsNext page