• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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: 73977
332
  • 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.”
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic