Java-Arry Loop Break
Java-Arry Loop Break
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
Array Length
To find out how many elements an array has, use the length property:
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
There is also a "for-each" loop, which is used exclusively to loop through elements
in arrays:
Note: The example above can be read like this: for each String element (called i -
as in index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-
each method is easier to write, it does not require a counter (using the length
property), and it is more readable.
Multidimensional Arrays
Multidimensional arrays are useful when you want to store data as a tabular form,
like a table with rows and columns.
To create a two-dimensional array, add each array within its own set of curly
braces:
Access Elements
To access the elements of the myNumbers array, specify two indexes: one for the
array, and one for the element inside that array. This example accesses the third
element (2) in the second array (1) of myNumbers:
Note: Remember that: Array indexes start with 0: [0] is the first element. [1] is
the second element, etc.
We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):
Java Break and Continue
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Another Example
This example will only print even values between 0 and 10:
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements
in an array:
The following example outputs all elements in the cars array, using a "for-each"
loop: