Java Control Statements Explained: if, else, switch and Loops (Beginner Guide)
Java Control Statements Explained: if, else, switch and Loops
Author: Gursehbaj Singh | Blog: DevMode
Control statements in Java decide the flow of program execution. They help your program make decisions and repeat tasks. In this post, we will learn if, else, switch, and all types of loops in a simple way.
1. if Statement
The if statement runs code only when a condition is true.
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
2. if-else Statement
int marks = 40;
if (marks >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
3. 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");
}
4. switch Statement
The switch statement is used when we have many choices.
int day = 2;
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
5. for Loop
Used when you know how many times to repeat.
for(int i = 1; i <= 5; i++) {
System.out.println(i);
}
6. while Loop
Runs while condition is true.
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}
7. do-while Loop
Runs at least once, even if condition is false.
int i = 1;
do {
System.out.println(i);
i++;
} while(i <= 5);
8. break and continue
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue;
}
System.out.println(i);
}
Common Mistakes
- Forgetting break in switch
- Infinite loops
- Wrong condition logic
Conclusion
Control statements are very important in Java. They help your program make decisions and repeat tasks. Once you master if-else, switch, and loops, you can write powerful and logical programs easily.
Comments
Post a Comment