Statements
- Variable declaration:
int a;
- Value assignment:
a = 33;
- Combined declaration and assignment:
int a = 33;
- Expression:
a - 4
- Statement:
b = a - 4;
Notice the trailing “
;
”.
a = b + 3; b = a - 4;
Discouraged by good coding practices:
-
Poor readability
-
Hampers debugging
-
Variable being defined on class level.
-
Visible to all methods.
public class X { // Class variable static int i = 3; ◀━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ public static void main(String[] args) { ┃ System.out.println("main: i=" + i);━━━━━━━┫ someMethod(); ┃ } ┃ public static void someMethod() { ┃ System.out.println("someMethod: i=" + i);━┛ } }
-
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 } public static void someMethod() { int j = 3; System.out.println("j=" + j); int i = 17; // No conflict with i in main(...) System.out.println("i=" + i); } }
public static void main(String[] args) { double initialAmount = 34; { // first block final double interestRate = 1.2; // 1.2% System.out.println("Interest:" + initialAmount * interestRate / 100); } { // second block final double interestRate = 0.8; // 0.8% System.out.println("Interest:" + initialAmount * interestRate / 100); } }
|
|
No. 55
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 |