Any orogramming language would be of little help if there were no control instructions. Basically, in Java, we have two types:

  • If statement
  • Switch statement

(IF) It works as it sounds. This instruction checks the condition and if it is true, instructions are performed in its body, if not, they are omitted. We can also use the word else, which will allow to execute other instructions in case the condition is false. The scheme looks like:

The if statements can be nested, just remember to close open bracket.

We also have instructions, if … else if …, the operation is similar, but it allows you to distinguish several cases.

In the above example, if condition1 is not met, the program will check the condition2. If both conditions are not meet, no method will be called.

The last example can also be changed into a more convenient way, which is convenient for example when creating a simple selection menu based on several numbers.

As a parameter, we give the integer, then the next cases are checked, if the number == 1 some instructions will be executed1, if the number == 2, then some instructions2 etc. Here, special attention should be paid to the break statement, which causes the execution of the case block to be aborted. Its omission will cause that all the instructions below will be executed, regardless of whether they will match the variable number or not. The default keyword followed the instructions to be executed if none of the cases matches the parameter. Placing the default block is not mandatory. You can imagine the switch statement like this:

Below is a practical example of using control instructions.

Under the variable int, we assign any number within the range. Then we check whether the result of dividing the modulo by this number by 2 results in 0, if so, we show the number is even, otherwise we display the opposite message. Then we check successively the number is greater than 10, or at the same time greater than 0 and less than or equal to 10, or is less than 0. In our example, the screen will show that the number is odd and positive less than or equal to 10. Check the behavior of the program with a different number.

In this example, we just check if the number is equal to 1 or 2, if not, we display a different message. After the default block, we do not need to place the break break.

LEAVE A REPLY

Please enter your comment!
Please enter your name here