Core Classes

Related slides on offer

Figure 462. Openjdk source code repository Slide presentation

Figure 463. Superclass Object Slide presentation
  • Superclass of all Java™ classes.

  • Common methods to be redefined by derived classes.


Figure 464. String literals Slide presentation

Figure 465. OpenJDK String implementation Slide presentation

Implementation of java.lang.String:

public final class String ... {
  private final char value[];
  private int hash;
  private static final long serialVersionUID = -6849794470754667710L;
...
}

Figure 466. String copy constructor Slide presentation
Code Output
final String s = "Eve"; ❶
final String sCopy = new String(s); ❷
IO.println("sCopy == s: " + (sCopy == s)); ❸
IO.println("sCopy.equals(s): " + sCopy.equals(s)); ❹
sCopy == s: false ❸
sCopy.equals(s): true ❹

❶

The string literal "Eve" corresponds to an instance of String. Its reference is being assigned to variable s.

❷

A clone carrying the same value "Eve" is being created by virtue of the String class copy constructor.

❸

We indeed have two distinct objects.

❹

Both String objects however carry the same value.


Figure 467. Copy constructor and heap Slide presentation

Figure 468. Operator == and equals() Slide presentation
Primitive type Object
// equal values
int a = 12, b = 12;

IO.println(
    "==: " + (a == b));
// No equals(...) method
// for primitive types
String 
 s1 = new String("Kate"),
 s2 = new String("Kate");

IO.println(
  "    ==: " + (s1 == s2));
IO.println(
  "equals: " + s1.equals(s2));
==: true
    ==: false
equals: true

Figure 469. Remarks == vs. equals() Slide presentation
  • The == operator acting on primitive types compares expression values.

  • The == operator acting on objects compares for equality of reference values and thus for object identity.

  • The == operator acting on objects does not check whether two objects carry semantically equal values.

  • The equals() method defines the equality two objects.


Figure 470. Operator == and equals() implications Slide presentation
  • Each object is equal by value to itself:

    object1 == object2 ⇒ object1.equals(object2)

  • The converse is not true. Two different objects may be of common value:

    Code Result
    String s = "Hello", copy = new String(s);
    
    IO.println("equals: " + s.equals(copy));
    IO.println("    ==: " + (s == copy));
    equals: true
        ==: false

Figure 471. equals() is being defined within respective class! Slide presentation

Implementation at https://github.com/openjdk/ .../String.java :

public final class String ... {
public boolean equals(Object anObject) {
  if (this == anObject) {
    return true;
  }
  return (anObject instanceof String aString)
    && (!COMPACT_STRINGS || this.coder == aString.coder)
    && StringLatin1.equals(value, aString.value);
}