toString() method in Java

Hello Learners, today we are going to learn about the toString method in Java. You all know that the object class is the parent class of all other classes in Java. The object class contains the toString method in it, let’s get a brief idea about the method.

Java toString() Method:

This method comes under Java.lang package inside the object class. The toString method is used to convert an object into a string. we can say that it gives a string representation of any object. Whenever you try to print any object, the toString method is called by the compiler internally and prints the string representation of the object.

toString method has different versions with different numbers of parameters, i.e. Method OverLoading. So, let’s see an example for better understanding of code.

import java.lang.*; 
public class Sample{ 
    
    int x;
    Sample(int a) {
        this.x = a;
    }

public static void main(String[] args) {
    
    Sample samp = new Sample(20);

  Integer obj = new Integer(8); 
  
  String st = obj.toString(); 
  System.out.println("value in string: " + st); //print1
  
  String s1 = obj.toString(450); 
  System.out.println("value in string: " + s1); //print2
   
  String s2 = obj.toString(450, 2); 
  System.out.println("value in string: " + s2); //print3
  
  System.out.println(samp);                     //print4
  System.out.println(samp.toString());          //print5
   } 
} 

OUTPUT:

value in string: 8
value in string: 450
value in string: 111000010
Sample@449b2d27
Sample@449b2d27
  • when print1 is executed, the value of obj which is 8 of type Integer has been changed to string and printed. Note that in print1 statement no argument is passed to the toString method. it converts the object value into a string (8 is converted into String).
  • In print2 statement, toString method is called over an Integer type object. One argument has been passed to the method of the same type which is also an integer. hence, 450 is converted into a string.
  • In print3 statement, two arguments have been passed that is of the same type as your object which is Integer here. The first argument (450) has been converted into a string taking the second argument (2) as a base. So, 450 in base 2 is the binary representation of it.
  • Now if you compare print4 and print5, the output for both the statements are the same. As I mentioned above, that is because while printing an object the compiler internally calls the toString method to get the object’s string representation.

Click on the link to learn more about Java string methods. So, that’s all for now about the toString method in Java. Till then Keep Learning, Keep Practicing, Keep Reading, Keep Coding!

Leave a Reply