An Overview of Java Statements: 4. 1. 2. Expressions
An Overview of Java Statements: 4. 1. 2. Expressions
Statement Control
4. 1. Statement
4. 1. 1. An Overview of Java Statements
4. 1. 2. Expressions
4. 1. 3. Declaring and defining multiple variables in a single statement
4. 1. 4. Label a statement block
4. 1. 5. Spreading a single declaration over several lines
4. 1. 6. How to write multiple assignments in a single statement
4. 1. 7. Combining both statements into one
4. 1. 8. Statement Blocks
4. 1. 2. Expressions
Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an
expression. However, this is a statement:
x++;
Statements can be grouped in a block. A block is a sequence of the following programming elements within braces:
statements
local class declarations
local variable declaration statements
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
4. 1. 6. How to write multiple assignments in a single statement
public class MainClass
{
public static void main(String[] argv)
{
int a, b, c;
a = b = c = 777;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Output:
777
777
777
4. 1. 8. Statement Blocks
You can have a block of statements enclosed between braces.
If the value of expression is true, all the statements enclosed in the block will be executed.
Without the braces, the code no longer has a statement block.
public class MainClass
{
4. 2. If Statement
4. 2. 1. The if statement syntax
4. 2. 2. Expression indentation for if statement
4. 2. 3. Using braces makes your 'if' statement clearer
4. 2. 4. Multiple selections
4. 2. 5. The if Statement in action
4. 2. 6. The else Clause
4. 2. 7. Nested if Statements
4. 2. 8. Using && in if statement
4. 2. 9. Using || (or operator) in if statement
if (booleanExpression)
{
statement (s)
}
or
if (booleanExpression)
{
statement (s)
}
else
{
statement (s)
}
For example, in the following if statement, the if block will be executed if x is greater than 4.
public class MainClass
{
public static void main(String[] args)
{
int x = 9;
if (x > 4)
{
// statements
}
}
}
In the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.
}
Consider the following example:
if (a > 0 || b < 5)
if (a > 2)
System.out.println("a > 2");
else
System.out.println("a < 2");
}
}
It is hard to tell which if statement the else statement is associated with.
Actually, An else statement is always associated with the immediately preceding if.
Using braces makes your code clearer.
if (a > 0 || b < 5) {
if (a > 2) {
System.out.println("a > 2");
} else {
System.out.println("a < 2");
}
}
}
4. 2. 4. Multiple selections
If there are multiple selections, you can also use if with a series of else statements.
if (booleanExpression1) {
// statements
} else if (booleanExpression2) {
// statements
}
...
else {
// statements
}
For example:
if (a == 1) {
System.out.println("one");
} else if (a == 2) {
System.out.println("two");
} else if (a == 3) {
System.out.println("three");
} else {
System.out.println("invalid");
}
}
if (a == 0) {
System.out.println("a is 0");
}
}
}
a is 0
4. 2. 7. Nested if Statements
public class MainClass {
} else {
System.out.println("a is not 0");
}
}
}
a is not 0
4. 3. Switch Statement
4. 3. 1. The switch Statement
4. 3. 2. The switch Statement: a demo
4. 3. 3. Execute the same statements for several different case labels
4. 3. 4. Free Flowing Switch Statement Example
4. 3. 5. Nested Switch Statements Example
4. 3. 6. Switch statement with enum
switch (expression) {
case value_1 :
statement (s);
break;
case value_2 :
statement (s);
break;
.
.
.
case value_n :
statement (s);
break;
default:
statement (s);
}
Failure to add a break statement after a case will not generate a compile error but may have more
serious consequences because the statements on the next case will be executed.
switch (choice) {
case 1:
System.out.println("Choice 1 selected");
break;
case 2:
System.out.println("Choice 2 selected");
break;
case 3:
System.out.println("Choice 3 selected");
break;
default:
System.out.println("Default");
break;
}
}
}
Choice 2 selected
switch(yesNo) {
case 'n': case 'N':
System.out.println("No selected");
break;
case 'y': case 'Y':
System.out.println("Yes selected");
break;
}
}
}
No selected
case 0:
System.out.println("i is 0");
case 1:
System.out.println("i is 1");
case 2:
System.out.println("i is 2");
default:
System.out.println("Free flowing switch example!");
}
}
}
/*
i is 0
i is 1
i is 2
Free flowing switch example!
*/
switch(ch) {
case Choice1:
System.out.println("Choice1 selected");
break;
case Choice2:
System.out.println("Choice2 selected");
break;
case Choice3:
System.out.println("Choice3 selected");
break;
}
}
}
Choice1 selected
4. 4. While Loop
4. 4. 1. The while Statement
4. 4. 2. Using the while loop to calculate sum
4. 4. 3. While loop with double value
4. 4. 4. Java's 'labeled while' loop
while (booleanExpression) {
statement (s)
}
statement(s) will be executed as long as booleanExpression evaluates to true.
If there is only a single statement inside the braces, you may omit the braces.
For clarity, you should always use braces even when there is only one statement.
As an example of the while statement, the following code prints integer numbers that are less than
three.
}
To produce three beeps with an interval of 500 milliseconds, use this code:
public class MainClass {
}
Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but
relies on the break statement to escape from the loop.
4. 5. Do While Loop
4. 5. 1. The do-while Statement
4. 5. 2. The do while loop in action
do {
statement (s)
} while (booleanExpression);
Just like the while statement, you can omit the braces if there is only one statement within them.
However, always use braces for the sake of clarity.
}
This prints the following to the console:
0
1
2
The following do-while demonstrates that at least the code in the do block will be executed once even
though the initial value of j used to test the expression j < 3 evaluates to false.
}
This prints the following on the console.
do {
sum += i;
i++;
} while (i <= limit);
4. 6. For Loop
4. 6. 1. The for Statement
4. 6. 2. For statement in detail
4. 6. 3. A loop allows you to execute a statement or block of statements repeatedly
4. 6. 4. The numerical for loop
4. 6. 5. Infinite For loop Example
4. 6. 6. initialization_expression: define two variables in for loop
4. 6. 7. Declare multiple variables in for loop
4. 6. 8. Multiple expressions in for loops
4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolons
4. 6. 10. Keeping the middle element only in for loop
4. 6. 11. Using the Floating-Point Values as the control value in a for loop
4. 6. 12. Nested for Loop
4. 6. 13. Java's 'labeled for' loop
4. 6. 14. Print out a Diamond
For example, the following for statement loops five times and each time prints the value of i. Note that
the variable i is not visible anywhere else since it is declared within the for loop.
}
The update statement is optional.
}
You can even omit the booleanExpression part.
}
If you compare for and while, you'll see that you can always replace the while statement with for. This
is to say that
while (expression) {
...
}
can always be written as
for ( ; expression; ) {
...
}
4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolons
public class MainClass {
int i = 1;
for (; i <= limit;) {
sum += i++;
}
System.out.println(sum);
}
}
55
4. 6. 11. Using the Floating-Point Values as the control value in a for loop
public class MainClass {
}
radius = 1.0area = 3.141592653589793
radius = 1.2area = 4.523893421169302
radius = 1.4area = 6.157521601035994
radius = 1.5999999999999999area = 8.04247719318987
radius = 1.7999999999999998area = 10.178760197630927
radius = 1.9999999999999998area = 12.566370614359169
System.out.print("\n");
}
System.out.print("\n");
}
}
}
/*
*
***
*****
*******
*********
*******
*****
***
*
*/
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
import java.util.ArrayList;
list.add(10.14);
list.add(20.22);
list.add(30.78);
list.add(40.46);
}
}
101.6
4. 7. 7. Iterating over Multidimensional Arrays: Use for-each style for on a two-dimensional array
public class MainClass {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
4. 8. Break Statement
4. 8. 1. The break Statement
4. 8. 2. Using the break Statement in a Loop: break out from a loop
4. 8. 3. Breaking Indefinite Loops
4. 8. 4. Labelled breaks breaks out of several levels of nested loops inside a pair of curly braces.
}
The result is
0
1
2
3
System.out.println(i);
if (i == 107) {
break;
}
}
}
}
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
4. 8. 4. Labelled breaks breaks out of several levels of nested loops inside a pair of curly braces.
public class Main {
public static void main(String args[]) {
4. 9. Continue Statement
4. 9. 1. The continue Statement
4. 9. 2. The continue statement: skips all or part of a loop iteration
4. 9. 3. The Labeled continue statement
4. 9. 4. Calculating Primes: using continue statement and label
}
37
try {
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { //
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
class LostException {
public static void main(String[] args) {
try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (YourException e) {
System.out.println(e.getMessage());
}
}
int b = 42 / a;
try {
if (a == 1)
a = a / (a - a); // division by zero
if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
4. 11. throw
4. 11. 1. Demonstrate throw.
4. 11. 2. Change Exception type and rethrow
class ChainDemo {
public static void main(String[] args) {
try {
someMethod1();
} catch (MyException e) {
e.printStackTrace();
}
}
4. 12. finally
4. 12. 1. Demonstrate finally.