Tanzeel
Tanzeel

Reputation: 4998

What is the difference between a normal class object and a wrapper class object in java

Normally when I try to print an object using System.out.println();

class Car {
    String color = "red";
}

class Main {
    public static void main(String[] args) {
        Car car = new Car();
        System.out.println(car);
    }
}

The output is something like:

Car@677327b6

Which is its class name + '@' + hashCode. And internally it is calling the toString() method. This seems good. But what happens when I implement autoboxing as follows:

class Main {
    public static void main(String[] args) {
        int i = 100;
        Integer obj = i;
        System.out.println(obj);
    }
}

Here the output is 100. Why it is not like Main@hexcode? I thought I'm converting the primitive i to an object of type Integer. Please correct me.

Upvotes: 1

Views: 125

Answers (1)

John Kugelman
John Kugelman

Reputation: 361655

Class@hashCode is the default return value of Object.toString(). The Integer class overrides toString().

public String toString()

Returns a String object representing this Integer's value. The value is converted to signed decimal representation and returned as a string, exactly as if the integer value were given as an argument to the toString(int) method.

Overrides:
toString in class Object

Returns:
a string representation of the value of this object in base 10.

Upvotes: 4

Related Questions