Core JAVA || Conditions

Bhavik Vashi
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.

  1. If / If Else/ Nested If Else
  2. 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 the if block if the condition inside the parentheses is true. If the condition is false, the code inside the else 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.
  1. The variable/expression is evaluated, and its value is compared against each case value within the switch statement.
  2. If a case the value matches the value of the variable/expression, the corresponding block of code is executed.
  3. The break a statement is used to exit the switch statement after executing the corresponding block of code. Without the break a statement, execution will continue to the next case until a break is encountered or the switch statement ends.
  4. If none of the case values match the value of the variable/expression, the code within the default a block is executed (optional).
  5. After executing the code for the matching case, control is transferred to the statement immediately following the switch 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);

--

--