Introduction
An if-else statement helps your program make choices. It runs one set of instructions if something is true, and another set if it is false.
An if-else statement helps your program make choices. It runs one set of instructions if something is true, and another set if it is false.
if (condition) { // code to run if condition is true } else { // code to run if condition is false }
condition is a question your program asks that can be true or false.{ } to group the code that runs for each case.age is 18 or more. If yes, it prints a voting message. Otherwise, it prints a different message.if (age >= 18) { System.out.println("You can vote."); } else { System.out.println("You are too young to vote."); }
score is above 50 to print a pass or fail message.if (score > 50) { System.out.println("You passed!"); } else { System.out.println("Try again."); }
This program checks if the temperature is above 25 degrees. It prints a message about the weather based on that.
public class Main { public static void main(String[] args) { int temperature = 30; if (temperature > 25) { System.out.println("It's hot outside."); } else { System.out.println("It's not hot today."); } } }
Always use == to compare values, not =, which assigns values.
You can add more choices using else if for multiple conditions.
If-else lets your program pick between two paths.
Use it to run code when a condition is true, and different code when false.
Remember to use curly braces to keep your code clear and organized.
if-else statement do in Java?int x = 10;
if (x > 5) {
System.out.println("Greater");
} else {
System.out.println("Smaller or equal");
}int num = 7;
if num > 5 {
System.out.println("Yes");
} else {
System.out.println("No");
}int n = 4; // Your code here
Pass the test and this pattern moves unknown