Consider the following Java method. What will be printed when testReturn() is called?
public class Test { public static int testReturn() { for (int i = 0; i < 5; i++) { if (i == 2) { return i; } } return -1; } public static void main(String[] args) { System.out.println(testReturn()); } }
Remember that return exits the method immediately.
The loop runs from 0 to 4. When i is 2, the method returns 2 immediately, so the output is 2.
What value does the method findFirstEven return when called?
public class Test { public static int findFirstEven(int[] numbers) { for (int num : numbers) { if (num % 2 == 0) { return num; } } return -1; } public static void main(String[] args) { System.out.println(findFirstEven(new int[]{1, 3, 5, 6, 8})); } }
The method returns the first even number it finds.
The first even number in the array is 6, so the method returns 6.
What error does this Java code produce when compiled?
public class Test { public static int test() { for (int i = 0; i < 3; i++) { if (i == 1) { return i; } } // Missing return statement here return -1; } }
Check if all code paths return a value.
The method must return an int on all paths. If the loop never returns, there is no return statement after the loop, causing a compilation error.
What does the following Java method print when called?
public class Test { public static int nestedReturn() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i * j > 2) { return i + j; } } } return -1; } public static void main(String[] args) { System.out.println(nestedReturn()); } }
Look for the first time i * j > 2 is true.
The first time i * j > 2 is true is when i=2 and j=2 (2*2=4 > 2). Then return 2+2=4. The output is 4.
What does this Java method print when called?
public class Test { public static int trickyReturn() { for (int i = 0; i < 3; i++) { try { if (i == 1) { return i; } } catch (Exception e) { return -1; } } return -2; } public static void main(String[] args) { System.out.println(trickyReturn()); } }
Consider if any exception is thrown inside the try block.
No exception is thrown, so when i == 1, the method returns 1 immediately.