Andy Malakov software blog

Friday, December 11, 2009

Old trap

I was puzzled why one of my objects had incorrect toString()

class Foo { 
private long id;
private String name;

Foo(
long id, String name) {
this.id = id;
this.name = name;
}

public String toString () {
return id + ' ' + name;
}
}


The statement new Foo(123, "Hello") prints something like "155Hello" instead of "123 Hello". Of course the reason is pretty simple:

 
public String toString2() {
return new StringBuilder().append(id + 32L).append(name.toString()).toString();
}