Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing reference to an object [duplicate]

Tags:

java

object

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
  1. What is the significance of this?
  2. Is it some kind of unique id for that object?
  3. Can I customize this? I mean write a function of my own which will give output when I print?
  4. If so, how can I do this?
like image 852
user Avatar asked Jan 04 '12 16:01

user


2 Answers

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.

like image 71
Ahamed Avatar answered Sep 21 '22 11:09

Ahamed


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

like image 38
Jan Zyka Avatar answered Sep 20 '22 11:09

Jan Zyka