Core Classes

Related slides on offer

Figure 412. Openjdk source code repository Slide presentation

Figure 413. Java Visualizer Slide presentation

Figure 414. Superclass Object Slide presentation
  • Superclass of all Java classes.

  • Common methods to be redefined by derived classes.


Figure 415. String literals Slide presentation

Figure 416. 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 417. String copy constructor Slide presentation
Code Output
final String s = "Eve"; 
final String sCopy = new String(s); 
System.out.println("sCopy == s: " + (sCopy == s)); 
System.out.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 418. Copy constructor and heap Slide presentation

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

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

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

Figure 420. 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 421. Operator == and equals() implications Slide presentation
  • Each object is equal by value to itself:

    object1 == object2object1.equals(object2)

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

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

Figure 422. 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);
}