Reputation: 4998
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
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 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.
Upvotes: 4