DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module5-toString and Clone methods

01.What is the "toString"?

  1. The toString() method is defined in the Object class.
  2. It is used to return a string representation of an object.
  3. Available in all Java classes.
  4. Shows class name + hash code.
  5. Provides custom readable output.
  6. Very useful for debugging, logging, and displaying object info.

Default implementation (from Object) → returns a string with the class name + @ + hash code (in hexadecimal).

Overridden implementation → you can override it in your class to return meaningful information about the object (like field values).

02. Advantages of toString():
1.Readable Output
2.Default Availability
3.Easily Overridable
4.Automatically Called
When you print an object (e.g., System.out.println(obj);), Java automatically calls obj.toString().

03. Disadvantages of toString()
1.Requires Manual Overriding
2.Possible Maintenance Overhead
3.Performance Overhead

04.What is the Clone method?

  1. The clone() method is used to create a duplicate of an object.
  2. It requires the Cloneable interface and by default performs a shallow copy.
  3. Creating copies of objects without using constructors.
  4. Helpful in prototyping or caching objects.
  5. Used in scenarios where object duplication is required.

05. Advantages of clone()?
1.Easy Object Duplication
2.Faster than Manual Copying
3.No Constructor Call Needed

06. Disadvantages of clone()?
1.Shallow Copy by Default
2.Must Implement Cloneable
3.Requires implementing Cloneable interface

Top comments (0)