Using For Loop
Part of the Fundamentals section of Coddy's Java journey — lesson 64 of 73.
Iteration means going through elements one by one in a sequence. With arrays, we can access each element systematically using different methods.
The most common way to iterate through an array is using a for loop:
String[] fruits = {"apple", "banana", "orange"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}Output:
apple
banana
orangeChallenge
EasyCreate a program that starts with an array of words, and prints a new array containing only the words longer than 5 characters
Reminder: to print an array use the
toString()function:System.out.println(Arrays.toString(arr));Check the hint if you are stuck.
Cheat sheet
To iterate through an array, use a for loop with an index variable:
String[] fruits = {"apple", "banana", "orange"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}To print an array, use Arrays.toString():
System.out.println(Arrays.toString(arr));Try it yourself
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String[] arr = text.split(",");
// Write your code below
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else