Statements

Related slides on offer

Figure 130. Statements: General syntax Slide presentation

Statement's body terminated by ;

{statement};

Figure 131. Statement examples: Declaring and assigning variables Slide presentation
Variable declaration:
int a;
Value assignment:
a = 33;
Combined declaration and assignment:
int a = 33;

Figure 132. Expression vs. statement Slide presentation
Expression:
a - 4
Statement:
b = a - 4;

Notice the trailing ;.


Figure 133. Multiple statements per line Slide presentation
a = b + 3; b = a - 4;

Discouraged by good coding practices:

  • Poor readability

  • Hampers debugging


Figure 134. Debugging multiple statements per line Slide presentation
Debugging multiple statements per line

Figure 135. Class scope Slide presentation
  • 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);
      }
    }

Figure 136. Method local variable scope Slide presentation
  • 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);
      }
    }

Figure 137. Blocks Slide presentation
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);
  }
}
  • Defining scopes

  • Unit of work

  • if: Conditional block execution.

  • for / while: Repeated block execution.