Skip to main content
Contents Index
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 5.3 Summary & Reading Questions
Javaβs
for loop syntax allows you to control loop initialization, condition, and update in one line using the format
for (init; condition; update).
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.
Pythonβs
range() function supports start, stop, and step, which directly maps to the three components of a Java
for loop.
Java also supports the
while loop, which executes a block of code while a condition is true, similar to Pythonβs
while loop.
Javaβs
do-while loop guarantees the loop body executes at least once, because the condition is evaluated after the loop body.
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?
No, that is Python syntax.
for (int i = 0; i < 10; i++)
Correct! Thatβs the proper Java syntax for a definite loop.
No, this is not valid syntax in Java.
No, the initialization part is missing in this Java loop.
2.
Which loop correctly iterates through all elements in a Java array of integers?
Yes! This is Javaβs enhanced for-each loop for arrays.
No, thatβs closer to Python syntax.
for (int i = 0; i < array; i++)
No, array is not a valid condition; use array.length.
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.