🚀 TechFlow Now

← Back to Resources

Java Object Methods

toString()

Returns a string representation of the object.

Object obj = new Object();
System.out.println(obj.toString());

equals(Object obj)

Compares this object to the specified object for equality.

String a = "Hello";
String b = "Hello";
System.out.println(a.equals(b)); // true

hashCode()

Returns the hash code value for the object.

String s = "Hello";
System.out.println(s.hashCode()); // e.g., 69609650

getClass()

Returns the runtime class of the object.

String s = "Hello";
System.out.println(s.getClass()); // class java.lang.String

clone()

Creates and returns a copy of this object.

class Person implements Cloneable {
  int age;
  public Person clone() throws CloneNotSupportedException {
    return (Person) super.clone();
  }
}

finalize()

Called by the garbage collector before object is destroyed.

@Override
protected void finalize() {
  System.out.println("Object is garbage collected");
}

wait(), notify(), notifyAll()

Used for thread synchronization on objects.

// wait(): pauses thread until notify()
// notify(): wakes up one waiting thread
// notifyAll(): wakes all waiting threads