Nearby lessons

22 of 125

Java - for Loop

📌 What You Will Learn
  • The small building blocks of Java: tokens
  • All 8 primitive data types with their ranges
  • Type casting — implicit and explicit
  • Control statements: if, switch, loops
  • Arrays — single, double and jagged
  • Variable length arguments (var-args)

for Loop is a core concept of the Java language. This lesson explains for loop and for Loop — Every Variation with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

for loop

Example01
JCode Cell
1for (start; condition; update) {
2 // body runs while condition is true
3}

for loop

Example02
JCode Cell
1class ForDemo {
2 public static void main(String[] args) {
3 for (int i = 1; i <= 5; i++) {
4 System.out.println(i + " * 2 = " + (i * 2));
5 }
6 }
7}
Output
1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 4 * 2 = 8 5 * 2 = 10

for Loop — Every Variation

The for loop is very flexible. All these forms are valid in Java:

Note: two declarations in the init need only one int: for (int i = 0, j = 0; ...) — int i=0, int j=0 is an error.

When to use `for`? When you know the number of iterations in advance.

Example03
JCode Cell
1for (int i = 0; i < 10; i++) // normal
2for (; i < 10; i++) // initialization outside
3for (int i = 0, j = 0; i < 10 && j < 10; i++, j++) // two variables
4for (int i = 0; ; i++) // no condition -> infinite (i++ runs)
5for (;;) // classic infinite loop
6for (;;) ; // empty body infinite loop
7for (int i = 0; i < 10;) { i = i + 1; } // update inside the body
📝 Key Takeaways
  • Tokens are the smallest pieces of a program: identifiers, literals, keywords, operators, separators.
  • Java has 8 primitive types: byte, short, int, long, float, double, char, boolean.
  • Widening casting is automatic and safe; narrowing casting needs brackets and may lose data.
  • if / switch decide which path runs; for / while / do-while repeat code; break and continue control loops.
  • Arrays hold many same-type values; index starts at 0; size is fixed; for-each loop reads them simply.
  • Var-args (int... x) lets a method take any number of arguments.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1