This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have David & Dawn Griffiths on-line!
See this thread for details.
Win a copy of Head First Android this week in the Android 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

how to write one method for more than one types of primitives

Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guys,

Suppose I have a method which prototype is
As you probably, understand, the method gets two integers and returns an int.

If I want to make this method work on two floats (and returns a float), I understand that I'll have to copy paste the implementation of the previous method and change 'int' to 'float'.
My question is: "Is there a way to write only one method that can be valid for both integeres and floats?".

Posts: 74354
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Depends what you want it to return. Don't create a method for floats. Don't use floats. If you really have to use floating‑point arithmetic use doubles.

If you create a method which takes two doubles it can return a double. You can pass ints and they will undergo widening conversion (sometimes called implicit casting) to doubles. But the method will return a double. You can cast that to an int but you may find you are outwith the range of an int and you get an extreme value, as described in the Java® Language Specification, but that bit is not easy to understand. Simply you might find you are rounded to 0 or Integer.MAX_VALUE or Integer.MIN_VALUE.

As they say in London, “You pays yer money and you takes yer choice.”
    Bookmark Topic Watch Topic
  • New Topic