|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
Last time, we saw boolean operators for (resp.) and, or, not: &&, ||, !. We could then work out, step-by-step,
/* Three local variables -- declare and initialize */ boolean healthy = true; boolean wealthy = true; boolean wise = false; (healthy || wealthy) && wise healthy || (wealthy && wise) /* Same expression but w/o parentheses */ healthy || wealthy && wise |
Add explicit parentheses to (part of) the following if condition, without changing the meaning:
/** @return a message to stick in a fortune cookie */ String fortuneCookieMessage() { int cholesterol = 160; double netWorth = 23456.78; boolean startHomeworksEarly = true; if ((cholesterol < 200) && (networth > 1000000) || startHomeworksEarly) { return "You are happy."; } else { return "Life is bleak."; } } |
double tier2fee = (salePrice - 25) * 3 / 100 ; |
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 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
©2007, Ian Barland, Radford University Last modified 2007.Aug.27 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |