By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
The for loop is a fundamental control structure in Java, enabling repetitive execution of code blocks. It comes in two forms: traditional and enhanced (for-each). Mastering both is crucial for efficient coding, especially in data processing and iterative tasks. Misunderstanding can lead to inefficient code, infinite loops, or runtime errors. For example, incorrectly using a for loop can cause performance bottlenecks in large datasets.
for (initialization; condition; update) { ... }
for (Type element : collection) { ... }
java for (int i = 0; i < 5; i++) { System.out.println(i); }
java int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println(number); }
java // Traditional for modifying elements for (int i = 0; i < array.length; i++) { array[i] = array[i] * 2; } // Enhanced for reading elements for (int num : array) { System.out.println(num); }
Experts view the traditional for loop as a tool for precise control over iteration, especially when index manipulation is required. They use the enhanced for loop for its simplicity and readability in scenarios where indexing is unnecessary. This dual perspective allows for efficient and maintainable code.
<
Question: Calculate the sum of all elements in an array.Solution:
int[] array = {1, 2, 3, 4, 5}; int sum = 0; for (int num : array) { sum += num; }
Answer: sum = 15Why it works: Enhanced for loop simplifies the summation process.
Question: Double each element in an array.Solution:
int[] array = {1, 2, 3, 4, 5}; for (int i = 0; i < array.length; i++) { array[i] = array[i] * 2; }
Answer: array = {2, 4, 6, 8, 10}Why it works: Traditional for loop allows index-based modification.
Question: Print each element in a list.Solution:
List<String> list = Arrays.asList("a", "b", "c"); for (String s : list) { System.out.println(s); }
Answer: Prints "a", "b", "c"Why it works: Enhanced for loop is ideal for simple iteration.
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.