As you’ve learned in the sequential statements topic, the computer while running a java program, starts executing from the topmost line of the code. It reads the first line of the code, and continues doing so till the last line. Control statements help you run a program in a manner you define. These statements are used to change the computer’s control from reading and executing the statements in a given sequence to the way you define.
Control statements always base the program execution on a set of conditions. Let’s take an example of a programmer designing a program for a financial institute. The data for such programs is confidential and cannot be accessed by all the users. You would provide such an access to the user only if they provide the correct username and password. “Only” if both the passwords and the username are correct, should the program code allow them to see the records. The “else” part of code will run for people who don’t have valid password and enter incorrect information.
As you can see, the control statements help you check a certain condition. You can also put one control statement into another. Such statements are then known as nested control statements. In the example given above, the financial institute software provides 3 chances o each user. If the user enters incorrect information in all the three chances, their records are locked for a particular period. A sample algorithm that would help you design such a program is shown below:
Continue reading JAVA – Control Statements