Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Reviewing Java looping structures - Part 1

See in this article a review of the main Java looping structures.

The computer programming usually requires that the professional is able to accurately manipulate various structures, commands and features of programming languages. Among the various commands available one need to know those who manipulate and alter the execution flow of programs. Moreover, the looping structures are the main resource for the programmer to reuse several lines of source code.

This article aims to present a review of the main Java looping structures for those just starting to program in this programming language and is still becoming familiar with how to structure a program logically. The article discusses the concept of structures, their uses, implications, risks and also specific details of the syntax. This first part focuses on explaining what the looping structures are, and cover how to work with loop structure in Java by showing some examples.

Looping structures

Before we begin treating on the structures of repetition is important to properly understand a fundamental concept for any professional who wants to work with the Java programming language: the concept of execution flow.

The flow of execution is addressed early in the introductory courses in programming or logic for programming languages. A correct understanding of this concept is very important, because once the student knows well how to run the program it should be able to structure their algorithms based on a logical sequence of steps. Usually the presentation of algorithms, threads and sequence of steps are performed by means of systematic solutions to everyday problems, like changing a tire on a car, tasks to be performed after waking up, preparing a cooking recipe, etc. Figure 1 shows an early example of an algorithm in natural language that describes the steps to conduct a phone call at a pay phone booth.



Figure 1. Example of algorithm and its execution flow.

The algorithm presented in Figure 1 shows three major types of flow control: a) sequentially represented by steps 1 to 4, b) conditional branch, represented by steps 5 and 6, and c) Repetition, represented by step 6.1.

From the concept of execution flow and logical steps we can create several algorithms to solve a problem. As shown by the arrows in Figure 1, the sequential flow of execution can be changed by a conditional structure, as in step 5, or a looping structure. In general, three types of common execution flow (sequential, conditional and looping) found in an algorithm are shown in Figure 2, where the flows are represented by arrows.


Figure 2. Three possible types of flow of execution in an algorithm.

Although there are variations, such as the simultaneous execution of more than one flow at the same time in concurrent programming algorithms, the three arrows shown in Figure 2 show how the steps of an algorithm can be executed. Obviously, it is possible to combine and chain the three types of flows, but this article will focus only on the looping execution flow.

When we talk about programs is natural to implement the logic of the algorithm defined in a programming language, and this goes for how to control the flow of execution. The most widely used programming languages such as Java, rely on repetition structures to allow developers to reuse lines of code by repeating the flow of program execution. It is common to use the term loop to refer to a generic structure of repetition without getting into their internal details of operation, as the use of counting variables, limits, etc. By the way, the use of the term loop  is a reference to the loop structure of a roller coaster that makes its occupants perform full circle, or 360 degrees, as shown in Figure 3.



Figure 3. A 360° loop in a roller coaster.

Each programming language has control structures implemented by means of specific commands or keywords of the language such as: loop, while, for, do, do while, etc. Before starting to talk specifically about the commands of Java to implement a loop it is important to get a little hands off the keyboard and reflect on the importance, implications and consequences of the use of loop structures.

The main importance of a loop structure is code reuse. Loop structures can perform the same programming lineup more than once. This is a common practice found in many programming languages from on the most basic, such as assembly, to the latest language (or other ways to program the computer). In addition, you can also run several times the same line of programming with a slight variation on each run by using a counter that indicate what is the 'lap' of the loop you are in. This feature is very powerful and under a fundamental point of view the tiny speed with which the most current processors can execute instructions is what allows the computer to do the job and assist us in every task we perform through the use of software.

But here goes the old saying: "With great power comes great responsibility." If the programmer does not know how to use responsibly the 'power' of a repeating structure he may suffer serious consequences. Perhaps the most common consequence resulting from the incorrect use of a looping structure is known as infinite loop, i.e., the programmer does not specify the maximum amount of repetitions in the structure of repetition neither a possible condition for the loop to finish. Thus the program, in theory, will be repeating the same set of instructions indefinitely. In the early days of computer programming that really was a problem. Today there are many means, both the operating system and the environment in which the program is running, to avoid that an infinite loop consume all available computer resources (memory, processing, etc.).

The implications of the use of loop structures end up involving a very important area of theoretical computer: the analysis of algorithms which is the study of algorithms and its resource consumption associated with the performance. The loop structures directly affect the consumption of computer resources, be they related to memory, processing, or storage. There are now many theories and studies that address both ratings algorithms (quadratic, exponential, NP: nondeterministic polynomial, etc.) as well as techniques and algorithms that use less resources (divide and conquer, dynamic programming, probabilistic algorithms, etc.). Anyway, the correct use of loop structures can make the difference between a program that runs in a few seconds and a program that takes days, weeks or months to complete its execution.

