Apex Vision AI

Your Genius Study Assistant

If Statements and Loops in Java If statements and loops are fundamental control structures in Java that allow you to control the flow of your program. If Statements An if statement lets you execute a block of code only if a specified condition is true.

AP Computer Science A

How do if statements and loops work in Java?

If Statements and Loops in Java

If statements and loops are fundamental control structures in Java that allow you to control the flow of your program.

If Statements

An if statement lets you execute a block of code only if a specified condition is true.

Syntax:
``java
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
`

Loops

Loops allow you to repeat a block of code multiple times. The most common types are for loops and while loops.

  • For loop: Used when you know how many times to repeat.
  • While loop: Used when you want to repeat as long as a condition is true.
  • For loop syntax:
    `java
    for (initialization; condition; update) {
    // code to repeat
    }
    `

    While loop syntax:
    `java
    while (condition) {
    // code to repeat
    }
    `


    Worked Example

    Problem: Print all even numbers from 1 to 10.

    Step 1: Use a for loop to iterate from 1 to 10.

    Step 2: Use an if statement to check if the number is even.

    Java code:
    `java
    for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { System.out.println(i); } }
    ``

    Explanation:

  • The loop variable $i$ starts at 1 and increases by 1 until it reaches 10.
  • The condition $i % 2 == 0$ checks if $i$ is divisible by 2 (even).
  • If true, $i$ is printed.

  • Takeaways

  • If statements execute code only when a condition is true.
  • Loops repeat code multiple times, either for a set number of iterations (for loop) or while a condition holds (while loop).
  • Combining if statements and loops allows for powerful, flexible program logic.
W

Walsh Pex

Walsh Pex is an educational technology specialist with over 8 years of experience helping students overcome academic challenges. He has worked with thousands of students across all education levels and specializes in developing AI-powered learning solutions that improve student outcomes.

Verified Expert
Last updated: January 27, 2026

Need More Help?

Get instant AI-powered answers for any homework question with ApexVision AI

Try ApexVision Free →