Skip to main content

Java For Python Programmers Edition 2

Section 5.3 Summary & Reading Questions

  1. Java’s for loop syntax allows you to control loop initialization, condition, and update in one line using the format for (init; condition; update).
  2. To loop over lists or arrays in Java, the enhanced for-each loop uses the syntax for (type var : collection), which is similar to Python’s for item in list.
  3. Python’s range() function supports start, stop, and step, which directly maps to the three components of a Java for loop.
  4. Java also supports the while loop, which executes a block of code while a condition is true, similar to Python’s while loop.
  5. Java’s do-while loop guarantees the loop body executes at least once, because the condition is evaluated after the loop body.
  6. To iterate through characters in a Java String, use toCharArray() along with a for-each loop.

Reading Questions Reading Questions

1.

Which of the following is the correct format for a definite loop in Java that runs 10 times?
  • for i in range(10):
  • No, that is Python syntax.
  • for (int i = 0; i < 10; i++)
  • Correct! That’s the proper Java syntax for a definite loop.
  • loop i from 0 to 10
  • No, this is not valid syntax in Java.
  • for (i < 10; i++)
  • No, the initialization part is missing in this Java loop.

2.

Which loop correctly iterates through all elements in a Java array of integers?
  • for (int i : array)
  • Yes! This is Java’s enhanced for-each loop for arrays.
  • for (i in array)
  • No, that’s closer to Python syntax.
  • for (int i = 0; i < array; i++)
  • No, array is not a valid condition; use array.length.
  • foreach i in array:
  • No, this is not valid Java syntax.

3.

What is a unique characteristic of the Java do-while loop compared to the while loop?
  • It checks the condition before the loop body runs.
  • No, that describes a regular while loop.
  • It always runs infinitely.
  • No, a do-while loop will stop when its condition becomes false.
  • It guarantees the loop body runs at least once.
  • Correct! The do-while loop checks the condition after running the loop body.
  • It is not supported in Java.
  • No, Java does support do-while loops.
You have attempted of activities on this page.