|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
In addition to naming intermediate calculations, we can also give name to constants in our program. For example,
double CRUST_WIDTH; // How much crust, all the way around the pizza. CRUST_WIDTH = 3.0; |
double PRICE_PER_SQ_IN; // Price in cents. PRICE_PER_SQ_IN = 3.0; |
double PI; PI = 3.14; |
The rules: Named constants are very similar to local variables:
heads up: We've introduced named constants as being declared in the same place as local variables (inside a function). We'll see next week that named constants are properly declared&initialized outside of a function.
What are the advantages of using such names? Discuss.
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 exist1. 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 set2 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).
1Well, 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(). ↩
2 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—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2008, Ian Barland, Radford University Last modified 2008.Feb.06 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |