Creating String object – toString() Method

All Java classes inherit a toString() defined in java.lang.Object that is used to generate a string representation of the object. For example, consider the following:

Long myLong = new Long(43);
String longStr = myLong.toString();


In this case, a Long object is created and set to hold the value 43. Note that this is an object of type Long, not a primitive of type long.

You can also create a String from user-defined object by overriding toString() method in your class.

class Person
	private int age;
	private String name;
	public Person(int age, String name)
		this.age = age; = name;
	public String toString() {
		return "Person [age=" + age + ", name=" + name + "]";

public class ObjectToString {
	public static void main(String[] args) {
		Person person = new Person(10, "Kumar");
		String objStr = person.toString();
		//calls Person’s toString()

Person [age=10, name=Kumar] Person [age=10, name=Kumar]

Leave a Comment