Statements
- Variable declaration:
int a;- Value assignment:
a = 33 * b;- Method invocation
System.out.println("Hello");
- Expression:
3 * (a - 4)- Statement:
b = 3 * (a - 4);Notice the trailing “
;”.
a = b + 3; b = a - 4;Discouraged by good coding practices:
-
Poor readability
-
Hampers debugging
-
Method scope being delimited by the { ... } block
-
A variable's visibility is restricted to its block:
public class X { public static void main(String[] args) { int i = 1; // Visible in current method System.out.println("i=" + i); someMethod(); // Method call } }
| Code | public static void main(String[] args) { double initialAmount = 500; { // first block final double interestRate = 2.0; // 2.0 % System.out.println(""First block interest:" + initialAmount * interestRate / 100"; } System.out.println("Second block"); { // second block final double interestRate = 1.0; // 1.0 % System.out.println("Second block interest:" + initialAmount * interestRate / 100); } } |
|---|---|
| Result | First block interest:10.0 Second block interest:5.0 |
|
|
No. 51
Blocks and variable glitches
|
Q: |
We consider: This code does not compile due to an “Variable 'a' is already defined in the scope” error. Why is that? Both definitions happen in different blocks. |
|
A: |
We do indeed have two blocks:
However the inner block is nested inside the main block and
thus inherits all variable declarations. It thus cannot redefine or
shadow variable |
| Code | |
|---|---|
| Result | Before: i = 1, j = 2 After: i = 2, j = 1 |
| Code | |
|---|---|
| Result | Before: i = 1, j = 2 After: i = 2, j = 1 |
No. 52
Cyclic variable permutation
|
Q: |
Extend Figure 145, “Swapping two variables using a block ” to perform a cyclic permutation of three variables:
|
||||
|
A: |
|
