This week's book giveaway is in the Java in General forum.
We're giving away four copies of Event Streams in Action and have Alexander Dean & Valentin Crettaz on-line!
See this thread for details.
Win a copy of Event Streams in Action 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
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

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: 579
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: 39396
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!