How do I print my Java object without getting “SomeType@2f92e0f4”?

Multi tool use
How do I print my Java object without getting “SomeType@2f92e0f4”?
I have a class defined as follows:
public class Person {
private String name;
// constructor and getter/setter omitted
}
I tried to print an instance of my class:
System.out.println(myPerson);
but I got the following output: com.foo.Person@2f92e0f4
.
com.foo.Person@2f92e0f4
A similar thing happened when I tried to print an array of Person
objects:
Person
Person people = //...
System.out.println(people);
I got the output: [Lcom.foo.Person;@28a418fc
[Lcom.foo.Person;@28a418fc
What does this output mean? How do I change this output so it contains the name of my person? And how do I print collections of my objects?
Note: this is intended as a canonical Q&A about this subject.
See also stackoverflow.com/questions/27647567/…
– Raedwald
Mar 26 '16 at 14:14
9 Answers
9
Background
All Java objects have a toString()
method, which is invoked when you try and print the object.
toString()
System.out.println(myObject); // invokes myObject.toString()
This method is defined in the Object
class (the superclass of all Java objects). The Object.toString()
method returns a fairly ugly looking string, composed of the name of the class, an @
symbol and the hashcode of the object in hexadecimal. The code for this looks like:
Object
Object.toString()
@
// Code of Object.toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
A result such as com.foo.MyType@2f92e0f4
can therefore be explained as:
com.foo.MyType@2f92e0f4
com.foo.MyType
MyType
com.foo
@
2f92e0f4
The name of array classes look a little different, which is explained well in the Javadocs for Class.getName()
. For instance, [Ljava.lang.String
means:
Class.getName()
[Ljava.lang.String
[
[[
[[[
L
java.lang.String
Customizing the Output
To print something different when you call System.out.println(myObject)
, you must override the toString()
method in your own class. Here's a simple example:
System.out.println(myObject)
toString()
public class Person {
private String name;
// constructors and other methods omitted
@Override
public String toString() {
return name;
}
}
Now if we print a Person
, we see their name rather than com.foo.Person@12345678
.
Person
com.foo.Person@12345678
Bear in mind that toString()
is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString()
for our Person
class might be:
toString()
toString()
Person
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + "]";
}
Which would print, e.g., Person[name=Henry]
. That's a really useful piece of data for debugging/testing.
Person[name=Henry]
If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}
.
String toElegantReport() {...}
Auto-generating the Output
Many IDEs offer support for auto-generating a toString()
method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.
toString()
Several popular Java libraries offer this feature as well. Some examples include:
ToStringBuilder
from Apache Commons Lang
ToStringBuilder
MoreObjects.ToStringHelper
from Google Guava
MoreObjects.ToStringHelper
@ToString
annotation from Project Lombok
@ToString
Printing groups of objects
So you've created a nice toString()
for your class. What happens if that class is placed into an array or a collection?
toString()
If you have an array of objects, you can call Arrays.toString()
to produce a simple representation of the contents of the array. For instance, consider this array of Person
objects:
Arrays.toString()
Person
Person people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));
// Prints: [Fred, Mike]
Note: this is a call to a static method called toString()
in the Arrays class, which is different to what we've been discussing above.
toString()
If you have a multi-dimensional array, you can use Arrays.deepToString()
to achieve the same sort of output.
Arrays.deepToString()
Most collections will produce a pretty output based on calling .toString()
on every element.
.toString()
List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people);
// Prints [Alice, Bob]
So you just need to ensure your list elements define a nice toString()
as discussed above.
toString()
return String.format( getClass().getSimpleName() + "[ name=%s ]", name);
and really instead of name
it should use the getter getName()
(but getters were omitted in the Person class...) but if a getter was used ... return String.format( getClass().getSimpleName() + "[ name=%s ]", getName());
– CrandellWS
May 23 '16 at 5:55
return String.format( getClass().getSimpleName() + "[ name=%s ]", name);
name
getName()
return String.format( getClass().getSimpleName() + "[ name=%s ]", getName());
if i have two classes in java file then how to create object of class which is not public A.java public class A{ } class B{ } ------ C.java public class C{ A a = new A(); }
– yatinbc
Oct 10 '16 at 9:22
Note that there are overloaded versions of
Arrays.toString()
so you can use it for arrays of primitives too (int
, double
). Also Arrays.deepToString()
handles multidimensional arrays of primitives nicely.– Ole V.V.
Mar 9 '17 at 15:17
Arrays.toString()
int
double
Arrays.deepToString()
I think apache provides a better util class which provides a function to get the string
ReflectionToStringBuilder.toString(object)
This has the advantage that it doesn't require to edit the class, which is sometimes not possible. However, how can I recursively print nested objects too?
– lukas84
Mar 23 at 17:16
Every class in java has toString()
method in it by default, which is called by System.out.println()
if you pass some object of a class to it. When you try to print object of a class, the System.out.println()
method will call toString()
of the class which returns the className@hashcode of that object.
toString()
System.out.println()
System.out.println()
toString()
{
SomeClass sc = new SomeClass();
// Class @ followed by hashcode of object in Hexadecimal
System.out.println(sc);
}
You can override the toString method of a class to get different output. See this example
class A {
String s = "I am just a object";
@Override
public String toString()
{
return s;
}
}
class B {
public static void main(String args)
{
A obj = new A();
System.out.println(obj);
}
}
This is a well-put and short answer, but to clarify why OP is getting
[Lcom.foo.Person;@28a418fc
as output: that's the output of toString()
method, too, but of the one that is implemented in the class that is generated at runtime for the type Person
, not Person
(see stackoverflow.com/a/8546532/1542343).– gvlasov
Mar 24 '15 at 21:28
[Lcom.foo.Person;@28a418fc
toString()
Person
Person
This output means package.Class@Hashcode . The default toString() method has return type like. return Object.hasCode() or some similar return statement which is returning hashcode in hexadecimal form along with class name.
– Pankaj Manali
Mar 25 '15 at 14:03
In Eclipse,
Go to your class,
Right click->source->Generate toString()
;
toString()
It will override the toString()
method and will print the object of that class.
toString()
If you Directly print any object of Person It will the ClassName@HashCode
to the Code.
ClassName@HashCode
in your case com.foo.Person@2f92e0f4
is getting printed . Where Person
is a class to which object belongs and 2f92e0f4
is hashCode of the Object.
com.foo.Person@2f92e0f4
Person
2f92e0f4
public class Person {
private String name;
public Person(String name){
this.name = name;
}
// getter/setter omitted
@override
public String toString(){
return name;
}
}
Now if you try to Use the object of Person
then it will print the name
Person
Class Test
{
public static void main(String... args){
Person obj = new Person("YourName");
System.out.println(obj.toString());
}
}
In intellij you can auto generate toString method by pressing alt+inset and then selecting toString() here is an out put for a test class:
public class test {
int a;
char b;
String c;
Test2 test2;
@Override
public String toString() {
return "test{" +
"a=" + a +
", b=" + b +
", c='" + c + ''' +
", test2=" + test2 +
'}';
}
}
As you can see, it generates a String by concatenating, several attributes of the class, for primitives it will print their values and for reference types it will use their class type (in this case to string method of Test2).
By default, every Object in Java has the toString()
method which outputs the ObjectType@HashCode.
toString()
If you want more meaningfull information then you need to override the toString()
method in your class.
toString()
public class Person {
private String name;
// constructor and getter/setter omitted
// overridding toString() to print name
public String toString(){
return name;
}
}
Now when you print the person object using System.out.prtinln(personObj);
it will print the name of the person instead of the classname and hashcode.
System.out.prtinln(personObj);
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc
the Array type and it's hashcode.
[Lcom.foo.Person;@28a418fc
If you want to print the person names, there are many ways.
You could write your own function that iterates each person and prints
void printPersonArray(Person persons){
for(Person person: persons){
System.out.println(person);
}
}
You could print it using Arrays.toString(). This seems the simplest to me.
System.out.println(Arrays.toString(persons));
System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.
Arrays.deepToString(arrayOfObject)
Above function print array of object of different primitives.
[[AAAAA, BBBBB], [6, 12], [2003-04-01 00:00:00.0, 2003-10-01 00:00:00.0], [2003-09-30 00:00:00.0, 2004-03-31 00:00:00.0], [Interim, Interim], [2003-09-30, 2004-03-31]];
This only allows printing primitives, not the complex objects
– Tim
Nov 24 '17 at 18:11
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
You can use GSON library to convert object to json and vice versa. Very useful for debugging.
– Ashish Rawat
Aug 8 '15 at 2:07