Core JAVA || Conditions
2 min readJul 16, 2023
Conditional Statement: -
Conditional statements are essential for controlling the flow of your program based on conditions and making decisions at runtime. They allow you to create dynamic and flexible code that responds to different scenarios.
- If / If Else/ Nested If Else
- Switch Statements
If Else Statement
1. If
- The
if
statement is the simplest conditional statement and is used to execute a block of code only if a certain condition is true.
int num = 5;
if (num > 0) {
System.out.println("Number is positive");
}
2. If Else
- The
if
the statement will only execute the code inside theif
block if the condition inside the parentheses is true. If the condition is false, the code inside theelse
the block will be executed.
int num = 5;
if (num > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}
3. If-else if else
- The
if-else if-else
statement allows you to test multiple conditions and execute different blocks of code based on which condition is true.
int num = 5;
if (num > 0) {
System.out.println("Number is positive");
} else if (num < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
Switch Statement
A switch statement in Java is a multi-way branch statement. It allows you to execute different code depending on the value of a variable.
- You can have a default case at any place in the switch case. it is not mandatory to keep the default at the end.
- The
variable/expression
is evaluated, and its value is compared against eachcase
value within theswitch
statement. - If a
case
the value matches the value of thevariable/expression
, the corresponding block of code is executed. - The
break
a statement is used to exit theswitch
statement after executing the corresponding block of code. Without thebreak
a statement, execution will continue to the nextcase
until abreak
is encountered or theswitch
statement ends. - If none of the
case
values match the value of thevariable/expression
, the code within thedefault
a block is executed (optional). - After executing the code for the matching
case
, control is transferred to the statement immediately following theswitch
block.
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day: " + dayName); // Output: Day: Wednesday
char ch = 'a';
String vowelType;
switch (day) {
case 'a' , 'e', 'i', 'o', 'u':
vowelType = "Lowercase Vowel";
break;
case 'A', 'E', 'I', 'O', 'U':
vowelType = "Uppercase Vowel";
break;
default:
vowelType = "Not a Vowel";
break;
}
System.out.println("Type: " + vowelType);