Downloads
Object toString() (Article)
Introduction
In this article from my free Java course, I will explain the Object to
The Object to
public String toString() {
return getClass().getName() + ‘@’ + Integer.toHexString(hashCode());
}
Example 1
Example 1 shows how the toString() method concatenates the getClass().getName() method, an ‘@’ symbol and a hexadecimal value for the Object’s hashCode to create a String that represents the object. The getClass() method returns the runtime class of the class the object belongs to. The getName() method then returns the full-fledged class name. For example, if you have a class “BMW” in the package “com.marcusbiel.java8course” and you instantiate a BMW object, a call to getClass().getName() will return “com.marcusbiel.java8course.BMW”. The Integer.toHexString(hashCode()) method creates a hexadecimal representation of the object’s hashCode. Here is a brief example of a method that would utilize a toString() call:
@Test
public void shouldConvertBMWToString() {
BMW bmw = new BMW(new Name("Marcus", "Biel"), new Color("silver"));
System.out.println(bmw.toString());
System.out.println(bmw);
}
Example 2
Both of the System.out.println() lines in Example 2 call Object to
While System.out.println() works well for debugging or diagnostic information in the console, it lacks the flexibility of logging in terms of output. A logger also normally yields better performance. Returning to the method above, either System.out.println() call will return BMW@e2144e4. That String isn’t very useful to us, especially if we are debugging the code and trying to understand the current state of the object. Presumably, if we are calling a BMW object to
Overriding the Object toString() Method
package com.marcusbiel.javacourse.car;
public class BMW implements Car, Cloneable {
private Name ownersName;
private Color color;
public BMW(Name ownersName, Color color) {
this.ownersName = ownersName;
this.color = color;
}
}
Example 3
Here you can see the BMW class that I referenced in my previous example. As you saw in the last section, when we call println(bmw.to
@Override
public String toString() {
return getClass().getName() + " [" + ownersName + ", " + color + "]";
}
Example 4
Above, I have overridden the to
@Test
public void shouldConvertBMWToString() {
BMW bmw = new BMW(new Name("Marcus", "Biel"), new Color("silver"));
System.out.println(bmw.toString());
}
Example 5
If I run this method again, assuming that we have created the Name to
StringBuilder: An Alternative to String Concatenation
The final thing I’d like to highlight in this article is the String
@Override
public String toString() {
return new StringBuilder (“BMW [“).append(ownersName).append(“,“)
.append(color).append(“]”).toString();
}
Example 6
2 comments
le livre java for passionnate Developers peut-il m’aider ?
It’s in english, so I am not sure if it can help you if you don’t seem to speak english.