For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
The Object class is a fundamental part of the Java programming language. It serves as the root class for all other classes in Java. Whether you create a custom class or use built-in Java classes, they all implicitly extend the Object class. Understanding the methods of the Object class is crucial because they provide essential functionalities that are used in everyday Java programming.
Enhance your Java skills with expert-led training. Check out upGrad’s Software Engineering course and learn how to apply Java in real-world projects.
The Object class is a part of java.lang package, and it is the superclass of all classes in Java programming language. This means that every class in Java, either directly or indirectly, inherits the methods of the Object class.
Since every Java class is a descendant of the Object class, the methods defined in it are inherited by all classes. This makes the Object class the backbone of object management in Java. From comparing objects to managing memory and handling threads, the Object class offers core methods that every Java programmer must understand.
Modifier and Type | Method | Description |
public String | toString() | Returns a string representation of the object. Typically overridden for clarity. |
public int | hashCode() | Returns a hash code value for the object, used in hash-based collections. |
public boolean | equals(Object obj) | Compares this object to the specified object for logical equality. |
public final Class<?> | getClass() | Returns the runtime class of the object. |
protected void | finalize() | Called by the garbage collector before object is reclaimed. Used for cleanup. |
protected Object | clone() | Creates and returns a copy of the object. Requires implementation of Cloneable. |
public final void | wait() | Causes the current thread to wait until another thread invokes notify(). |
public final void | wait(long timeout) | Waits for the specified time in milliseconds. |
public final void | wait(long timeout, int nanos) | Waits for the specified time (in ms + ns). |
public final void | notify() | Wakes up a single thread waiting on this object’s monitor. |
public final void | notifyAll() | Wakes up all threads waiting on this object’s monitor. |
Java powers the backend. Generative AI drives the future. Equip yourself with leadership skills in AI through this executive programme.
The methods provided by the Object class in Java form the foundation of working with objects in Java programming. Let's explore the most commonly used object class methods:
The toString() method is used to convert an object into a string representation. Every class in Java inherits this method from the Object class, and it can be overridden to provide a more meaningful description of the object.
Example:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Janvi", 25);
System.out.println(p);
}
}
Output:
Person{name='Janvi', age=25}
Explanation: In the example above, the toString() method is overridden to provide a meaningful string representation of the Person object. By default, it returns the class name and the memory reference.
Already confident in Java? Level up with in-demand cloud and DevOps knowledge through upGrad’s Professional Certificate Program.
The hashCode() method returns a hash code for the object, which is used in hashing data structures like HashMap, HashSet, and Hashtable. The default implementation of hashCode() in the Object class typically returns the memory address of the object.
Example:
class Car {
String model;
int year;
Car(String model, int year) {
this.model = model;
this.year = year;
}
@Override
public int hashCode() {
return model.hashCode() + year;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Tesla", 2022);
System.out.println(car.hashCode());
}
}
Output:
1553668604
This example shows how the hashCode() method is used to return a unique identifier for each Car object, which is important for hash-based collections.
NOTE: Different outputs may appear on different systems due to variations in how String.hashCode() is internally calculated across JVM implementations or versions.
The equals() method compares the current object with another object for equality. By default, it checks for reference equality, but it can be overridden to check for logical equality between two objects (i.e., comparing the content).
Example:
class Book {
String title;
String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book book = (Book) obj;
return title.equals(book.title) && author.equals(book.author);
}
}
public class Main {
public static void main(String[] args) {
Book book1 = new Book("Java Basics", "John");
Book book2 = new Book("Java Basics", "John");
System.out.println(book1.equals(book2)); // true
}
}
Output:
true
In this example, the equals() method compares two Book objects by their title and author fields. If the fields match, it returns true.
The getClass() method returns the Class object that represents the runtime class of the object. This method is often used in reflection to dynamically obtain information about the object's class.
Example:
class Animal {}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
System.out.println(animal.getClass().getName());
}
}
Output:
Animal
This example demonstrates how to use the getClass() method to retrieve the class name of an object dynamically at runtime.
The finalize() method is called by the garbage collector before an object is destroyed. This method is useful for releasing system resources like file handles or database connections before an object is reclaimed by the garbage collector.
Example:
class Resource implements AutoCloseable {
public void doSomething() {
System.out.println("Using resource");
}
@Override
public void close() {
System.out.println("Resource closed");
}
}
public class Main {
public static void main(String[] args) {
try (Resource res = new Resource()) {
res.doSomething();
}
}
}
Output:
Using resource
Resource closed
Explanation:
In this code, the finalize() method is overridden to print a message before the object is garbage collected. However, since finalize() is deprecated, the compiler shows a warning. The output confirms successful execution but advises against using finalize().
The clone() method is used to create and return a copy of the object. By default, it performs a shallow copy, but you can override it to create a deep copy if needed.
Example:
class Laptop implements Cloneable {
String brand;
int year;
Laptop(String brand, int year) {
this.brand = brand;
this.year = year;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Laptop laptop1 = new Laptop("Dell", 2022);
Laptop laptop2 = (Laptop) laptop1.clone();
System.out.println(laptop1.brand + " " + laptop2.brand);
}
}
Output:
Dell Dell
Explanation:
In this example, the clone() method is overridden to provide a shallow copy of the Laptop object.
These methods are part of the Object class and are used for thread synchronization and communication. The wait() method causes the current thread to release the lock and enter a waiting state. The notify() and notifyAll() methods are used to wake up one or all threads that are waiting on the object.
Example:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
notify();
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
synchronized (counter) {
while (counter.getCount() < 5) {
try {
counter.wait();
} catch (InterruptedException e) {}
}
System.out.println("Count reached 5!");
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.increment();
System.out.println("Incremented count: " + counter.getCount());
}
});
t1.start();
t2.start();
}
}
Output:
Incremented count: 1
Incremented count: 2
Incremented count: 3
Incremented count: 4
Incremented count: 5
Count reached 5!
Explanation:
This example demonstrates how the wait(), notify(), and notifyAll() methods can be used for synchronizing threads.
The Object class in Java is integral to the Java language as it provides essential methods for object comparison, memory management, thread synchronization, and more. Understanding and overriding these methods in your custom classes can lead to more efficient and organized code. The methods like toString(), hashCode(), equals(), and clone() are frequently used across Java applications.
Mastering these methods not only helps with better object handling but also improves the overall performance and maintainability of Java programs. Whether you're debugging, implementing collections, or managing object states, the methods from the Object class are fundamental tools in your Java programming toolkit.
The Object class is the root of the Java class hierarchy. Every class in Java directly or indirectly inherits from it. It provides core methods like toString(), equals(), hashCode(), and others that enable fundamental object behavior such as comparison, representation, and synchronization.
Java follows a single-rooted inheritance model to ensure consistency. Making Object the superclass of all classes allows the JVM to treat every object uniformly, enabling features like polymorphism, collection handling, and method overriding with consistent default behavior.
Key methods include toString(), equals(), hashCode(), getClass(), clone(), finalize(), and synchronization-related methods like wait(), notify(), and notifyAll(). These methods help in object representation, identity, lifecycle management, and inter-thread communication.
Yes, most methods of the Object class can be overridden, such as toString(), equals(), and hashCode(), to provide class-specific behavior. However, methods like getClass() and wait() are final, so they cannot be overridden.
The toString() method returns a string representation of the object. By default, it returns the class name followed by the object's hash code. Overriding it helps display object content meaningfully, especially useful for debugging or logging.
The equals() method checks for logical equality (whether objects have the same value), while == checks for reference equality (whether both references point to the same object in memory). Overriding equals() allows comparing content meaningfully.
The hashCode() method returns an integer value, used in hashing-based collections like HashMap or HashSet. It works alongside equals() to identify object uniqueness. If two objects are equal, their hash codes must also be equal for correct collection behavior.
The finalize() method was used for cleanup before object destruction but is now deprecated due to unpredictability and performance issues. Modern Java recommends using try-with-resources or Cleaner for resource management instead of relying on finalize().
The getClass() method returns the runtime class of an object as a Class<?> instance. It helps in reflection, where you want to inspect or manipulate class metadata dynamically at runtime without knowing the class type beforehand.
The clone() method creates and returns a copy of the object. To use it, a class must implement the Cloneable interface. It performs a shallow copy by default and can be overridden for deep copying or custom behavior.
These methods are used for thread communication and synchronization. wait() pauses a thread until another thread invokes notify() or notifyAll() on the same object. They help manage multi-threaded scenarios where threads share resources and need coordination.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Disclaimer
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.