What is a Conditional Statement:
-Conditional statements in Java are used to make decisions in a program. They allow the program to execute different blocks of code depending on whether a condition is true or false.
Types of Conditional Statements in Java:
- if Statement
- if-else Statement
- else-if Statement
- Nested if Statement
- Switch Statement
1.1 If Statement:
-This gets executed only when the given condition is true. If the condition is false, then the statement inside the if is completely ignored.
if(condition){
// code to execute if the condition is true
}
public class IfExample {
public static void main(String[] args) {
int number = 10;
if(number > 0){
System.out.println("Number is positive");
}
}
}
O/P: Number is Positive
2.1 What is If-else Statement:
-This would execute the statement if the condition is false
if(condition){
// if block
}else{
// else block
}
public class IfElseExample {
public static void main(String[] args) {
int number = -5;
if(number > 0){
System.out.println("Positive number");
}else{
System.out.println("Negative number");
}
}
}
3.1: Else if Statement:
- This statement is used when we need to check multiple conditions.
if(condition1){
// code
}else if(condition2){
// code
}else if(condition3){
// code
}else{
// default code
}
public class GradeExample {
public static void main(String[] args) {
int marks = 85;
if(marks >= 90){
System.out.println("Grade A");
}else if(marks >= 75){
System.out.println("Grade B");
}else if(marks >= 50){
System.out.println("Grade C");
}else{
System.out.println("Fail");
}
}
}
4.1: Nested if Statement:
- It means if statement inside another if.
public class NestedIfExample {
public static void main(String[] args) {
int age = 20;
boolean hasLicense = true;
if(age >= 18){
if(hasLicense){
System.out.println("You can drive");
}
}
}
}
5.1: Switch Statement:
-The switch statement is used to execute one block of code among many options.
- Once a matching case is found, execution starts from that case. If the break statement is not used, the program continues executing the following cases. This behavior is known as fall-through.
switch(expression){
case value1:
// code to execute
break;
case value2:
// code to execute
break;
case value3:
// code to execute
break;
default:
// default code if no case matches
}
public class SwitchExample {
public static void main(String[] args) {
int day = 2;
switch(day){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
O/P: Tuesday
Top comments (0)