简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM