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
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");
}
}
}
}
Top comments (0)