Statements

Related slides on offer

Figure 161. Purposes of statements Slide presentation Create comment in forum
  • Declaring variables and assigning values.

  • Creating output.

  • Control whether code will be executed.

  • Control how often code will be executed.


Figure 162. General Syntax Slide presentation Create comment in forum

Statement body terminated by ;

{statement};

Figure 163. Example: Declaring and assigning variables Slide presentation Create comment in forum
Variable declaration
int a;
Value assignment
a = 33;
Combined declaration and assignment
int a = 33;

Figure 164. Expression vs. statement Slide presentation Create comment in forum
Expression
++a - 4
Statement
b = ++a - 4;

Notice the trailing ;.


Figure 165. Multiple statements per line Slide presentation Create comment in forum
a *= 3; b = ++a - 4;

Discouraged by good coding practices:

  • Poor readability

  • Hampers debugging


Figure 166. Debugging multiple statements per line Slide presentation Create comment in forum
Debugging multiple statements per line

Figure 167. Blocks Slide presentation Create comment in forum
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.