The Wayback Machine - https://web.archive.org/web/20241126031847/https://www.geeksforgeeks.org/object-class-in-java/
Open In App

Object Class in Java

Last Updated : 06 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of Object and if extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of the inheritance hierarchy in any Java Program.

Object Class in Java

Using Object Class Methods

The Object class provides multiple methods which are as follows:

  • toString() method
  • hashCode() method
  • equals(Object obj) method
  • finalize() method
  • getClass() method
  • clone() method
  • wait(), notify() notifyAll() methods

1. toString() method

The toString() provides a String representation of an object and is used to convert an object to a String. The default toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, it is defined as:

// Default behavior of toString() is to print class name, then
// @, then unsigned hexadecimal representation of the hash code
// of the object

public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

It is always recommended to override the toString() method to get our own String representation of Object. For more on override of toString() method refer – Overriding toString() in Java 

Note: Whenever we try to print any Object reference, then internally toString() method is called.

Student s = new Student();

// Below two statements are equivalent
System.out.println(s);
System.out.println(s.toString());

2. hashCode() method

For every object, JVM generates a unique number which is a hashcode. It returns distinct integers for distinct objects. A common misconception about this method is that the hashCode() method returns the address of the object, which is not correct. It converts the internal address of the object to an integer by using an algorithm. The hashCode() method is native because in Java it is impossible to find the address of an object, so it uses native languages like C/C++ to find the address of the object.

Use of hashCode() method

It returns a hash value that is used to search objects in a collection. JVM(Java Virtual Machine) uses the hashcode method while saving objects into hashing-related data structures like HashSet, HashMap, Hashtable, etc. The main advantage of saving objects based on hash code is that searching becomes easy. 

Note: Override of hashCode() method needs to be done such that for every object we generate a unique number. For example, for a Student class, we can return the roll no. of a student from the hashCode() method as it is unique. 

Java




// Java program to demonstrate working of
// hashCode() and toString()
 
public class Student {
    static int last_roll = 100;
    int roll_no;
 
    // Constructor
    Student()
    {
        roll_no = last_roll;
        last_roll++;
    }
 
    // Overriding hashCode()
    @Override public int hashCode() { return roll_no; }
 
    // Driver code
    public static void main(String args[])
    {
        Student s = new Student();
 
        // Below two statements are equivalent
        System.out.println(s);
        System.out.println(s.toString());
    }
}


Output :

Student@64
Student@64

Note that 4*160 + 6*161 = 100 

3. equals(Object obj) method

It compares the given object to “this” object (the object on which the method is called). It gives a generic way to compare objects for equality. It is recommended to override the equals(Object obj) method to get our own equality condition on Objects. For more on the override of equals(Object obj) method refer – Overriding equals method in Java

Note: It is generally necessary to override the hashCode() method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 

4. getClass() method

It returns the class object of “this” object and is used to get the actual runtime class of the object. It can also be used to get metadata of this class. The returned Class object is the object that is locked by static synchronized methods of the represented class. As it is final so we don’t override it.

Java




// Java program to demonstrate working of getClass()
 
public class Test {
    public static void main(String[] args)
    {
        Object obj = new String("GeeksForGeeks");
        Class c = obj.getClass();
        System.out.println("Class of Object obj is : "
                           + c.getName());
    }
}


Output: 

Class of Object obj is : java.lang.String

Note: After loading a .class file, JVM will create an object of the type java.lang.Class in the Heap area. We can use this class object to get Class level information. It is widely used in Reflection 

5. finalize() method

This method is called just before an object is garbage collected. It is called the Garbage Collector on an object when the garbage collector determines that there are no more references to the object. We should override finalize() method to dispose of system resources, perform clean-up activities and minimize memory leaks. For example, before destroying the Servlet objects web container, always called finalize method to perform clean-up activities of the session. 

Note: The finalize method is called just once on an object even though that object is eligible for garbage collection multiple times. 

Java




// Java program to demonstrate working of finalize()
 
public class Test {
    public static void main(String[] args)
    {
        Test t = new Test();
        System.out.println(t.hashCode());
 
        t = null;
 
        // calling garbage collector
        System.gc();
 
        System.out.println("end");
    }
 
    @Override protected void finalize()
    {
        System.out.println("finalize method called");
    }
}


Output: 

1510467688
finalize method called
end

6. clone() method 

It returns a new object that is exactly the same as this object. For clone() method refer Clone().

The remaining three methods wait(), notify() notifyAll() are related to Concurrency. Refer to Inter-thread Communication in Java for details.

Example of using all the Object class methods in Java

Java




import java.io.*;
 
public class Book implements Cloneable {
    private String title;
    private String author;
    private int year;
 
    public Book(String title, String author, int year)
    {
        this.title = title;
        this.author = author;
        this.year = year;
    }
 
