Creating String object – toString() Method

20 January 2012 By Nithya Vasudevan 1,015 views One Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

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();
System.out.println(longStr);

43

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;
		this.name = name;
	}
	
	@Override
	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();
		System.out.println(objStr);
		//or
		//calls Person’s toString()
		System.out.println(person);
	}
}

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

Tags: , ,