• Core Classes

    Working with class String.

    Pitfalls when using operator ==

    Using equals(...).

Java Visualizer

http://prog.mi.hdm-stuttgart.de/java_visualize

  • Superclass of all Java classes.

  • Common methods to be redefined by derived classes.

Image layer 1
Image layer 2
Image layer 3
Image layer 4

Implementation of java.lang.String:

public final class String ... {
  private final char value[];
  private int hash;
  private static final long serialVersionUID = -6849794470754667710L;
...
}
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 
Image layer 1
Image layer 2
Image layer 3
Image layer 4
Image layer 5
Image layer 6
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
  • 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 == 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

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);
}
  • Core Classes
    • ➟ Using class Math
Code Result Math notation
final double x = 90;
final double y = Math.sin(x);
System.out.println(y + " == sin(" + x + ")");
0.8939966636005579 == sin(90.0) 
y = sin ( x )
  1. Common pitfall using trigonometric functions
  2. Strings on CodingBat
  3. Masking strings
  4. Analyzing strings
  5. Pitfalls using ==: Equality of String instances
  6. Weird, weirder, weirdest!
  7. Analyzing file pathnames