Why toString() ?

toString() in java
-------------------------------------------------------------------------
There is a superclass of all classes in java that is Object class.There are some methods which are present in the Object class. One of the methods is toString( ).

Do you ever know what if I print an object? When I print an object, internally it calls the toString() method of Object class And the "classname@hashcode" of the class is printed.

So if we want to print something that we want by toString(), Then we have to override it and to give it our own implementation.


Following is the default implementation of the toString() in java

@Override
public String toString() {

return "ConnectionClass [getClass()=" + getClass() + ", hashCode()=" + hashCode() + ",                                                                                                        toString()=" + super.toString() + "]";

}

it returns the classname+hashcode

if we want to print something we want then we override it and give our implementation.


class A
{
String name;
int age;

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

@Override
public String toString() {
return String.format("%-20s%-20s",name,age);
}
}


import java.util.*;
class Main
{
public static void main(String[] args)
{
     Scanner sc=new Scanner(System.in);
     int age=sc.nextInt();
     String name=sc.next();
   
     A a=new A(name,age);
   
     System.out.println(a);             //name and age will be printed with space separated
      System.out.println(a.toString());  //name and age will be printed with space separated
}
}

In the above program Main class, I printed the object "a".So internally toString() will be called and classname@hashcode() will print. So in order to print the age and name I override toString() method and told him to print name and age in class A.



type2
-----------------------
 public String toString(){
        return "Name: "+this.name+"-- Age: "+this.age;
    }

#why toString()
#Use of toString() in java
#what if i print an object
#Syntax of to string method

Comments

Popular posts from this blog

Git Commands With Output Log

Java Interview Preparation (conceptual)

Java 8 Function Interface