CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > Object Class in Java – The Root of All Classes

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

Object Class in Java – The Root of All Classes

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 5 min read · 0 Comments
Share: in X

The Object class in Java is a fundamental class in the Java programming language. It is the superclass of all other classes, and provides methods for dealing with objects in a general way. In this blog post, we will discuss the important methods and use cases of the Object class in Java.

Table of Contents

  • The Key Methods of Object Class
    • toString()
    • equals(Object obj)
    • hashCode()
    • getClass()
    • clone()
    • finalize()
  • FAQs
    • What is the purpose of the hashCode() method in the Object class?
    • What is the purpose of the getClass() method in the Object class?

The Key Methods of Object Class

The Object class provides a set of crucial methods that can be utilized by any class in Java. These are:

  • toString() – Returns a string representation of an object.
  • equals(Object obj) – Compares two objects for equality.
  • hashCode() – Returns a unique integer (hash code) for an object.
  • getClass() – Returns the runtime class of the object.
  • clone() – Creates a copy of the object (requires implementing Cloneable).
  • finalize() – Called before garbage collection (deprecated in Java 9).

Let’s explore some of the most commonly used methods with accompanying code examples and their expected output.

toString()

The toString() method provides a textual representation of the object. It is good to override subclasses to return meaningful and descriptive information about the object’s state while printing the object itself.

See the example below:

class Person {
	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person{" + "name='" + name  + "', age=" + age + '}';
	}
}

public class ToStringMethodDemo {
	public static void main(String[] args) {
		Person person = new Person("Radha", 30);

		System.out.println(person); // Output: Person{name='Radha', age=30}
	}
}

If we don’t override the toString() method then it will print the garbage value. See the example below:

class Person {
	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

}

public class ToStringMethodDemo {
	public static void main(String[] args) {
		Person person = new Person("Radha", 30);

		System.out.println(person); // Output: Person@75a1cd57
	}
}

Although, it allows us to use the toString() method like:

String objectValue = person.toString();

It still prints the garbage value like:

Person@75a1cd57

Hence, it is recommended to override toString() method if you want to print the nicely formatted information of the class object.

equals(Object obj)

The equals() method allows for the comparison of two objects for equality. By default, the equals() method checks for reference equality.

import java.util.Objects;
class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        Person person = (Person) obj;
        return Objects.equals(name, person.name);
    }
}

public class EqualsMethodDemo {
    public static void main(String[] args) {
        Person person1 = new Person("Radha");
        Person person2 = new Person("Radha");
        Person person3 = new Person("Krishnan");

        System.out.println(person1.equals(person2)); // Output: true
        System.out.println(person1.equals(person3)); // Output: false
    }
}

hashCode()

The hashCode() method returns a unique integer value for each object. This method is often overridden when the equals() method is customized to ensure consistency between the two. It is widely used in hash-based data structures like HashMap and HashSet.

import java.util.Objects;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

public class HashCodeMethodDemo {
    public static void main(String[] args) {
        Person person1 = new Person("Radha");
        Person person2 = new Person("Radha");

        System.out.println(person1.hashCode()); // Output: 78717901
        System.out.println(person2.hashCode()); // Output: 78717901
    }
}

getClass()

The getClass() method returns the runtime class of an object. It is frequently used to obtain metadata about the object’s class, such as its name or the interfaces it implements.

class Person {
	// Class implementation

	public void printClassName() {
		System.out.println("Class: " + super.getClass().getName());
	}
}

public class GetClassMethodDemo {
	public static void main(String[] args) {
		Person person = new Person();
		person.printClassName(); // Output: Class: Person
	}
}

clone()

The clone() method creates a shallow copy of the object. The copy of the object will have the same values as the original object, but it will be a separate object.

class Person implements Cloneable {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Person(String name) {
		super();
		this.name = name;
	}

	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.clone();
	}
}

public class CloneMethodDemo {
	public static void main(String[] args) {
		Person person1 = new Person("Radha");
		try {
			Person person2 = (Person) person1.clone();
			System.out.println(person1.equals(person2)); // Output: false
			System.out.println(person1.getName().equals(person2.getName())); // Output: true
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}

finalize()

The finalize() method is invoked by the garbage collector before reclaiming an object’s memory. It can be overridden to perform necessary cleanup operations or resource deallocation.

class Person {
	// Class implementation

	@Override
	protected void finalize() throws Throwable {
		System.out.println("Finalizing Person object...");
		// Cleanup operations
		super.finalize();
	}
}

public class FinalizeMethodDemo {
	public static void main(String[] args) {
		Person person = new Person();
		person = null;
		System.gc(); // Request garbage collection
	}
}

Output:

Finalizing Person object...

Note: The finalize() method is deprecated from Java 9. I am adding it for reference. You should not use this method. You can read about this deprecation on the official site.

Since all classes implicitly inherit from the Object class, it is possible to override its methods in subclasses to tailor their behavior to specific requirements. This allows developers to define customized equality checks, change the object’s string representation, or implement additional functionality.

There are other important methods in Object class like wait() and notify(). There is a separate post on this. You can read the wait() and notify() methods with proper examples.

FAQs

What is the purpose of the hashCode() method in the Object class?

The hashCode() method returns a hash code value for an object. This value is often used in data structures like hash tables to optimize and speed up retrieval operations. It’s essential to override hashCode() when the equals() method is overridden to ensure consistent behavior.

What is the purpose of the getClass() method in the Object class?

The getClass() method in the Object class returns the runtime class of an object. It is often used for runtime type checking and can be helpful when working with polymorphism.

Related Posts:

  • == vs .equals() in Java: What’s the Difference?
  • Control Statements in Java
  • Java Classes and Objects: The Foundation of Object…
  • Inheritance in Java: A Developer’s Guide to Code Reusability
  • MySQL Commands for Developers
  • Abstract Class in Java: Bridging Code Reusability…
Tags:devopsjava
Was this article helpful?
← Previous Articlesuper Keyword in Java
Next Article →JCheckBox in Java Swing

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap