In java if else statement is very important to understand
if else ladder is used to make decisions based on conditions .
//here is basic overview of how if else works
if(condition){
//block of code
}
//else if part will run if "if" condition is false
else if(condition){
//block of code
}
//else block will run if none of condition is true
else{
//block of code
}
here, "if" keyword used to make decisions and inside Parenthesis condition must be given to if condition is true it will execute the corresponding block of code
//here is a basic example
public class Main {
public static void main(String[] args) {
int num = 10;
// Check if num is greater than 0
if (num > 0) {
System.out.println("Number is positive.");
} else {
System.out.println("Number is non-positive.");
}
}
}
In above example if num is greater than 0 which is true so it will print Number is positive.
and if num is not greater than 0 it will check go in "else" block else block does not check any condition it means if non of then condition is true then else part of code will run and in this case it will print Number is non-positive.
//here is another example
public class Main {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}