Core Classes
Object
-
Superclass of all Java™ classes.
-
Common methods to be redefined by derived classes.
Implementation of java.lang.String
:
public final class String ... {
private final char value[];
private int hash;
private static final long serialVersionUID = -6849794470754667710L;
...
}
Code | Output |
---|---|
|
sCopy == s: false ❸ sCopy.equals(s): true ❹ |
Primitive type | Object |
---|---|
|
|
==: true |
==: false equals: true |
-
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.
-
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); System.out.println("equals: " + s.equals(copy)); System.out.println(" ==: " + (s == copy));
equals: true ==: false
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);
}