Java if Statement
In this page:
Basic if Statement
An if statement evaluates its parenthesized boolean condition once; if it's true, the block that follows executes, and if it's false, Java skips straight past that block to whatever code comes next.
Example: Basic if Statement
public class Main {
public static void main(String[] args) {
int age = 20;
if (age >= 18) {
System.out.println("Condition was true - block executed");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Comparisons inside if Conditions
Double equals (==) inside a condition checks whether two primitive values match exactly -- a very common beginner mistake is writing a single = here, which is assignment, not comparison, and usually causes a compiler error for boolean contexts.
Example: Comparisons inside if Conditions
public class Main {
public static void main(String[] args) {
int x = 5;
if (x == 5) { // == is comparison; a single '=' here would be a compile error
System.out.println("x equals 5");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Logical AND (&&) inside if
Chaining conditions with && inside one if means every single one must evaluate to true for the block to execute -- if any single condition is false, the whole check short-circuits to false immediately.
Example: Logical AND (&&) inside if
public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasId = true;
if (age >= 18 && hasId) { // both must be true
System.out.println("Entry allowed");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Logical OR (||) inside if
Using || instead lets the block run if just one of several conditions holds, which is the right choice when you want to react to any one of multiple acceptable situations.
Example: Logical OR (||) inside if
public class Main {
public static void main(String[] args) {
boolean isAdmin = false;
boolean isOwner = true;
if (isAdmin || isOwner) { // runs if just one holds
System.out.println("Access granted");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Nested if Statements
Placing an if statement inside another if's block lets you ask a second, more specific question only once the first, broader condition has already been confirmed true -- useful for drilling down through layered eligibility checks.
Example: Nested if Statements
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) { // more specific question, asked only after the first passes
System.out.println("Can drive");
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: