Control Statements in Java

 In Java, control statements are used to alter the flow of execution in a program. They help in decision-making, looping, and branching. Here's a complete overview:


✅ Types of Control Statements in Java

Java control statements are mainly classified into:

  1. Decision-Making Statements

  2. Looping (Iteration) Statements

  3. Branching Statements


πŸ”Ή 1. Decision-Making Statements

a) if Statement

int num = 10;
if (num > 0) { System.out.println("Positive number"); }

b) if-else Statement

int num = -5;
if (num > 0) { System.out.println("Positive"); } else { System.out.println("Negative or Zero"); }

c) if-else-if Ladder

int score = 85;
if (score >= 90) { System.out.println("Grade A"); } else if (score >= 75) { System.out.println("Grade B"); } else { System.out.println("Grade C"); }

d) switch Statement

int day = 3;
switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Other day"); }

πŸ”Ή 2. Looping (Iteration) Statements

a) for Loop

for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i); }

b) while Loop

int i = 1;
while (i <= 5) { System.out.println("Count: " + i); i++; }

c) do-while Loop

int i = 1;
do { System.out.println("Count: " + i); i++; } while (i <= 5);

d) Enhanced for-each Loop (used with arrays/collections)


int[] nums = {10, 20, 30}; for (int n : nums) { System.out.println(n); }

πŸ”Ή 3. Branching Statements

a) break

Used to exit a loop or switch early.


for (int i = 1; i <= 10; i++) { if (i == 5) break; System.out.println(i); }

b) continue

Skips the current iteration and goes to the next.


for (int i = 1; i <= 5; i++) { if (i == 3) continue; System.out.println(i); }

c) return

Exits from the method and optionally returns a value.


public static int square(int x) { return x * x; }

πŸ“ Summary Table

CategoryStatementPurpose
Decision        if, else, switch        For making choices
Looping        for, while, do-while, for-each        For repeating tasks
Branching        break, continue, return        To alter loop/method flow

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism