Conditional statements
Conditional statements in a computer program support decisions based on a certain condition: if the condition is met, or “true,” a certain piece of code is executed. There are two main conditional statements used in Java: the if-then and if-then-else statements and the switch statement.
1. if-then Statement:
The if-then statement is used when you want to execute a block of code only if a specified condition is met.
Syntax:
if ( Statement ) {
// block of code
}
Example:
class KaloKalam{
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Number is positive.");
}
System.out.println("This statement is always executed");
}
}
The Output will be:
Number is positive.
This statement is always executed.
In this example, the code inside the if block is executed because the condition number > 0 is true. The second System.out.println statement is always executed, regardless of the condition’s outcome.
2. if-then-else Statement:
The if-then-else statement is used when you want to execute one block of code if a condition is true and another block of code if the condition is false.
Syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {
// Code to be executed if none of the conditions are true
}
Example:
public class KaloKalam {
public static void main(String[] args) {
int number = 10;
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.");
}
}
}
Output:
Number is positive.
In this example, if the condition number > 0 is false (because number is -5), the code inside the else block is executed. The last System.out.println statement is always executed.
These conditional statements allow your Java program to make decisions and execute different code paths based on the evaluation of conditions, enhancing the flexibility and functionality of your code.
3. Switch Statement
The switch statement provides an effective way to deal with a section of code that could branch in multiple directions based on a single variable.
Syntax:
switch ( single_variable ) {
case value:
//code_here;
break;
case value:
//code_here;
break;
default:
//set a default;
}
Example:
public class KaloKalam {
public static void main(String[] args) {
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;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("The day is: " + dayName);
}
}
Output:
The day is: Wednesday