Control Flow
Control flow in Java refers to the order in which the statements of a program
are executed. It dictates how a program makes decisions, repeats tasks, and
handles different scenarios dynamically, allowing for non-sequential execution
based on conditions.
Selection statements: in Java, also known as conditional or decision-making
statements, allow a program to execute different blocks of code based on
whether a specified condition evaluates to true or false.
1)- if statement: This statement executes a block of code only if a given
condition is true.
Syntax: if (condition) {
// Code to be executed if condition is true
}
Program :
import java.util.Scanner;
public class Mains{
public static void main(String [] args){
int age = 35;
if(age>18){
System.out.println("Adult");
2)- if-else, statement: In Java, if-else statements are fundamental control
flow constructs that allow a program to execute different blocks of code based
on whether a specified condition is true or false. This enables decision-making
within a program.
Syntax:
if (condition) {
// Code block to be executed if the condition is true
else {
// Code block to be executed if the condition is false
Program:
import java.util.Scanner;
public class Mains4{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter The Number");
int a = sc.nextInt();
if(a%2==0){
System.out.println("Number is Even");
else{
System.out.println("Number is Odd");
}
3)- Switch Statement: The switch statement in Java is a multi-way branch
statement. In simple words, the Java switch statement executes one statement
from multiple conditions.
Syntax:
switch (expression) {
case 1:
Statement 1;
break;
case 2:
Statement 2;
break;
// ... more cases
default:
Statement;
}
Program:
import java.util.Scanner;
public class Switch{
public static void main(String [] args){
int a=12, b=10, Num;
System.out.println("Enter Case Number");
Scanner sc =new Scanner(System.in);
Num=sc.nextInt();
switch(Num)
case 1:System.out.println("Sum:"+(a+b));
break;
case 2:System.out.println("Multi:"+(a*b));
break;