Skip to main content

toString method of Object class in java

What is toString() method of object class in java:

The toString method in Java is a member of the Object class and is used to return a string representation of an object.

By default, the toString method provides a string that includes the class name and the memory address of the object.

Default Implementation of toString:

The toString method is defined in the Object class as follows:

Purpose of Overriding toString:

The default implementation is not very informative for most use cases. Therefore, it is common to override the toString method in custom classes to provide meaningful and human-readable information about the object's state.

Example: Default Behavior:

public class Main {

  public static void main(String[] args) 

  Object obj = new Object();

 System.out.println(obj.toString());

 } 

 }

Output:

java.lang.Object@<hashCode>

The <hashCode> part is the hexadecimal representation of the object's hash code.

Example: Overriding toString

Here's how you might override the toString method in a custom class:

java code:

public class Person { private String name; private int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } // Overriding toString @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } public static void main(String[] args) { Person person = new Person("Alice", 30); System.out.println(person); // Calls person.toString() implicitly } }

Output:

Person{name='Alice', age=30}

Explanation of the Code: Equals Method: Compares two Person objects for equality based on their name and age fields.
HashCode Method: Uses Objects.hash() to generate a hash code based on the name and age fields. This ensures that hashCode is consistent with equals.
Demonstration: Two Person objects with the same name and age have the same hashCode value and are considered equal. Different Person objects produce different hash codes.
Key Points: Consistency: If the state of an object does not change, the hashCode method should consistently return the same value. Performance: A good hashCode implementation minimizes collisions, improving the performance of hash-based collections.
Best Practices: Use the Objects.hash() utility method for simplicity and reliability when calculating hash codes. Include the same fields in hashCode as in equals. This ensures that your custom class works effectively in collections like HashMap or HashSet

Comments

Popular posts from this blog

What is real use of interface: mostly asked interview question

Actually in real project development interfaces are use to write business logic code . Also Interfaces in java are powerful tools that allow you to define a contract for what a class can do, without specifying how it does it. it means we can give method declaration in interface and what that method does actually that responsibility is given to the class which is going to implement that class. They are used for several real-world purposes like enabling polymorphism , creating loosely coupled systems , and defining common behaviors across different classes . Real-World Use of Interfaces Let's look at some practical scenarios where interfaces are commonly used: 1. Multiple Inheritance (via Interfaces):  Java doesn't support multiple inheritance with classes, but it allows multiple inheritance with interfaces. This allows a class to implement multiple interfaces, enabling it to inherit behaviors from more than one source. 2. Polymorphism: Interfaces allow you to treat different o...

Roadmap to become a fullstack developer

 Becoming a Full Stack Developer means gaining proficiency in both frontend and backend development, as well as understanding the tools and practices that tie them together. Below is a roadmap to guide your journey toward becoming a full-stack developer. This roadmap covers the key areas, from foundational knowledge to advanced topics. Roadmap to Becoming a Full Stack Developer 1. Learn the Basics of Web Development 1.1 HTML (Hypertext Markup Language) Learn the basic structure of web pages. Understand the role of elements like <div>, <span>, <a>, <img>, etc. Learn about semantic HTML (<header>, <footer>, <article>, etc.). 1.2 CSS (Cascading Style Sheets) Learn how to style web pages (colors, fonts, spacing, etc.). Master CSS layout techniques like Flexbox and Grid. Understand the importance of Responsive Design (media queries, mobile-first approach). 1.3 JavaScript (JS) Learn the fundamentals: variables, loops, conditionals, functions. Und...

How to convert Enum Contants into String: Inbuilt methods of Enum in java

 In Java, every enum type inherits several built-in methods from the java.lang.Enum class, which is the base class for all enum types. These built-in methods provide functionality such as getting the name of an enum constant, comparing enum constants, and iterating over all constants. Here are the inbuilt methods provided by the Enum class: 1. values() Description : This method returns an array of all the constants of the enum type, in the order they were declared. Syntax : public static T[] values() Example : enum Day {     MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public class EnumMethodsExample {     public static void main(String[] args) {         Day[] days = Day.values();  // Get all enum constants                  // Loop through the array and print each day         for (Day day : days) {             System.out....