|
home—info—labs—hws—exams
textbook—java.lang docs—java.util docs—archive
In elementary school, you might have learned “PEMDAS”, to remind you: Parentheses, Exponentiation, Muliplication, Division, Addition, Subtraction. In Java it's similar:
double tier2fee = (salePrice - 25) * 3 / 100 ; |
Habit of Programming: Whenever you use "/", think:
- Could the denominator ever be 0?
- Is this integer-division (quotient), or floating-point division?
What do you do if you have two ints, and you want to do floating-point division on them? Well, if you have int literals like 4 and 3, you could write 4.0 / 3.0. But what if you had two int variables, like numPizzas and numPeople?
The solution, is that we call a built-in function, to convert an int into a double. You'd think that the function might have a familiar signature, like double Integer.toDouble( int ). Alas, no such functions exist2. It turns out, that's not the case -- Java has a whole special syntax for calling this particular conversion function, called casting. You write (double) in front of the int expresion:
((double) numPizzas) / ((double) numPeople) |
Casting is the only time you use the name of a type even though you aren't introducing a new name to the Java compiler. It is conceptually annoying that Java has a whole special syntax just for this small set3 of conversion functions.
Java calls these conversion functions for you all the time, behind your back. For instance, Math.sqrt(25) is silently re-written as Math.sqrt( (double) 25 ), since Math.sqrt's documentation shows it requires a double as input.
Beware that casting from double to int can induce arithmetic errors (discussed below).
If (somehow) time allows: show motivation for how public-key-crypto can possible work.
2Well, they do, but they're not static, and they require new which we haven't talked about yet. And anyway, the built-in conversion functions are tedious to write: (new Integer( numPizzas )).doubleValue(). ↩
3 Well, we haven't talked about classes yet, but Java also lets you cast one class to another (not just numbers). However, casting classes is poor style; it indicates your program isn't correctly mirroring your real-world problem. ↩
home—info—labs—hws—exams
textbook—java.lang docs—java.util docs—archive
©2008, Ian Barland, Radford University Last modified 2008.Sep.29 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |