Operator Precedence Operators Precedence: Expr++ Expr
Operator Precedence Operators Precedence: Expr++ Expr
Operators
Java operators produce new values from one or more operands. The result of most
operations is either a boolean or numeric value. All binary operators except for the
assignment operators are evaluated from left to right; assignment operators are evaluated
right to left.
Operator Precedence
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
multiplicative * / %
Additive +-
Shift <<>>>>>
Relational <><= >= instanceof
Equality == !=
logical AND &&
logical OR ||
Ternary ?:
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true.
For example, the Bicycle class could allow the brakes to decrease the bicycle's
speed only if the bicycle is already in motion. One possible implementation of
the applyBrakes method could be as follows:
void applyBrakes() {
// the "if" clause: bicycle
// must be moving
if (isMoving){
// the "then" clause: decrease
// current speed
currentSpeed--;
}
}
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps
to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:
void applyBrakes() {
// same as above, but
// without braces
if (isMoving)
currentSpeed--;
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make
the code more brittle. If a second statement is later added to the "then" clause, a common
mistake would be forgetting to add the newly required braces. The compiler cannot catch
this sort of error; you'll just get the wrong results.
The if-then-else Statement
The following program, IfElseDemo, assigns a grade based on the value of a test
score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
You may have noticed that the value of testscore can satisfy more than one
expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a
condition is satisfied, the appropriate statements are executed (grade = 'C';) and
the remaining conditions are not evaluated.
The switch Statement
Unlike if-then and if-then-else statements, the switch statement can have a
number of possible execution paths. A switch works with the byte, short,char,
and int primitive data types. It also works with enumerated types (discussed in Enum
Types), the String class, and a few special classes that wrap certain primitive
types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The following code example, SwitchDemo, declares an int named month whose
value represents a month. The code displays the name of the month, based on the value
of month, using the switch statement.
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes thestatement(s) in
the while block. The while statement continues testing the expression and executing
its block until the expression evaluates to false. Using thewhile statement to print the
values from 1 through 10 can be accomplished as in the following WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: "
+ count);
count++;
}
}
}
The Java programming language also provides a do-while statement, which can be
expressed as follows:
do {
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its
expression at the bottom of the loop instead of the top. Therefore, the statements within
the do block are always executed at least once, as shown in the
following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: "
+ count);
count++;
} while (count <= 11);
}
}
The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop
begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: "
+ i);
}
}
}
Notice how the code declares a variable within the initialization expression. The scope of
this variable extends from its declaration to the end of the block governed by
the for statement, so it can be used in the termination and increment expressions as well.
If the variable that controls a for statement is not needed outside of the loop, it's best to
declare the variable in the initialization expression. The names i, j, and k are often used to
control for loops; declaring them within the initialization expression limits their life span
and reduces errors.
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form
in the previous discussion of the switch statement. You can also use an
unlabeled break to terminate a for, while, or do-while loop, as shown in the
following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts =
{ 32, 87, 3, 589,
12, 1076, 2000,
8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0;
i < arrayOfInts.length;
i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found "
+ searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in
boldface, terminates the for loop when that value is found. Control flow then transfers
to the statement after the for loop. This program's output is:
Found 12 at index 4
The continue Statement
The continue statement skips the current iteration of a for, while , or do-
while loop. The unlabeled form skips to the end of the innermost loop's body and
evaluates the boolean expression that controls the loop. The following
program, ContinueDemo , steps through a String, counting the occurences of the
letter "p". If the current character is not a p, the continue statement skips the rest of
the loop and proceeds to the next character. If it is a "p", the program increments the
letter count.
class ContinueDemo {
public static void main(String[] args) {
String searchMe
= "peter piper picked a " +
"peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
// process p's
numPs++;
}
System.out.println("Found " +
numPs + " p's in the string.");
}
}
The last of the branching statements is the return statement. The return statement
exits from the current method, and control flow returns to where the method was invoked.
The return statement has two forms: one that returns a value, and one that doesn't. To
return a value, simply put the value (or an expression that calculates the value) after
the return keyword.
return ++count;
The data type of the returned value must match the type of the method's declared return
value. When a method is declared void, use the form of return that doesn't return a
value.
return;