Loops
Use loops to iterate through lists and repeat code.
StartKey Concepts
Review core concepts you need to learn to master this subject
For-each statement in Java
For-each statement in Java
// array of numbers
int[] numbers = {1, 2, 3, 4, 5};
// for-each loop that prints each number in numbers
// int num is the handle while numbers is the source array
for (int num : numbers) {
System.out.println(num);
}
In Java, the for-each
statement allows you to directly loop through each item in an array or ArrayList
and perform some action with each item.
When creating a for-each
statement, you must include the for
keyword and two expressions inside of parentheses, separated by a colon. These include:
The handle for an element we’re currently iterating over.
The source array or
ArrayList
we’re iterating over.
What you'll create
Portfolio projects that showcase your new skills
Fizz Buzz
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
The Prime Directive
Your prime directive: Use Java loops to find every prime number in an array.
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory