Conditions are used to control the flow of a program based on certain criteria. The most common way to express conditions is through the use of 'if'
, 'else if'
, and 'else'
statements. Additionally, Java provides the switch
statement for multi-branch conditions.
- if Statement
int number = 10;
if (number > 0) {
System.out.println("Number is positive");
}
- if-else Statement
int number = -5;
if (number > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}
- if-else if-else Statement
int number = 0;
if (number > 0) {
System.out.println("Number is positive");
} else if (number < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
- Switch Statement
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
default:
System.out.println("Invalid grade");
}
Комментариев нет:
Отправить комментарий