How To Use Java toString Method?

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

In this tutorial, we will learn about the Java toString() method. We will take a look at the Description of the toString() Java Method along with the Programming Examples:

Upon going through this tutorial, you will be able to understand the concepts of the toString() Java method and you will be comfortable in using it in your programs to get the String representation of the object.

=> Visit Here To Learn Java From Scratch

Java String - toString Method

Java toString()

As the name suggests, a Java toString() method is used to return the String equivalent of the object that invokes it.

Syntax

public static String toString()
public static String toString(int i)
public static String toString(int i, int base)

We have three variants of the Java String toString() method. All the three variants return the String representation for any Integer. We will discuss all the three variants in the latter part of this tutorial.

toString() With base 10 And base 2

In this programming example, we will see how toString() Java method works. Here, we are creating an object of base 10. Then we are trying to get the String representation of that object in base 10 and base 2.

public class toString {

	public static void main(String[] args) {
		
		//in base 10
		Integer obj = new Integer(10);

		//used toString() method for String equivalent of the Integer
		String str1 = obj.toString();
		String str2 = obj.toString(80);
		
		//in base 2
		String str3 = obj.toString(658,2);

		// Printed the value of all the String variables
		System.out.println(str1);
		System.out.println(str2);
		System.out.println(str3);

	}

}

Output:

toString with base10 and 2

toString() With Decimal

In this example, we will see how the Java toString() method works with the decimal or float variables.

Here, we have created an object of base 10. Then, we have passed a decimal value (in the previous program we have passed an integer value 80 which returned 80 as an output).

This will throw a compilation error with the message “The method toString(int) in the type Integer is not applicable for the arguments (double)”. That is why we have to use the Double class toString() method to get the String representation of float/double which we will discuss in the next example.

public class toString {

	public static void main(String[] args) {

		//in base 10
		Integer obj = new Integer(10);
		
		/*
		 *  The method toString(int) in the type Integer is
		 *  not applicable for the arguments (float or double)
		 */
		
		String str1 = obj.toString(69.47);
		System.out.println(str1);
		
	}

}

Output:

toString decimal

toString() With Double

As an outcome of the previous example, we will discuss getting the String representation of float/double variables in this example.

public class toString {

	public static void main(String[] args) {

		// Initialized a double variable with the value 146.39
		double dbl = 146.39d;
		
		// Getting the String representation of the double variable 
		String str = Double.toString(dbl);
		System.out.println(str);
		
	}

}

Output:

toString double

Scenarios

Scenario 1: Illustrating Java toString(int num, int base value).

Explanation: Here, we are going to illustrate the Java toString(int number, int base value) and will try to get the String representation of the different cases.

In this scenario, we have created an object in base 10. Then, we have used Java toString(int num, int base value) to try the base value 2, 8, 16, and 10. Thereafter, we have printed the String representation of each of these base values for the specified integer value.

public class toString {

	public static void main(String[] args) {
		
	    // in base 10
		Integer obj = new Integer(10);
		
        // in base 2 
	    String str = obj.toString(9876, 2); 
	    
	    // It returns a string representation	    
	    System.out.println("String Value of 9876 in base 2 = " +  str); 
	    System.out.println();
	    
        // in base 8
	    str = obj.toString(350, 8); 
	    
	    // It returns a string representation
	    System.out.println("String Value of 350 in base 8 = " + str);  	  
	    System.out.println();
	    
	    // in base 16 
	    str = obj.toString(470, 16); 
	    
	    // It returns a string representation
	    System.out.println("String Value of 470 in base 16 = " + str);  	  
	    System.out.println();
	    
	    // in base 10 
	    str = obj.toString(451, 10);
	    
	    // It returns a string representation
	    System.out.println("String Value of 451 in base 10 = " + str);

	}

}

Output:

Scenario 1 - toString method

Scenario 2: In this scenario, we will try Java toString on the negative Integers.

Explanation: Here, we have used the same program (as in Scenario 1). The only difference here is the use of a negative number. We did not change the base value but the Integer values have been changed into negative numbers.

As we see the output of this program, we came to know that the Java toString() method works well with the negative numbers.

Note: If we add any decimal value in the place of the Integer then the program will throw a compilation error.

public class toString {

