Skip to main content

Control Statements in Java

 

A control statement in Java is used to control the flow of execution of a program.
It allows the program to make decisions, repeat tasks, or jump to specific parts of code based on certain conditions.

There are three main types of control statements in Java:

1.      Decision-Making Statements

2.      Looping (Iteration) Statements

3.      Jump Statements

 

 Decision-Making Statements

Decision-making statements allow a program to choose which block of code to execute based on a condition.

Types of Decision-Making Statements:

1.      if statement

2.      if-else statement

3.      if-else-if ladder

4.      nested if statement

5.      switch statement

 

 Simple if Statement

·         The if statement checks a condition.

·         If the condition is true, the block of code inside the if is executed.

·         If it is false, the code is skipped.

Syntax:

if (condition) {
    // code to execute if condition is true
}

Example:

public class Student {
    public static void main(String[] args) {
        int x = 1;
        int y = 12;
 
        if (x + y > 20) {
            System.out.println("x + y is greater than 20");
        }
    }
}

Output:

x + y is greater than 20

 

 if-else Statement

·         The else block executes when the if condition is false.

Syntax:

if (condition) {
    // executes when condition is true
} else {
    // executes when condition is false
}

Example:

public class Student {
    public static void main(String[] args) {
        int x = 10;
        int y = 12;
 
        if (x + y < 10) {
            System.out.println("x + y is less than 10");
        } else {
            System.out.println("x + y is greater than 20");
        }
    }
}

Output:

x + y is greater than 20

 

 if-else-if Ladder

·         Used when there are multiple conditions to check.

·         Only the first true condition’s block will execute.

Syntax:

if (condition1) {
    // executes when condition1 is true
} else if (condition2) {
    // executes when condition2 is true
} else {
    // executes when all conditions are false
}

Example:

public class Student {
    public static void main(String[] args) {
        String city = "Kathmandu";
 
        if (city == "Pokhara") {
            System.out.println("City is Pokhara");
        } else if (city == "Kathmandu") {
            System.out.println("City is Kathmandu");
        } else if (city == "Butwal") {
            System.out.println("City is Butwal");
        } else {
            System.out.println(city);
        }
    }
}

Output:

City is Kathmandu

 

 Nested if Statement

·         A nested if means an if statement inside another if or else block.

Syntax:

if (condition1) {
    if (condition2) {
        // executes when both are true
    } else {
        // executes when condition2 is false
    }
}

Example:

public class ElseIf {
    public static void main(String[] args) {
        String dist = "Rup";
        String village = "boadgaun";
 
        if (dist == "Kapilvastu") {
            System.out.println("District is Kapilvastu");
            if (village == "boadgaun") {
                System.out.println("Village is boadgaun");
            } else {
                System.out.println("Village is not inside Kapilvastu");
            }
        } else {
            System.out.println("District is not Kapilvastu");
        }
    }
}

 

 Switch Statement

·         Used when we have multiple options for a single variable.

·         It is easier than writing many if-else statements.

Syntax:

switch (expression) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    ...
    default:
        // default statements
}

Example:

class Weekdays {
    public static void main(String args[]) {
        int day = 8;
 
        switch (day) {
            case 1: System.out.println("Sunday"); break;
            case 2: System.out.println("Monday"); break;
            case 3: System.out.println("Tuesday"); break;
            case 4: System.out.println("Wednesday"); break;
            case 5: System.out.println("Thursday"); break;
            case 6: System.out.println("Friday"); break;
            case 7: System.out.println("Saturday"); break;
            default: System.out.println("Wrong Choice! Enter 1 to 7 only");
        }
    }
}

Output:

Wrong Choice! Enter 1 to 7 only

 

 Looping (Iteration) Statements

Loop statements are used to execute a block of code repeatedly while a condition remains true.

Types of loops:

1.      for loop

2.      for-each loop

3.      while loop

4.      do-while loop

 

 for Loop

·         Used when we know how many times to repeat a block of code.

·         Combines initialization, condition, and increment/decrement in one line.

Syntax:

for (initialization; condition; increment/decrement) {
    // statements
}

Example:

public class Calculation {
    public static void main(String[] args) {
        int sum = 0;
        for (int j = 1; j <= 10; j++) {
            sum = sum + j;
        }
        System.out.println("The sum of first 10 natural numbers is " + sum);
    }
}

Output:

The sum of first 10 natural numbers is 55

 

 for-each Loop

·         Used to iterate through arrays or collections easily.

·         We don’t need to use indexes.

Syntax:

for (data_type var : array_name) {
    // statements
}

Example:

public class Calculation {
    public static void main(String[] args) {
        String[] names = {"Java", "C", "C++", "Python", "JavaScript"};
 
        System.out.println("Printing the contents of the array:");
        for (String name : names) {
            System.out.println(name);
        }
    }
}

Output:

Java
C
C++
Python
JavaScript

 

 while Loop

·         Used when we don’t know how many times to run the loop.

·         It checks the condition before executing the loop body.

Syntax:

while (condition) {
    // statements
}

Example:

public class Calculation {
    public static void main(String[] args) {
        int i = 0;
        System.out.println("Printing first 10 even numbers:");
        while (i <= 10) {
            System.out.println(i);
            i = i + 2;
        }
    }
}

Output:

0
2
4
6
8
10

 

 do-while Loop

·         Similar to the while loop, but it executes the loop at least once before checking the condition.

·         It is known as an exit-controlled loop.

Syntax:

do {
    // statements
} while (condition);

Example:

public class Calculation {
    public static void main(String[] args) {
        int i = 0;
        System.out.println("Printing first 10 even numbers:");
        do {
            System.out.println(i);
            i = i + 2;
        } while (i <= 10);
    }
}

Output:

0
2
4
6
8
10

 

3. Jump Statements

Jump statements are used to transfer control from one part of the program to another.

Types of Jump Statements:

1.      break statement

2.      continue statement

 

 break Statement

·         It terminates the current loop or switch statement.

·         The control moves to the next statement after the loop/switch.

Example:

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 0; i <= 10; i++) {
            System.out.println(i);
            if (i == 6) {
                break;
            }
        }
    }
}

Output:

0
1
2
3
4
5
6

 

 continue Statement

·         It skips the current iteration and jumps to the next iteration of the loop.

Example:

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 0; i <= 2; i++) {
                if (i == 4) {
                    continue;
                }
                System.out.println(i);
            
        }
    }
}

Output:

0
1
2
3
5

Comments

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 2 Java

Data Types A data type defines the kind of data a variable can store, the operations that can be performed on it, and the amount of memory allocated. Java Primitive Data Types Data Type Size Range (Approx.) Example Byte 1 byte -128 to 127 byte a = 100; short 2 bytes -32,768 to 32,767 short s = 1000; Int 4 bytes -2,147,483,648 to 2,147,483,647 int num = 50000; Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long l = 100000L; float 4 bytes ~6–7 decimal digits float f = 5.75f; double 8 bytes ~15 decimal digits double d = 19.99; Char 2 bytes Single Unicode character char c = 'A'; boolean 1 bit* tru...