    // Override the toString method
    @Override public String toString()
    {
        return title + " by " + author + " (" + year + ")";
    }
 
    // Override the equals method
    @Override public boolean equals(Object obj)
    {
        if (obj == null || !(obj instanceof Book)) {
            return false;
        }
        Book other = (Book)obj;
        return this.title.equals(other.getTitle())
            && this.author.equals(other.getAuthor())
            && this.year == other.getYear();
    }
 
    // Override the hashCode method
    @Override public int hashCode()
    {
        int result = 17;
        result = 31 * result + title.hashCode();
        result = 31 * result + author.hashCode();
        result = 31 * result + year;
        return result;
    }
 
    // Override the clone method
    @Override public Book clone()
    {
        try {
            return (Book)super.clone();
        }
        catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
 
    // Override the finalize method
    @Override protected void finalize() throws Throwable
    {
        System.out.println("Finalizing " + this);
    }
 
    public String getTitle() { return title; }
 
    public String getAuthor() { return author; }
 
    public int getYear() { return year; }
    public static void main(String[] args)
    {
        // Create a Book object and print its details
        Book book1 = new Book(
            "The Hitchhiker's Guide to the Galaxy",
            "Douglas Adams", 1979);
        System.out.println(book1);
 
        // Create a clone of the Book object and print its
        // details
        Book book2 = book1.clone();
        System.out.println(book2);
 
        // Check if the two objects are equal
        System.out.println("book1 equals book2: "
                           + book1.equals(book2));
 
        // Get the hash code of the two objects
        System.out.println("book1 hash code: "
                           + book1.hashCode());
        System.out.println("book2 hash code: "
                           + book2.hashCode());
 
        // Set book1 to null to trigger garbage collection
        // and finalize method
        book1 = null;
        System.gc();
    }
}


Output

The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)
The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979)
book1 equals book2: true
book1 hash code: 1840214527
book2 hash code: 1840214527



Previous Article
Next Article

Similar Reads

Collator compare(Object, Object) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result . Syntax: public int compare(Object o1, Object o2) Parameter: This method takes two objects between which comparison is going to take place.Return Value: if the first
2 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println("Hello"); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
Object Level Lock vs Class Level Lock in Java
Synchronized is the modifier applicable only for methods and blocks but not for classes and variables. If multiple threads are trying to operate simultaneously on the same java object then there may be a chance of data inconsistency problem to overcome this problem we should go for a 'synchronized' keyword. If a method or block declares as synchron
6 min read
Java Object Creation of Inherited Class
In Java, being an object-oriented language, objects inside a class is created with help of constructors. When it comes down to inheritance in Java we are basically dealing with deriving a class from another class. Now let us understand inheritance a step deeper so when a particular class inherits a class we do have a keyword that we use in order to
3 min read
Object level and Class level locks in Java
Synchronization: Synchronization is a modifier that is used for the method and blocks only. With the help of a synchronized modifier, we can restrict a shared resource to be accessed only by one thread. When two or more threads need access to shared resources, there is some loss of data i.e. data inconsistency. The process by which we can achieve d
3 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Difference Between Object And Class
Class is a detailed description, the definition, and the template of what an object will be. But it is not the object itself. Also, what we call, a class is the building block that leads to Object-Oriented Programming. It is a user-defined data type, that holds its own data members and member functions, which can be accessed and used by creating an
6 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), "GeeksforGeeks"); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet<String, String, String, String> quartet = new Quartet<String, String, String, String>( "Quartet", "Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet<String, String, String> triplet = new Triplet<String, String, String>( "Triplet 1", "1", "GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
String Literal Vs String Object in Java
Compare string initialization performance for String Literal and String object. String Literal String str = "GeeksForGeeks"; This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value "GeeksForGeeks", th
2 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
List remove(Object obj) method in Java with Examples
The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Syntax: boolean remove(Object obj) Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List. Return Value: It return
2 min read
ZoneOffset equal(Object) method in Java with Examples
The equals(Object) method of ZoneOffset Class in java.time package is used to check whether the another instance of ZoneOffset passed as the parameter to this ZoneOffset instance, is equal or not. This method returns a boolean value stating the same. Syntax: public boolean equals(Object object) Parameters: This method accepts a parameter object whi
2 min read
Stack indexOf(Object, int) method in Java with Example
The Java.util.Stack.indexOf(Object element, int index) method is used to the index of the first occurrence of the specified element in this Stack, searching forwards from index, or returns -1 if the element is not found. More formally, returns the lowest index i such that (i >= index && Objects.equals(o, get(i))), or -1 if there is no su
2 min read
Stack add(Object) method in Java with Example
The add(Object) method of Stack Class appends the specified element to the end of this Stack. Syntax: boolean add(Object element) Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended to end of the Stack. Return Value: This method returns True after successful
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg