Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

Working with methods

Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following class:
What will it print when compiled and run? It will not compile, if //1, //2, and //3 are commented out. I really do not understand this answer. I would kindly ask for a clarification.
Ranch Hand
Posts: 590
jQuery Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I remember reading an article which explained that in case of multiple methods having compatible data types, the one which accommodates the value closest (least bit size) would be selected.

By default, if you run the program, the output is
Here you get Integer because you already have a method with param type Integer.

Second result has more to do with the native value. As casting to an object with not be optimal, it selected the one with native data type.

If you comment out 1, 2, and 3, you get error as Integer/ int are not compatible with Long. They would not be justified also, even if it were allowed. The bit size would not be utilized properly for a value of lower bit size.

If you cast it, it might work or else keep the native long option available.

author & internet detective
Posts: 39997
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is an exact match, that one gets used. So if there was a method that took an int, b would use it. After that, it looks for types that can be widened. That's why long is picked. It doesn't look at autoboxing or varargs until after that "tie break".

Why you ask? Back in Java 4, autoboxing and varargs didn't exist. When java 5 was introduced, they didn't want the method called to change in the same scenario! So autoboxing and varargs "tie break" later in the order.
Do not threaten THIS beaver! Not even with this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic