-3
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?

xlxs
  • 133
  • 1
  • 8

1 Answers1

12

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);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • If im correct Integer is a final class. Can methods of final classes get overriden ? – xlxs Nov 13 '16 at 16:14
  • @xlxs: You're correct that it's `final`, and no, the point of a final class is that it cannot be subclassed; since only subclasses can override methods, a final class's methods cannot be overridden. `Integer` overrides `Object`'s `toString` (`Number` is in-between them, but doesn't override `toString`), but `Integer`'s `toString` can't be overridden because it cannot be subclassed. – T.J. Crowder Nov 13 '16 at 16:20
  • Thank's for the help :) – xlxs Nov 13 '16 at 16:22