Wednesday, May 7, 2014

Why toString() method in bean class?

Why toString() method in bean class?

We can use it to print object values directly, if overriding toString() method. If you will try to print object without overriding toString() method, it will print some hexadecimal values.

Generally we will use toString() in bean class, to check the bean property values.

For example,

public class TestBean implements Serializable {

private string name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name= name;
}

public int getAge() {
return age;
}

public void setAge(String age) {
this.age= age;
}

@Override
public String toString() {

return "TestBean [name=" +  name  + ", age=" + age + "]";
}
}


Now you should set values to this bean property. Now somewhere you can create object for this bean class like below.

TestBean test = new TestBean();

try to print the test object ,
System.out.println(test);

It will display the value like below.

=TestBean[name=test, age=19 ]

So you can use this to debug or log etc.,



No comments:

Post a Comment