0% found this document useful (0 votes)
59 views10 pages

Java Loop Structures Explained

The document discusses different types of loops in Java including while, do-while, for, and for-each loops. It provides examples of how to use each type of loop and explains their syntax and purpose. Key details include: - A while loop will continuously execute a block of code as long as a specified condition is true. - A do-while loop is similar but will always execute the code block at least once before checking the condition. - A for loop allows looping a specified number of times by including an initialization, condition, and increment/decrement statement. - A for-each loop is used to loop through elements in an array in a simplified way compared to a traditional for
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views10 pages

Java Loop Structures Explained

The document discusses different types of loops in Java including while, do-while, for, and for-each loops. It provides examples of how to use each type of loop and explains their syntax and purpose. Key details include: - A while loop will continuously execute a block of code as long as a specified condition is true. - A do-while loop is similar but will always execute the code block at least once before checking the condition. - A for loop allows looping a specified number of times by including an initialization, condition, and increment/decrement statement. - A for-each loop is used to loop through elements in an array in a simplified way compared to a traditional for
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java While Loop

Loops

 Loops can execute a block of code as long as a specified condition is reached.

 Loops are handy because they save time, reduce errors, and they make code more readable.

Java While Loop

 The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {

// code block to be executed

Example 1

int i = 0; Output

while (i < 5) {

[Link](i);

i++;

Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:

Example
int i = 0;
do {

[Link](i);

i++;

while (i < 5);

Exercise:
Print i as long as i is less than 6..

int i = 1;

(i < 6) {
[Link](i);
;
}

Java For 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:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.


Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {

[Link](i);

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

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.

Example
for (int i = 0; i <= 10; i = i + 2) {

[Link](i);

For Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

Syntax
for (type variableName : arrayName) {

// code block to be executed

}
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

[Link](i);

Exercise:
Use a for loop to print "Yes" 5 times.

(int i = 0; i < 5; ) {
[Link]( );
}

Java Break and Continue

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.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

[Link](i);

}
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.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

[Link](i);

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example
int i = 0;

while (i < 10) {

[Link](i);

i++;

if (i == 4) {

break;

}
Continue Example
int i = 0;

while (i < 10) {

if (i == 4) {

i++;

continue;

[Link](i);

i++;

Exercise:
Stop the loop if i is 5.

for (int i = 0; i < 10; i++) {


if (i == 5) {
;
}
[Link](i);
}

Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link](cars[0]);

// Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

[Link](cars[0]);

// Now outputs Opel instead of Volvo


Array Length
To find out how many elements an array has, use the length property:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link]([Link]);

// Outputs 4

Loop Through an Array


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.

The following example outputs all elements in the cars array:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < [Link]; i++) {

[Link](cars[i]);

Loop Through an Array with For-Each


There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

Syntax
for (type variable : arrayname) {

...

}
The following example outputs all elements in the cars array, using a "for-each" loop:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

[Link](i);

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
A multidimensional array is an array containing one or more arrays.

To create a two-dimensional array, add each array within its own set of curly braces:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its 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:

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

int x = myNumbers[1][2];

[Link](x); // Outputs 7
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):

Example
public class MyClass {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < [Link]; ++i) {

for(int j = 0; j < myNumbers[i].length; ++j) {

[Link](myNumbers[i][j]);

}
}

Exercise:
Create an array of type String called cars.

= {"Volvo", "BMW", "Ford"};

Common questions

Powered by AI

Java determines the size of an array through the length property, which provides the total number of elements within an array . This property is crucial for iterating over arrays, as it defines the boundary condition for for loops. Using array.length ensures loops iteratively process from index 0 up to but not exceeding the last index, preventing out-of-bounds errors that can occur if one exceeds this length . This is demonstrated in examples such as iterating with for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); } . Properly leveraging array length ensures safe and complete iteration across elements.

In a while loop, variable incrementing is explicitly conducted within the loop body, typically at the end of the block to ensure the loop progresses towards the completion . For a do/while loop, the increment also occurs within the loop body, but since the body executes before the condition check, the placement of incrementing can determine whether the loop condition might be immediately true or false on the next check . In a for loop, the incrementing happens as part of its third statement, which executes after each iteration of the loop's body, inherently providing a structured approach for incrementing . This order of increment differs from while loops where control flow isn’t as explicitly tied to increment mechanics, offering a clearer increment path in for loops.

In a Java for loop, the three key components serve the following functions: Statement 1 is executed once before the loop starts and is generally used to initialize a counter variable ['int i = 0']. Statement 2 is the condition that defines whether the loop will continue to execute; it is evaluated before each iteration ['i < 5']. Statement 3 is executed at the end of each iteration after the code block has been executed, commonly used to increment the loop counter ['i++'].

Arrays in Java are declared by specifying the data type, followed by square brackets, and the array name, such as int[] or String[]. To initialize an array for a basic data type, an array literal can be used, where values are listed within curly braces, like int[] myNum = {10, 20, 30, 40} . For objects like Strings, the process is similar, using a list of String literals, e.g., String[] cars = {"Volvo", "BMW", "Ford", "Mazda"} . While both involve the same syntax, initializing arrays of objects may additionally involve constructors or new keyword under complex scenarios, unlike primitive types where literals suffice.

A while loop in Java executes a block of code as long as its condition is true, checking the condition before the code block's execution. This means if the condition is initially false, the code block will not execute at all . On the other hand, a do/while loop executes the code block once before checking the condition, ensuring that the code block is executed at least once, regardless of whether the condition is true or false on the first check . This difference affects their execution by determining whether the code block runs at least once or potentially not at all.

"Break" and "continue" statements serve distinct roles in both for and while loops. The "break" statement halts loop execution entirely, exiting the loop when a specified condition is met; it is used to stop processing entirely at a particular point, like exiting a loop when a match is found . On the other hand, the "continue" statement stops the current iteration and moves the control to the next iteration, skipping further execution of that specific cycle . For example, within a for loop, using continue might bypass printing a value but proceed to increment the counter and check the condition again . These control mechanisms offer significant flexibility and granularity in how loops are navigated.

The for-each loop offers several advantages over a traditional for loop when iterating through arrays. It is more concise and readable as it doesn't require a counter variable or the need to manually access array elements using an index . The for-each loop automatically iterates over each element in the array without needing to use the length property, reducing the likelihood of errors such as out-of-bound exceptions . This enhances code clarity and reduces complexity, especially beneficial for arrays where the iteration order is straightforward or every element needs processing.

A two-dimensional array in Java can be accessed and iterated over by specifying two index values: one for the array itself and another for elements within that array . For example, int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; accesses the third element of the second array with myNumbers[1][2], outputting 7 . Iterating over this array involves using nested for loops, where the outer loop iterates over the outer array and the inner loop over the inner arrays . An example is: for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } .

The break statement enhances control flow by allowing the program to exit a loop prematurely when a certain condition is met, which is useful for terminating a loop early, such as when a specific value is found . For example, in the for loop, it breaks out when i equals 4 . The continue statement, in contrast, skips the current iteration and proceeds to the next iteration of the loop . This is typically used to bypass certain iterations while continuing the loop, such as when skipping the iteration where i is 4 . Both are used for more granular control over loop execution flow.

In Java, array indices play a crucial role in both accessing and modifying elements, as each index points to a specific position within the array, facilitating direct element manipulation. For instance, accessing an element at index 0 or modifying it is done via cars[0] = "Opel", changing the first element from "Volvo" to "Opel" . Zero-based indexing, where the first element is at index 0, simplifies calculations related to element positioning and aligns with memory address computations, minimizing off-by-one errors . This approach offers consistency with many programming languages, promoting a standardized method to array handling.

You might also like