Java & J2EE Page 2 - Conditionals, Expressions and Other Java Operators |
One last thing before we proceed: when it comes to operator precedence, there is a way to change it. Simply use parentheses(). When your program evaluates your statement, it will execute the part of your equation in parentheses() first. Like so... a = 5 * (1 + 2); This would result in the value of a being 15, whereas had we written the statement this way: a = 5 * 1 + 2; we would have received a result of 7. Because the brackets were not there, the program simply multiplied 5 times 1 (which equals 5), then added 2, for a total of seven. In the previous example, since the (1+2) was in brackets, it added those together first (equaling 3) and then multiplied that number by 5 (for a result of 15). Statements There are three types of statements in Java: Selection, Iteration, and Jump. Let's take a look at each one. Selection Statements There are two types of Selection Statements in Java. The first, which we previewed in the prior tutorial, is the If Statement. In simple terms, it states that if this happens, do that. int james = 10; int you = 2; if (james > you) you = 0; else james = 0; See what happens there? If the value of James is greater than the value of You, then your value becomes 0. If your value was greater than mine, my value would become 0. Sometimes you need to do more than one if statement within an if statement. Consider the code below: int james = 10; int you = 2; int your_daddy =3; if (james > You) { if (james > your_daddy) your_daddy = 0; else james = 0; //refers to the closest if } else james = 0; //refers to the original if In the code above, the program asks the question: Is James better than You? If so, it goes to the next if statement and asks if James is better than your daddy. If he is, it sets your daddy's value at 0. If not, it sets James value at 0. If James value had been less than yours, it would have skipped the comparison to your father, and changed James value to 0.
blog comments powered by Disqus |
|
|
|
|
|
|
|