The if statement
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An if statement lets a program decide. It runs some lines only when a condition is true, and skips them when it is false.
The if statement
A college app must warn a student whose attendance is below 75%, but not one with 90%. An if statement asks a yes/no question, the condition, and runs the lines in braces { } only when the answer is true.
- Line 1: run only when the condition is true
- Line 2: always runs
Example 1 · Attendance warning
import java.util.Scanner;
public class AttendanceCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter attendance %: "); int attendance = sc.nextInt(); if (attendance < 75) { System.out.println("Warning: attendance below 75%"); } System.out.println("Attendance: " + attendance + "%"); sc.close(); }}Enter attendance %: 68 Warning: attendance below 75% Attendance: 68%
What this code does
68 < 75istrue, so the warning prints.- The last
printlnsits after the}, so it runs either way. - Run it again and type 90:
90 < 75isfalse, so Java skips the block and only the last line prints.
What can be a condition?
A UPI payment should go through only when the balance is enough. A condition must give true or false: a comparison such as balance >= amount (see Comparison operators (opens in a new tab)) or a boolean variable such as isMember.
Example 2 · A boolean as the condition
public class MemberPrice { public static void main(String[] args) { int price = 500; boolean isMember = true; if (isMember) { price = price - 50; System.out.println("Member discount: Rs 50"); } System.out.println("To pay: Rs " + price); }}Member discount: Rs 50 To pay: Rs 450
What this code does
isMemberis alreadytrueorfalse, so it is the whole condition.isMember == truewould only add words.- The block changes
price, and the line after the block prints the new value.
A number or a piece of text is not a condition: if (age + 1) stops with incompatible types: int cannot be converted to boolean.
Classify
Condition or not?
Tap an item, then tap where it belongs.
The block: lines that run together
A topper should see two lines, "Excellent" and "Scholarship form sent", and both belong to one decision. The lines inside { } form a block: Java runs the whole block or none of it.
Indent the block four spaces and always write the braces, even for one line. Common mistakes and practice (opens in a new tab) shows what goes wrong without them.
Trace the code
Watch which lines run
Variables
- marks
- 92
Output
(nothing printed yet)Line 3marks starts at 92.
if (marks >= 90); ends the if right there, so the block below runs every time.Next step
Check your understanding
7 quick questions