0

How can I represent a value via an object(A custom value)

Hello, I would like to ask how to represent a value using object (I am not talking about referring the the object itself, but represent a custom value.)

This is one of the class that I found having a custom value

It is wrapper class. When I try to print a wrapper class object (Integer for example),it prints out the value that I stored in it.

package Testing;
public class test {
    static Integer one = 1;
    public static void main(String[] args) {
    System.out.println(one);
}
}

So, I create an Integer object, and when I print it, it prints the value that I stored in it.

So,

I wanted to understand how it work. Sorry if it is a build in feature (that can't be coded in regular java)
Thank you :)

Taco Meow
  • 3
  • 2
  • It is done by [overriding toString() method](https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java) – Ricky Mo Jan 04 '22 at 03:05

1 Answers1

1

I will tell you the internal logic about System.out.println().

this is println(Object o) method.

public void println(Object x) {
        String s = String.valueOf(x); // In summary, the output string in this line is determined.
        synchronized (this) {
            print(s);
            newLine();
    }
}

this is valueOf(Object o) method.

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString(); // Here you can see that obj's toString() method is called.
}

In summary, when you println() with an object, it prints according to the return value of the toString() method in the object.


Now, let's see your case about Integer class.

private final int value;

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

public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648"; // If integer is MinValue, the minimum value is returned as a string.
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true); // Creates a char array, assembles numbers, converts them to strings, and returns them.
}
윤현구
  • 467
  • 7
  • 19