RU beehive logo ITEC Department logo
ITEC 120
2007spring
ibarland,
jpittges

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect04a
arithmetic

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
What happens in the last case? This is actually reminiscent of 3+4*5 — where arithmetic (and Java) have a special rule: do all the multiplications-and-divisions (left-to-right), then go back and do all the additions-and-subtractions (left-to-right).

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.";
    }
  }

Arithmetic


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.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Aug.27 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme