toString with examples

ToString() is a Java built-in method that returns a string representation of the value sent to it. As a result, any object on which this method is called will be returned as a string object.

The String object representing the primitive data type value is returned if the method takes a primitive data type as an input. If the method has two arguments, the first argument will be represented as a String in the radix provided by the second argument.

Java toString

Syntax

The Following are some of the toString()’s variants:-

String toString()
static String toString(int i)

i – refers to an int that will be returned as a string representation.

Value of the Return

toString()

toString() returns a String object that represents this integer’s value.

toString(int i)

This method returns a String object representing the supplied integer. toString(int i returns a String object representing the specified integer.

The toString() function in Java has several advantages. We may return object values without writing much code by altering the toString() method of the Object class.

You can find the Object class in the java.lang package. Every class in Java is inherited, either directly or indirectly, from the Object class. As a result, it is a child of the Object class. If a class does not extend another class, it is a direct child class of Object, and if it does, it is indirectly derived. As a result, all Java classes have access to the Object class methods.

In any Java application, the object class serves as the root of the inheritance tree.

Without the toString() method, it’s challenging to grasp the problem. Let’s explore some basic code that prints references.

class Employee{  
 int empID;  
 String name;  
 String city;  
  
 Employee(int empID, String name, String city){  
 this.empID =empID;  
 this.name=name;  
 this.city=city;  
 }  
  
 public static void main(String args[]){  
   Employee empOne =new Employee(1,"Ann","Smith");  
   Employee empTwo =new Employee(2,"Mike","Dean");  
     
   System.out.println(empOne);//compiler writes here empOne.toString()  
   System.out.println(empTwo);//compiler writes here empTwo.toString()  
 }  
}  

Printing empOne and empTwo prints the hashcode values of the objects, as seen above, but we want to publish the values of these objects. Because the toString() method is called internally by the Java compiler, overriding it will return the supplied values. Let’s explore a sample to help you understand:

Let’s look at an example of the toString() method in action.

class Employee{  
 int empID;  
 String name;  
 String city;  
  
 Employee(int empID, String name, String city){  
 this.empID =empID;  
 this.name=name;  
 this.city=city;  
 }  
   
 public String toString(){//overriding the toString() method  
  return empID+" "+name+" "+city;  
 }  
 public static void main(String args[]){  
   Employee empOne =new Employee(1,"Ann","Smith");  
   Employee empTwo =new Employee(2,"Mike","Dean");  
     
   System.out.println(empOne);//compiler writes here empOne.toString()  
   System.out.println(empTwo);//compiler writes here empTwo.toString()  
 }  
}  

The toString() method is called internally by the Java compiler in the software, as mentioned earlier; overriding this method returns the provided values of the empOne and empTwo objects of the Student class.

What is the toString() method, and how do I utilize it?

In Java, there are two implementations of the toString() method. The first implementation is invoked as a method of an object instance. This is demonstrated in the example below.

class numToString {
  public static void main( String args[] ) {   
//Creating an integer of value 25
    Integer numVal=25;
    // Calling the toString() method as a function of the Integer variable
    System.out.println( numVal.toString() );
}
}

The second implementation is when the value is passed as an argument to the relevant class’s member method. This is demonstrated in the example below.

class numToString {
    public static void main( String args[] ) {
        
        // The method is called on the Double data type
       // the double value is passed  as an argument
     

        System.out.println(Double.toString(25.50));
       

        //Implementation on the Integer datatype
        System.out.println(Integer.toString(98));

        // Implementation on the Long Datatype
        System.out.println(Long.toString(54527857902316));

        // Implementation on the Booleam Datatype
        System.out.println(Boolean.toString(false));
    }
}

It’s worth noting that this function can be overridden as part of a class to adapt to the user’s specific requirements. This is demonstrated in the sample below!

class Employee{

  String name;
  Integer age;

  Employee(String n, Integer a){
    this.name=n;
    this.age=a;
  }

//Over-riding the toString() function as a class function
  public String toString(){
    return "The Employee's name is: " + this.name + ". The age of the employee is " + this.age;
  }
}

class HelloCodeunderscored {
    public static void main( String args[] ) {
      Employee newEmp = new Employee("Ann",78);

      //Calling the class version of toString()
        System.out.println(newEmp .toString());

      //Calling the original toString()
      System.out.println(Integer.toString(35));
    }
}

We created a new method within the Employee class with the same name as the toString() function from lines 11 to 13 in the code above. When the toString() function is triggered on line 20, the class version of the procedure is used. The function, however, does not alter for any other data type, as seen on line 22!

Example:

 public class toStringExample {

   public static void main(String args[]) {
      Integer numVal = 35;

      System.out.println(numVal .toString());  
      System.out.println(Integer.toString(numVal));
   }
}

Example: program illustrating the working of toString() method

// Main class
class ToStringExample {

	// defining the class Member attributes
	String name;
	int age;
	String college;
	String course;
	String address;

	// Constructor of this class
	ToStringExample(String name, int age, String college,
				String course, String address)
	{
		// This keyword refers to current instance itself
		this.name = name;
		this.age = age;
		this.college = college;
		this.course = course;
		this.address = address;
	}

	// Approach 1
	// Creating our own toString() method
	public String toString()
	{
		return name + " " + age + " " + college + " "
			+ course + " " + address;
	}

	// Approach 2
	// Main driver method
	public static void main(String[] args)
	{
		// Creating object of class inside main() method
		ToStringExample toStringExample = new ToStringExample(
			"Ann Smith", 35, "Codeunderscored School of Computing", "Java Competency",
			"Code");

		// Printing and displaying the commands needed to illustrate
		// toString() method as both will print the same
		// Print the object
		System.out.println(toStringExample);

		// Printing object but using toString() method
		System.out.println(toStringExample .toString());
	}
}

The toString() method is overridden for meaningful String representation in all wrapper classes, all collection classes, String class, StringBuffer, and StringBuilder classes. As a result, overriding the toString() method in our class is highly advised.

Conclusion

The toString() method is available if you wish to express any object as a string. The toString() method returns the object’s string representation. The Java compiler calls the object’s toString() method internally when you print an object. So, depending on your implementation, overriding the toString() method produces the appropriate output, which may be the state of an object.

To acquire the string representation of an object, we usually utilize the toString() method. Readers must understand that anytime we try to print an object reference, the toString() method is called internally. If we didn’t specify the toString() method in the class, the toString() method of the Object class is used. Otherwise, our overridden or implemented toString() method is used.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *