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.
toString()
methodThe toString()
method in Java has two implementations;
class HelloWorld {public static void main( String args[] ) {//Creating an integer of value 10Integer number=10;// Calling the toString() method as a function of the Integer variableSystem.out.println( number.toString() );}}
class HelloWorld {public static void main( String args[] ) {// The method is called on datatype Double// It is passed the double value as an argumentSystem.out.println(Double.toString(11.0));// Implementing this on other datatypes//IntegerSystem.out.println(Integer.toString(12));// LongSystem.out.println(Long.toString(123213123));// BooleanSystem.out.println(Boolean.toString(false));}}
toString()
methodWhat 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 functionpublic 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