It is worth mentioning that the use of a loop structure is usually accompanied by a data structure such as a list, matrix, array, arraylist, vector, or other internal structure of the programming language that allows the manipulation of various data types grouped. It is very common to use a repetition structure to traverse the elements of the data structure or to perform some operation for each element such as reads or writes on the values stored. Loop structures allow you to create blocks of code delimited that are often used in conjunction with the conditional structures in order to specify the maximum number of repetitions or to indicate that after a certain number of repetitions you need to do some set of instructions differently . The term iteration is used to indicate each cycle of the repeating structure in order to enumerate the number of times the block within the structure has been used. For example, if the flow of the program is in fifth iteration this means that the block of statements within the structure has been performed four times and this is the fifth execution of the block.

Loop structures in Java

After learning the theory of loop structures, we will see what are the main commands in Java that implement this feature. There are several variations of looping, but one of the simplest is represented by the while statement. This command requires a Boolean expression that is checked before each iteration begins. Note that the while statement does not have any kind of counter and if the programmer need an accountant he/she should implement it through an appropriate variable. Listing 1 shows an example of a Java program that uses a while statement. This program generates random numbers between 0 and 4 and the prints them on the screen while the random numbers generated are different from 0.

Listing 1. Simple example of the while statement in Java.

public class Random

{

  public static void main(String arg[])

  {

        int value = (int)(Math.random()*5);

 

        while(value != 0)

        {

          value = (int)(Math.random()*5);

      System.out.println("Value equals to: " + value);

        }

  }

}

 

In the example shown in Listing 1 the boolean expression used in the while statement is checked before the execution flow into the first iteration so that depending on the random number generated and stored in the variable value it is possible that no iteration is performed. Note that this example does not use a counter variable and the number of iterations actually performed by the program is uncertain until the time of execution. There are variations of the command while allowing the execution of at least one iteration, since the scan of the boolean expression is placed after the block of statements.

When the number of iterations of the loop structure is known or at least we have a notion of quantity it is recommended to use the for loop structure, which has an associated counter variable. One must indicate an initialization of this variable, the boolean expression to be checked before the start of each iteration and also the step that updates the counter variable. It is a common practice to  use a step increment or decrement represented by the unary ++ and -- operators, respectively, placed next to the counter variable. Listing 2 contains an example of a program that uses a counter as follows: when the number of parameters indicated in the program execution command in Java is greater than zero the program will display a score from 0 and going up to the number numerical value represented by the first parameter least one unit. Note that in this case, and in many situations where one uses a counter variable to traverse a data structure, the counter value starts at 0 and ends with the total number of elements of the data structure minus 1. The Listing 3 shows a simple example where the command is used to display the values contained in an array of integers. This example shows how the counting variable is used as array index within the block of code to be executed on each iteration.

 

Listing 2. Simple demonstration of the for command in Java.

 

public class ExampleFor

{

  public static void main(String[] args)

  {

 

        if (args.length > 0 )

        {

          for(int j=0; j

          {

        System.out.println("" + j + "");

          }

         

      System.out.println("End of the loop");

        }

        

    System.out.println("End of the program");

  }

}

                                                                                                   

Listing 3. Example of using the for command to go through a vector.

class ExampleFor2

{

  public static void main(String arg[ ])

  {

        int A[] = new int[3];

        A[0] = 50;

        A[1] = 100;

        A[2] = 150;

    System.out.println("Vector length = " + A.length);

        

        int counter;

        

        for(counter = 0; counter

        {

      System.out.println("index= " + counter + "  value= " + A[counter] );

        }

  }

}

 

A variation of the for statement in Java is the foreach command. Although the for keyword is present is often said that a loop is a foreach loop when we use the for structure without a numeric counter and exclusively to traverse elements of a typed data structure. Listing 4 shows an example of using the for command when it behaves as a foreach to cycle through all elements of a String data type stored in an array of strings in order to display them on the console screen. There are no major difficulties in this example, but more traditional programmers, especially those who already have a good experience in C/C + +, may take time to get used to this simplified version of the for command.

 

Listing 4. Use of the for command to traverse objects in the foreach style.

public class ExampleForeach

{

  public static void main(String[] args)

