toString is another method belonging to the Object class. The default behavior is to return the name of the class, followed by an @ then the hash code of the object in hexadecimal. toString can be invoked explicitly as in
System.out.println(emp2.toString());
resulting in something like:
Employee@f97
toString is also invoked implicitly by Java when concatenating a non-String object with a String, as in
System.out.println("emp2 is " + emp2);
toString
public String toString()
{
return ''Employee[" + empNumber + ", " + name + ", " + salary + "]";
}
The statement
System.out.println(emp2.toString());
will now output
Employee[2, Sim, 15000]
Java toString Method
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment