tags:

views:

111

answers:

3

a difficult one..

using classes of primitive types in java, like Integer, Float, Long, etc, write a code fragment using a method to double the value of a variable passed as an argument

+1  A: 

Just read the javadocs. It's really simple.

kalkin
+3  A: 
Double doubleDouble(Double aDouble) {
   return aDouble * 2;
}

Wow. That was fun to write.

See also


Update: People seems to think that with the above answer, I've done it ALL for OP, when in fact this is just the beginning. I would have rather OP discover the issues I'm covering in this next section on his own, but since many people seem to not realize it, I will explain it here for educational purposes.

Now, before you think that this homework is now "solved" and you can just substitute other types for Double, think again! You will find that the following does not compile:

Byte doubleByte(Byte aByte) {
    return aByte * 2;           // DOESN'T COMPILE!!!
}

In fact, you can go even further and try this, and it still wouldn't compile:

Byte doubleByte(Byte aByte) {
    return (Byte) (aByte * 2);  // STILL DOESN'T COMPILE!!!
}

Instead of explaining why and/or show you how to "solve" it, I will refer you to reading materials:

See also

This homework is FAR from solved. There's still A LOT I have not simply given out to you yet.

polygenelubricants
instead of giving the answer to homework, i might be more helpful to give a push in the right direction and allow the OP to figure out the answer on his/her own.
akf
@akf: This is a push in the right direction. He can't just substitute `Byte` for `Double`. He'd have to figure out how to do all the narrowing conversion etc.
polygenelubricants
I hope you're there for his next homework, otherwise you're doing a misservice.
OscarRyz
I think this exercise is actually related to the `Number` class and its utility methods.
Esko
@danben: `Byte b = anotherByte * 2;` doesn't compile! =)
polygenelubricants
+1  A: 

From the description of your problem I can think of two easy ways to do this in Java:

  1. Write a separate method for each primitive wrapper type (Double, Float, Long, etc) that returns the doubling of that value in the same type.

  2. Write a single method that takes a Number parameter and returns a Number that uses instanceof to determine the actual type and do the doubling.

Preference would be the first and rely on polymorphism; or you can do both with the second method using the first set to do the actual doubling.

Kevin Brock