• 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 ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 38
1
  • 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?".

 
Marshal
Posts: 79239
377
  • 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.”
 
All that thinking. Doesn't it hurt? What do you think about this tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic