Java return does weird things

  • A+

I have just started learning Java for university with some excercises. I am not new to programming, only to Java. I have followed all instrucions, but Java's return function does some really weird things. I have inserted some debug outputs to better understand the code. CMD.output of the program is included.

I thought that the function would terminate directly after return. But why does it not do in this case?

public class Rekursion {      public static void main(String[] args) {         int zahl = 10;         System.out.println("debugStart");         boolean even = isEven(zahl);         System.out.println("debugEnd");          if (even == true) {             System.out.println(zahl + " is even");         } else {             System.out.println(zahl + " is uneven");         }     }      public static boolean isEven(int n) {         System.out.println(n);         if (n > 1) {             System.out.println("debugx");             isEven(n - 2);         }          if (n == 0) {             System.out.println("debug1");             return true;         } else if (n == 1) {             System.out.println("debug2");             return false;         } else {             System.out.println("ERROR");             return false;         }     } } 

Output (cmd):

debugStart 10 debugx 8 debugx 6 debugx 4 debugx 2 debugx 0 debug1 

Program needs to stop here, normally. But it continues....

ERROR ERROR ERROR ERROR ERROR debugEnd 10 is uneven 


You should return the recursion call too,

 if(n>1){      System.out.println("debugx");      return isEven(n-2);//return at this point  } 

As you haven't returned your recursive calls are reaching else statements hence returning false.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: