Java Object Class in the java.lang Package
The Object class is the top-level class in Java programs.
Main Object Methods
| Method | Description |
|---|---|
Object clone() |
A method used to clone an object. |
boolean equals(Object object) |
Compares whether two objects are equal and returns true if they are equal, otherwise false. |
void finalize() |
Called before garbage collection is performed and used to release resources occupied by the object. |
Class getClass() |
Returns the class name of the object as a Class object. |
int hashCode() |
Gets the hash code associated with the called object. |
String toString() |
Returns the string representation of the current object. |
void notify() |
Restarts one of the waiting threads. |
void notifyAll() |
Restarts all waiting threads. |
void wait() |
Stops execution and enters the waiting state. |
void wait(long timeout) |
Makes the current thread wait until the specified time has elapsed. |
void wait(long timeout, int nanos) |
Makes the current thread wait until another thread calls notify() or notifyAll() on this object, another thread interrupts the current thread, or the specified amount of real time has elapsed. |
The equals() method compares the data held by two objects and returns true if they are the same, otherwise false.
The toString() method is used to return the string representation held by an object. Most classes override the toString() method to provide object information as a string.
Object Example
Overriding the toString() Method
The example below overrides the object’s toString() method.
package com.devkuma.tutorial.java.lang;
public class User {
private Integer id;
private String name;
private String email;
public User(Integer id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String toString() {
return "id:" + id + ", name=" + name + ", email=" + email;
}
public static void main(String[] args) {
User user = new User(1, "devkuma", "devkuma.com@gmail.com");
System.out.println(user.toString());
}
}
Execution result:
id:1, name=devkuma, email=devkuma.com@gmail.com