Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 210
The return Statement
ОглавлениеGiven that this book shouldn't be your first foray into programming, we hope you've come across methods that contain return
statements. Regardless, we cover how to design and create methods that use them in detail in Chapter 5, “Methods.”
For now, though, you should be familiar with the idea that creating methods and using return
statements can be used as an alternative to using labels and break
statements. For example, take a look at this rewrite of our earlier FindInMatrix
class:
public class FindInMatrixUsingReturn { private static int[] searchForValue(int[][] list, int v) { for (int i = 0; i < list.length; i++) { for (int j = 0; j < list[i].length; j++) { if (list[i][j] == v) { return new int[] {i,j}; } } } return null; } public static void main(String[] args) { int[][] list = { { 1, 13 }, { 5, 2 }, { 2, 2 } }; int searchValue = 2; int[] results = searchForValue(list,searchValue); if (results == null) { System.out.println("Value " + searchValue + " not found"); } else { System.out.println("Value " + searchValue + " found at: " + "(" + results[0] + "," + results[1] + ")"); } } }
This class is functionally the same as the first FindInMatrix
class we saw earlier using break
. If you need finer-grained control of the loop with multiple break
and continue
statements, the first class is probably better. That said, we find code without labels and break
statements a lot easier to read and debug. Also, making the search logic an independent function makes the code more reusable and the calling main()
method a lot easier to read.
For the exam, you will need to know both forms. Just remember that return
statements can be used to exit loops quickly and can lead to more readable code in practice, especially when used with nested loops.