xlxs xlxs - 25 days ago 5
Java Question

Why it is possible to print "correctly" an Integer object in java?

Integer ki=new Integer("50");
System.out.println(ki);//Here I would expect to print the objects name something like package_name.Class@15db9742 but this didn't happen.
ki=3;//Here I would expect an error but this actually works.


When System.out.println(ki); executed then 50 appeared in the console but when I print other objects some thing like package_name.Class@15db9742 appears why 50 appeared instead of something like package_name.Class@15db9742?

I though ki is type Integer so when I assign the primitive value of 3 I should get an error but I didn't why?

Answer

You have two separate questions there:

System.out.println(ki);//Here I would expect to print the objects name something like package_name.Class@15db9742 but this didn't happen.

Because Integer overrides toString. Its implementation:

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

Hmm...or because println(int) exists on PrintStream.

Nope, it's calling System.out.println(Object), which then uses toString on the object. This is because (as the specification tells us) the rule is to first try to find a matching signature without auto-(un)boxing and without varargs; then just with auto-(un)boxing, then at last with both.

 ki=3;//Here I would expect an error but this actually works.

That's because of autoboxing: The Java compiler inserts the necessary code to take that primitive 3 and create an Integer instance for it. The bytecode it actually emits does this:

ki = Integer.valueOf(3);