Java Notes
A one-dimensional array is an ordered list of values. Learn traversal, updates, totals, maximum values, and safe indexed access in Java.
A one-dimensional array is a single ordered sequence of values. Java indexes it from 0 through length - 1. Use it for lists such as marks, prices, names, or daily readings.
Read values with an enhanced for loop
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The enhanced for loop gives you each value, but not its index. It is the clearest option when you only need to read values.
Use indexes when position matters
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The condition is index < marks.length, not index <= marks.length. The latter tries to access one position beyond the final element.
Calculate a total and average
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The cast to double prevents integer division. Without it, 311 / 4 would become 77 instead of 77.75.
Find the maximum value
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
This requires a non-empty array because it begins with marks[0]. For data that may be empty, check marks.length == 0 first.
What to remember
- Use enhanced
forwhen you only need values. - Use an indexed
forloop when position or updates matter. - The final valid index is
array.length - 1. - Cast before division when an average needs a decimal result.
Continue the lesson path