toString() method in Java



The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Objectit is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes.

===============================ToStringClass ======================================
public class ToStringClass {
public String toString() {
return "Hello I am ToStringClass\n";
}
public ToStringClass() {
System.out.println(this);
}

}

=====================================MainClass====================================
public class MainClass {

public static void main(String[] args) {
ToStringClass toStringObject = new ToStringClass();
}

}

=======================================OUTPUT===================================

Hello I am ToStringClass




In most languages, toString or the equivalent method just guarantees that an object can be represented textually.
This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.
Objects often implement custom toString behavior so that the method actually tells you something about the object instance. For example, a Person class might override it to return "Last name, First name" while a Date class will show the date formatted according to some default setting (such as the current user interface culture).

Comments

  1. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we provide Java training at Fita.

    ReplyDelete

Post a Comment

Popular posts from this blog

What happened to the blog ?

Why I love to be a programmer ?