Java Tutorial
Java For Loop
for packs init, condition, and step in one line. Use it when you know how many times to repeat.
Counted for
for (int i = 1; i <= 5; i++) sets i, checks the bound, then adds one after each pass.
Example
public class Main {
public static void main(String[] args) {
for (int n = 1; n <= 5; n++) {
System.out.println(n + " squared is " + n * n);
}
}
}for-each
for (int n : nums) walks every element. You do not get an index. Use it when you only need the value.
Example
public class Main {
public static void main(String[] args) {
int[] nums = {4, 17, 9};
for (int n : nums) System.out.print(n + " ");
System.out.println();
}
}When to pick which
Use the counted form when you need the index, or when the bound is a number you already know. Use for-each for arrays and lists when the index does not matter.
Watch the boundary. i < 5 runs five times (0,1,2,3,4); i <= 5 runs six. Getting this "off by one" wrong is the most common loop bug — decide up front whether the last number should be included.
Loop over the characters of a String
A counted loop plus charAt visits every character. Handy for counting, searching, or transforming text one letter at a time.
Example
public class Main {
public static void main(String[] args) {
String word = "banana";
int count = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') count++;
}
System.out.println(count); // 3
}
}Try It Yourself
Exercise: Print the sum of the numbers 1 to 100 using a single for loop.
Show solution
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
System.out.println(total); // 5050Note the i <= 100 — we want 100 included, so the loop stops after it, not before.
Key Takeaways
- The counted
forpacks init, condition, and step into one line — use it when you know the count. - for-each (
for (int n : nums)) is cleaner when you only need the values. - Mind the boundary:
<versus<=is the classic off-by-one.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Maths
Squares 1 to 5
A for loop is the right tool when the count is known. Each pass prints n and n².
Example
public class Main {
public static void main(String[] args) {
for (int n = 1; n <= 5; n++) {
System.out.println(n + " squared is " + n * n);
}
}
}