I am a newbie in java. Say, I have a class Individual. I want to print
Individual ind = new Individual();
System.out.println(ind);
Above code gives output like this:
Individual@1922221
If you want to print meaningful content of any object, you have to implement your own toString()
method, which will override the parent(Object
) class's toString()
method. By default all the classes(Whatever you create) extends Object
class.
Sample Code:
public class Individual {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Name of Individual :").append(this.getName())
.append("\nCity :").append(this.getCity());
return builder.toString();
}
public static void main(String[] args) {
Individual individual = new Individual();
individual.setName("Crucified Soul");
individual.setCity("City of Crucified Soul");
System.out.println(individual);
}
}
Output:
Name of Individual :Crucified Soul
City :City of Crucified Soul
If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.
This is the result of default toString() method - the classname + hashcode. This can be override by overriding toString().
Some reference here: http://www.javapractices.com/topic/TopicAction.do?Id=55
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With