public static void main(String[] args) {

        long sum = 0;
        for (int i = 1; i < 4000000; i++) {

            long fib = fib(i);
            if (fib > 4000000) {
                break;  // out of the for loop
            }

            // sum all even terms
            if (fib % 2 == 0) {
                sum += fib;
            }
        }

        System.out.println("The sum is = " + sum);
    }