Computer Science

Java Enhanced For Loop

The Java Enhanced For Loop is a simplified way of iterating over arrays and collections in Java. It is also known as the "for-each" loop and allows for cleaner and more concise code. The loop automatically handles the indexing and iteration, making it easier to read and write code.

Written by Perlego with AI-assistance

3 Key excerpts on "Java Enhanced For Loop"

  • Book cover image for: Java Concepts
    eBook - PDF
    • Cay S. Horstmann(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    Then the loop body is executed. You should read this loop as “for each element in values”. This loop is equivalent to the following for loop and an explicit index variable: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; } Common Error 6.3 © John Bell/iStockphoto. Special Topic 6.2 You can use the enhanced for loop to visit all elements of an array or array list. Use the enhanced for loop if you do not need the index values in the loop body. 6.3 The Enhanced for Loop 305 Syntax 6.3 The Enhanced for Loop for (double element : values) { sum = sum + element; } An array or array list These statements are executed for each element. This variable is set in each loop iteration. It is only defined inside the loop. The variable contains an element, not an index. for (typeName variable : collection) { statements } Syntax Note an important difference between the enhanced for loop and the basic for loop. In the enhanced for loop, the element variable is assigned values[0], values[1], and so on. In the basic for loop, the index variable i is assigned 0, 1, and so on. The enhanced for loop is a convenient mechanism for traversing all elements in a collection. 15. What does this enhanced for loop do? int counter = 0; for (double element : values) { if (element == 0) { counter++; } } 16. Write an enhanced for loop that prints all elements in the array values. 17. Write an enhanced for loop that multiplies all elements in a double[] array named factors, accumulating the result in a variable named product. FULL CODE EXAMPLE Go to wiley.com/go/ javacode to download a program that demonstrates the enhanced for loop. © Nicholas Homr S E L F C H E C K 306 Chapter 6 Arrays and Array Lists 18. Why is the enhanced for loop not an appropriate shortcut for the following basic for loop? for (int i = 0; i < values.length; i++) { values[i] = i * i; } Practice It Now you can try these exercises at the end of the chapter: R6.7, R6.8, R6.9.
  • Book cover image for: Beginning Java Programming
    eBook - ePub

    Beginning Java Programming

    The Object-Oriented Approach

    • Bart Baesens, Aimee Backiel, Seppe vanden Broucke(Authors)
    • 2015(Publication Date)
    • Wrox
      (Publisher)
    for loop may be simpler to code and easier to read.
    Nesting for Loops
    As you saw with if-then statements, for loops can also be nested. The format is very similar, where one inner for loop is contained within another outer for loop. The general appearance is as follows:
    for (/*Initialization*/; /*Termination*/; /*Increment*/){ //outer loop /*execute these statements*/ for (/*Initialization2*/; /*Termination2*/; /*Increment2*/){ //inner loop /*execute these statements*/ } //close inner loop } //close outer loop
    Because the statements inside the inner for loop can refer to the iterator of both the inner loop and outer loop, it’s necessary to use different variable names in the initialization of each loop. You’ve probably noticed that many of the standard for loops shown in this chapter use
    x
    as the index name (and
    x = 0
    as the initialization); this is by no means required, but is often used in practice. Similarly,
    x
    and
    y
    are often used as index names in nested for loops. You will often encounter the use of nested for loops to iterate through a matrix of values. Here is an example of that type to demonstrate the use of nested for loops.
    Suppose you run a small business with three employees. You store the hours worked by each employee in a matrix like the one shown in Table 5.3 .
    Table 5.3
    Weekly Hours Worked by Employee
    EMPLOYEE MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY
    Chris 3 2 8 2 3
    Danielle 4 4 4 4 4
    Michael 5 5 0 5 5
    By using nested for loops, you can iterate through all the entries of this matrix, where the position (0,0), first row and first column, refers to the hours worked by Chris on Monday, and position (1,3), second row and fourth column, refers to the hours Danielle worked on Thursday. One for
  • Book cover image for: Big Java
    eBook - PDF

    Big Java

    Early Objects

    • Cay S. Horstmann(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    The enhanced for loop makes this process particularly easy to program. Here is how you use the enhanced for loop to total up all elements in an array named values: double[] values = . . .; double total = 0; for (double element : values) { total = total + element; } The loop body is executed for each element in the array values. At the beginning of each loop iteration, the next element is assigned to the variable element. Then the loop body is executed. You should read this loop as “for each element in values”. Return address Buffer for input (512 bytes) 1 Before the attack 2 After the attack Return address Overrun buffer (536 bytes) Malicious code A “Buffer Overrun” Attack You can use the enhanced for loop to visit all elements of an array. 7.2 The Enhanced for Loop 231 This loop is equivalent to the following for loop with an explicit index variable: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; } Note an important difference between the enhanced for loop and the basic for loop. In the enhanced for loop, the element variable is assigned values[0], values[1], and so on. In the basic for loop, the index variable i is assigned 0, 1, and so on. Keep in mind that the enhanced for loop has a very specific purpose: getting the elements of a col- lection, from the beginning to the end. It is not suitable for all array algorithms. In particular, the enhanced for loop does not allow you to modify the contents of an array. The following loop does not fill an array with zeroes: for (double element : values) { element = 0; // ERROR: this assignment does not modify array elements } When the loop is executed, the variable element is set to values[0]. Then element is set to 0, then to values[1], then to 0, and so on. The values array is not modified. The remedy is simple: Use a basic for loop.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.