	public static void main(String[] args) {
		
	    // in base 10
		Integer obj = new Integer(10);
		
        // in base 2 
	    String str = obj.toString(-9876, 2); 

	    // It returns a string representation
	    System.out.println("String Value of 9876 in base 2 = " +  str); 
	    System.out.println();

        // in base 8
	    str = obj.toString(-350, 8); 

	    // It returns a string representation
	    System.out.println("String Value of 350 in base 8 = " + str); 
	    System.out.println();
	    
	    // in base 16 
	    str = obj.toString(-470, 16); 
	    
	    // It returns a string representation
	    System.out.println("String Value of 470 in base 16 = " + str);
	    System.out.println();
	    
	    // in base 10 
	    str = obj.toString(-451, 10); 

	    // It returns a string representation
	    System.out.println("String Value of 451 in base 10 = " + str);
	    
	}

}

Output:

Scenario 2 - toString method

Frequently Asked Questions

Q #1) Is toString a static method?

Answer: No. The Java toString() is an instance method because we invoke this method on the instance of the class. Therefore, you can call it a class method.

Q #2) What are the variants of the Java toString() method?

Answer: There are three variants of the Java toString() method as shown below.

  • public static String toString() -> String representation of invoking object.
  • public static String toString(int i) -> String representation of a specified Integer.
  • public static String toString(int i, int base) -> String representation of a specified Integer according to the base value.

Q #3) Write a Java Program to illustrate all three variants of the Java toString() method.

Answer: Given below is the program where we have used all the three variants to generate the String equivalent of an Integer with all the three variants.

The first variant is the “String representation of this Integer”, the second variant is the “String representation of specific Integer” and the third variant is the “String representation of specified Integer according to the base value”.

public class toString {

   public static void main(String args[]) {
      Integer a = 5;

      // String representation of the this Integer
      System.out.println(a.toString());  

      //String representation of specified Integer 9
      System.out.println(Integer.toString(9));

      //String representation of specified Integer 20 with base 10
      System.out.println(Integer.toString(20, 10));
      
   }
}

Output:

Java Program to illustrate all three variants

Q #4) Does Java automatically call toString()?

Answer: Yes. As every object in Java belongs to the “IS-A” relationship. IS-A is nothing but inheritance. For E.g. – Toyota C-HR is a Car.

If there is no implementation for toString() found in the class, then the Object class (which is a superclass) invokes toString() automatically.

Hence, the Object.toString() gets called automatically.

Q #5) What is array toString() Java?

Answer: An array toString(int[]) is a method that returns the String representation of the elements of an array of type Integer.

The syntax is given as

public static String toString(int[] arr)

Where arr is the array whose String equivalent has to be returned.

import java.util.Arrays;

public class toString {
   public static void main(String[] args) {

      // initialized an array of type Integer
      int[] arr = new int[] { 90, 63, 44, 55 };

      // printing all the elements of an array
      System.out.println("The array is:");
      for(int i=0; i<arr.length; i++) {
    	  System.out.println(arr[i]);
      }
      
      System.out.println("The string representation of array:");
      
      // printing the String Equivalent of array
      System.out.println(Arrays.toString(arr));    
   }
}

Output:

array toString() Java

Q #6) Can we override the toString method in Java?

Answer: Yes, we can override the toString() method in Java. Below is the example where we have created a class called Zoo with private data members animal_name and animal_number.

Then we have used a constructor to initialize these two members. Thereafter, we have an overridden method toString() which will return the values of these two data members (concatenated by space).

Finally, in the main class toString, we have created an object str of Zoo class with the values as 534 and “Animals” and printed the object.

class Zoo {

	// Zoo class has two members animal_number and animal_name
	private int animal_number;
	private String animal_name;

	// The constructor Zoo initialized these two data members
	public Zoo(int a, String b) {
		animal_number = a;
		animal_name = b;
	}

	public String toString() {

		/*
		 * This overridden method toString() will return the value of members -->
		 * animal_number and animal_name
		 */
		return animal_number + " " + animal_name;
	}
}Public class toString {
	public static void main(String[] args) {

		// Object str of Zoo class is created with 534 and "Animals" as value
		Zoo str = new Zoo(534, "Animals");
		System.out.println("Total Animals are:");

		// Printed the str object
		System.out.println(str);
	}
}

Output:

override the toString method in Java

Conclusion

In this tutorial, we have understood the Java toString() method in detail. Moreover, the programming examples for each of the base value was appropriate to know about the conversion of Integer into String representation for a particular base value.

For better understanding, this tutorial was explained with the help of different scenarios. We also learned about the negative and decimal/floating-point number behavior when used in the toString() method.

Also, we explored the Frequently asked questions with the help of which you can understand this method clearly.

=> Check The Entire Java Training Series Here

Was this helpful?

Thanks for your feedback!

Leave a Comment