  {

        String[] names = { "John", "Mary", "Steve", "Joana" };

 

        for( String s : names )

        {

      System.out.println(s);

        }

  }

}

 

As Java is evolving new approaches were used to working with the looping structures, especially when using such a structure to traverse elements of a collection. One of the points to be highlighted and represents a major difficulty of understanding for those just starting out in Java is the use of the Iterator design pattern.

 

Design Pattern: Design Patterns describe solutions to recurring problems in the development of object-oriented software. A design pattern provides a name and define the problem, the solution, when applying this solution and its consequences. The design standards are intended to facilitate the reuse of design solutions,that is, solutions in the design phase of the software, regardless of code reuse. Also carry a common vocabulary of design, facilitating communication, documentation and learning of software systems.

 

This design pattern explores a standard solution to solve the following problem: how to build a loop with the command for generic objects that traverses a data structure without worrying about the data type's internal structure? The solution is to use a class that implements the Iterator interface and use the methods that generate a generic object. This object, whose data type is the Iterator interface will be used to fetch the objects of the data structure itself and also to control the number of iterations of the loop. Listing 5 contain a code snippet that shows how the Iterator design pattern can be used. This code is only an excerpt from an incomplete example, but the set of standard Java classes is filled with data structures that implement the Iterator design pattern.

 

Listing 5. Code snippet that illustrates the use of the Iterator design pattern.

ObjectGroup groupOfObjects = new ObjectGroup();

Iterator it = Iterator.iteratorFor( groupOfObjects ) ;

 

// The hasMore() method returns true if there are more elements or false otherwise

while ( it.hasMore() )

{

  // The current() method return a generic object that must be converted

  // to the data type of the member's collection

  Object obj = it.current();

  …

}

 

Another feature of the language related to the use of loops that presents difficulties for programmers who are new in Java is the use of generics. This feature was recently added to Java and is directly related to the data type of a collection and what it takes to go through this collection with a loop structure. The main motivation for the use of generic is the need to perform data type casting in the structure when it was necessary to gather the data collection. Thus there was a very high probability of the programmer makes a mistake, since the Java compiler does not check the data types at compile when using the casting. With the use of generic collections should be typed, i.e. they must use data structures that are not generic and already contain the correct type. Listing 6 shows a snippet of sample code which uses generics to scroll through a data structure.

 

Casting: Casting is the conversion of primitive types or objects from one type to another type. When dealing with casting, it is the need for explicit conversion between types - which potentially can cause loss of information. It is noteworthy that it is not mandatory to do a casting value of a primitive type to a higher primitive type, since this category of conversion is always permitted. It should be noted that in Java the casting of primitive types is applicable to all except the boolean type (for which, you can not make a casting of boolean for any other type and vice versa).

 

Listing 6. Code snippet that illustrates the use of generics.

// Gets the collection Farmer who owns chickens

Farmer McDonald =new Farmer(MyFarm);

 

// Gets the chickens have typed iterator interface to the object Chicken

Iterator chickens =McDonald.getChickens();

 

// The method hasNext() returns true if more elements or

/  false otherwise

while(chickens.hasNext())

{

  / / The next() method returns an object already typed as Chicken

  Chicken theChosenOne= chickens.next(); // no need for casting

  …

}

 

To sum up it is worth remembering that the use of a loop structure can also be represented in a UML sequence diagram. For example, Figure 4 shows how a loop that runs through all elements of a data structure is represented in the sequence diagram. The object called surrender is from the class OpenGLRender and, according to the diagram, during its life cycle is necessary to go through all the elements returned by the method models(). This loop is labeled 2:models foreach () in the diagram and is represented by an arrow coming out of the execution flow of the object and returning to itself. Note also that the specification of the loop in the life cycle of the object adds a new rectangle that is placed on the right side of the original rectangle that represents the flow of the life cycle of the object.



Figure 4. An example of how to represent a loop in a sequence diagram.

 

Figure 5 shows another sequence diagram that contains a reference to a loop. This time the object aCustomer, who represents a client in a video rental model, should make a loop to get all the items that are rented by the customer at some point in the life cycle of the object aCustomer. The loop is represented in the diagram by the arrow pointing to their own flow of execution and the text * [for all rentals]. Note that the examples of the diagrams of Figures 4 and 5 do not provide any indication as to which command, counter, object or data type must be used because the UML diagrams are used in a higher level of abstraction. The technical details used to implement the loop in Java that match what was modeled in the diagram must be handled directly by whom will write the source code.



Figure 5. Second example of a loop representation in a sequence diagram.

Conclusion

This article presented a short review of the concepts related to the structures of repetition of an algorithm and a program. The focus of this article was to present the concepts behind the repetitions in the flow of execution algorithms, followed by an explanation and details of some commands in Java that implement looping. The article also addressed the consequences and implications of the use of repetition structures, and ended with the presentation of three exercised for setting the content addressed in order to help readers who are beginning to program in Java. This first part explained what looping structures are, how to work with them in an algorithm and how to use looping structures in Java.


The second part contain three exercises about loop concepts in Java.



Mauro Pichiliani has the Master of Science degree on collaborative systems by the Aeronatics Institute of Technology (ITA) in Brazil. He is a specialist on database technologies with more than 8 years of experience on the industry...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login