How to exit a method in Java

2 Answers

0 votes
public class MyClass {
   public static int sumNumbers(int[] array) {
        int sum = 0;
      
        for (int number : array) {
            if (number > 50) {
                return sum; // exit the method + return the sum
            }
            sum += number;
        }
      
        return sum; 
    }

    public static void main(String args[]) {   

        int array[] = {2, 5, 1, 96, 8, 0, 4, 7, 3};
      
        System.out.println(sumNumbers(array));
    }
}


   
   
   
/*
run:
   
8

*/

 



answered Nov 9, 2023 by avibootz
0 votes
public class MyClass {
   public static void printNumbers(int[] array) {
        int sum = 0;
      
        for (int number : array) {
            if (number > 50) {
                return; // exit the method
            }
            
            System.out.println(number);
        }
    }

    public static void main(String args[]) {   

        int array[] = {2, 5, 1, 96, 8, 0, 4, 7, 3};
      
        printNumbers(array);
        
        System.out.println("After printNumbers(array);");
    }
}


   
   
   
/*
run:
   
2
5
1
After printNumbers(array);

*/

 



answered Nov 9, 2023 by avibootz
...