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
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
Double doubleDouble(Double aDouble) {
return aDouble * 2;
}
Wow. That was fun to write.
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:
This homework is FAR from solved. There's still A LOT I have not simply given out to you yet.
From the description of your problem I can think of two easy ways to do this in Java:
Write a separate method for each primitive wrapper type (Double, Float, Long, etc) that returns the doubling of that value in the same type.
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.