1
Integer myInt = new Integer(10);
System.out.println(myInt);

This would give me back 10. But how? Every time I print out for example a custom Number object, which has a value, or any other object I get back something like: com.example.CustomNumber@14ae5a6

How can I achieve, to get the value as a number? Shall I Override something? I get it how it works with Strings, I'd simply override the toString method, but how does it work with numbers?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
dmbdnr
  • 334
  • 3
  • 19

2 Answers2

3

This would give me back 10. But how?

Integer class overrides the toString Method which is returning the int value of the object as String (that is what the System.out.println is receiving as parameter)

Exactly code of the ToString()

public String toString() {
    return toString(value);
}


public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}

to avoid this: com.example.CustomNumber@14ae5a6

you have to override the toString method and give something meaningfull for what is that for an object instead of the default hashcode...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
3

Shall I Override something?

Yes. As you said, you should override the toString() method.

How does it work with numbers?

The Integer class has simply overriden the toString() method, and thus, when calling println(myInt) this override get executed.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147