Java Control statements - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Thursday, November 1, 2018

Java Control statements

Control statements in Java

A programming language uses control statement to control the flow of execution of a program. Java's program control statement can be categories in three: selection, iteration and jump.

Selection statement allows the different paths of execution based on outcomes of the expression or the state of variable.

Iteration statement allows execution to repeat the one or set of statements(block of code).

Jump statement allows program to run in non-linear fashion.

Java Control statements

Selection statement

Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s execution based upon conditions known only during runtime.

  1. if statement Read more »
  2. switch statement Read more »

Iteration statement

We call iteration statement as loops. Loop repeatedly execute the same set of instructions until termination condition is met. Java's iteration statement are:

  1. while loop Read more »
  2. do-while loop Read more »
  3. for loop Read more »
for loop in Java
Comparison while loop do while loop for loop
Introduction The Java while loop is control flow statement that control the execution of the programs repeatedly on the basis of given boolean condition. The Java do while loop is control flow statement that executes the program at least once and the further execution depends on given boolean condition. The Java for loop is control flow statement that iterates the set of instruction multiple times.
when to use If the number of iteration is unknown or not fixed, it is recommended to use while loop. If the number of iteration is not fixed and you must have to execute the set of code at least once, it is recommended to use do-while loop. If the number of iteration is known or fixed, it is recommended to use for loop.
Syntax
while (condition) {
// code to be executed
}
            
do {
// code to be executed
} while (condition);
            
for(initialization; condition; increment/decrement) {
// code to be executed
}
            
Syntax for infinite loop
while (true) {
// code to be executed
}
            
do {
// code to be executed
} while (true);
            
for (; ; ) {
// code to be executed
}
            
Example
int i = 0;
while (i <= 5) {
  System.out.println(i);
  i++;
}
            
int i = 0;
do {
  System.out.println(i);
  i++;
} while (i <= 5);
            
for (int i = 0; i <= 5; i++) {
  System.out.println(i);
}
            

We will also see the For-Each version of for loop and nested loops.

Jump statement

Jump statement transfer the control statement to another part of program. Java support three jump statements:

  1. break statement Read more »
  2. continue statement Read more »
  3. return statement Read more »

No comments :

Post a Comment