Topic 5_Control Statement in Java
Topic 5_Control Statement in Java
Syntax of switch...case
How does the switch statement work?
switch (expression)
{
The expression is evaluated once and compared
case constant1:
with the values of each case label.
// statements
break; • If there is a match, the corresponding
statements after the matching label are
case constant2: executed. For example, if the value of the
// statements expression is equal to constant2, statements
break; after case constant2: are executed until break
. is encountered.
. • If there is no match, the default statements are
default: executed.
// default statements
}
Java Program Loops and Iteration
class Main {
if false if true public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println(i);
}
}
// Program to print a text 5 times using for Loop }
public static void main(String[] args) { // Program to find the sum of natural numbers
from 1 to 100.
// declare variables
int i = 1, n = 5; class Main {
public static void main(String[] args) {
// while loop from 1 to 5
int i = 1, n = 5;
while(i <= n) {
System.out.println(i); // do...while loop from 1 to 5
do {
i++; System.out.println(i);
} i++;
} while(i <= n);
} }
} }
Java break
Jump statements
The break statement ends the loop immediately
Jump statements change execution from when it is encountered.
its normal sequence.
Its syntax is:
When execution leaves a scope, all
automatic objects that were created in
that scope are destroyed. break;
Java continue
public static void main(String[] args) { public static void main(String[] args) {
// for loop
// for loop
for (int i = 1; i <= 10; ++i) {
for (int i = 1; i <= 10; ++i) {
// if value of i is between 4 and 9
// if the value of i is 5 the loop terminates
// continue is executed
if (i == 5) {
if (i > 4 && i < 9) {
break;
continue;
}
}
System.out.println(i);
System.out.println(i);
}
}
}
}
}
}