The return statement

The return statement is used to return from a method. A method can have either a return value of some type, or it can have a return type of void (which means it returns nothing).

If we want to return from a method that actually should return a value, the value is specified right after the return statement. The data type of the return value must match the data type in the declaration of the method.

Continue reading

The break statement

The break statement is used to terminate a loop or a switch / case statement. Normally, only the word break is used with a semi-colon after. This cancels the loop or the case statement in which the break statement is specified. This kind of statement is often used for example when looking for a specific value in a loop, and once it’s found we don’t want to continue to look for something that we already have. We just want to get out as quickly as possible.

Continue reading

Control flow statements – for loop

When it comes to iterate over a set of values ​​in Java the for loop is one of the most, if not the most, used approaches. A for loop begins with an expression that consists of three parts: initialization of a variable, termination – ie. for how long the loop should continue, and an incremental or decremental part that shows by how much the original value will increase or decrease each time in the loop.

This is an example of a for loop:

Continue reading

Control flow statements – Switch statement

There are similarities between the Switch statement and the if / else if statements but also a decisive difference. Unlike the if / else if statements that test for a condition to be true for every part of the statement, the Switch statement tests only a single value and offers different execution paths depending on its value. That single value can be of the following types:

Continue reading

Labeled statements

Labeled statements are useful when dealing with nested loops. For example, if you have one loop inside another and call ‘break’, which ends a loop, it is the inner loop that is exited.
However, if you also want to exit the outer loop you can label it and call ‘break’ with that label.
For example, consider these loops (see section about loops for more info):

Continue reading