a shot of dev knowledge

RELATED TAGS

How to use the toString() in Java

What is toString()?

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

How to use the toString() method

The toString() method in Java has two implementations;

  • The first implementation is when it is called as a method of an object instance. The example below shows this implementation
class HelloWorld {
    public static void main( String args[] ) {

        //Creating an integer of value 10
        Integer number=10;
        // Calling the toString() method as a function of the Integer variable
        System.out.println( number.toString() );
    }
}
  • The second implementation is when you call the member method of the relevant class by passing the value as an argument. The example below shows how to do this
class HelloWorld {
    public static void main( String args[] ) {
        
        // The method is called on datatype Double
        // It is passed the double value as an argument
        System.out.println(Double.toString(11.0)); 
        // Implementing this on other datatypes

        //Integer
        System.out.println(Integer.toString(12)); 

        // Long
        System.out.println(Long.toString(123213123));

        // Booleam
        System.out.println(Boolean.toString(false));
    }
}

What is interesting is that this method can also be over-ridden as part of a class to cater to the customized needs of the user. The example below shows how to do this!

class Pet{

  String name;
  Integer age; 

  Pet(String n, Integer a){
    this.name=n;
    this.age=a;
  }
//Over-riding the toString() function as a class function
  public String toString(){
    return "The name of the pet is " + this.name + ". The age of the pet is " + this.age;
  }
}

class HelloWorld {
    public static void main( String args[] ) {
      Pet p = new Pet("Jane",10);
      //Calling the class version of toString()
        System.out.println(p.toString());
      //Calling the original toString()
      System.out.println(Integer.toString(12));
    }
}

In the code above, from lines 11 to 13 we have simply created a new method within the Pet class with the same name as the toString() method. On line 20 when the toString() method is called, it is the class version of the method that is invoked. However as seen on line 22, the method does not change for any other data type!

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring