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 thisInteger
'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 thetoString(int)
method.Overrides:
toString
in classObject
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.