Statements

Related slides on offer

Figure 157. 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 158. General Syntax Slide presentation Create comment in forum

Statement body terminated by ;

{statement};

Figure 159. 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 160. Expression vs. statement Slide presentation Create comment in forum
Expression
++a - 4
Statement
b = ++a - 4;

Notice the trailing ;.


Figure 161. 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 162. Debugging multiple statements per line Slide presentation Create comment in forum
Debugging multiple statements per line

Figure 163. 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.