Views: 339
Following are the control flow statements supported in Java, each statement is self explanatory with code sample.
if-then Statement
int age = 35;
if(age > 18) {
System.out.println("Adult");
}
if-then-else Statement
int age = 35;
if(age > 18) {
System.out.println("Adult");
}else {
System.out.println("Child");
}
if-then-else ladder
int age = 35;
if(age >= 18) {
System.out.println("Adult");
}else if(age < 18 && age >= 1){
System.out.println("Child");
}else {
System.out.println("Infant");
}
Switch
public class SwitchStatement {
public static void main(String[] args) {
int monthNumber = 11;
switch (monthNumber) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("Invalid Input, Choose between 1 & 12");
break;
}
}
}
while loop
int n = 1;
while (n < 5) {
System.out.println("Value: " + n);
n++;
}
do-while loop
int n = 1;
do {
System.out.println("Value: " + n);
n++;
} while (n < 5);
for loop
for (int i = 1; i < 5; i++) {
System.out.println("Value: " + i);
}
Enhanced for loop
Enhanced for loop is used to easily iterate over arrays or Lists in java
int[] numbers = { 1, 2, 3, 4, 5 };
for(int i : numbers) {
System.out.println("Value: " + i);
}
On By
FastFoodCoding
Top Tutorials
492.5K
32K
21.8K
18.7K
18.7K
6.7K
6.6K
4.9K
3.3K
3.1K
Top Questions
18.7K
14.5K
8.3K
6.6K
6.2K
5.7K
4.8K
4.8K
4.3K
3.9K
Top Articles
1.9K
1.6K
947
Top Blogs
796
778
54
Top News
752
683
670
397
383
381