Thursday, August 7, 2014

Method without return statement in Java. Breaking method signature contract..

Caution : I'm just playing with java compiler and having fun. The below code demonstration is just for fun and do not try that in your Enterprise level code, so that you won't loose your job :P

*********************************************************************************

Have you ever tried to write a java method which has a return type and with out a return statement in implementation?? Let see a normal java method.

  public String getThatOwnerName() {  
     // TODO : find the owner somewhere  
     return "sureshatta";  
   }
That is a nicely compiled method and works perfectly return exactly what you want. Now another method
  public String getThatOwnerName() {  
     // TODO : find the owner somewhere  
     // I'm lazy. I wont return anything.  
   } 
In the above case, Compiler cries like anything and abuse you with a compile time error "This method must return a result of type String". But look at the below codes 

Example 1 :
   public String getThatOwnerName() {  
     while(true) {  
     }  
   }   
Example 2:
  public String getThatOwnerName() {  
     for(;;) {  
     }  
   }  

Hold on. Can you think how compiler reacts now ?? Surprisingly it allows you to do so and you can even use this method nicely with out any compilation errors though there is no return statement.

The idea is creating a never ending (infinite) loop before reaching to the last statement. Strange but true. Compiler is not dumb here, rather it's smarter than us :) . But why we are not getting any compilation error here ??. The reason is that compiler cries when it completely scan the method and when it reached to the end, that is the last statement of a method which is a end bracket (}) then and then only it  reacts about the missing return statement. Since we are placing a infinite loop, there is no way of that method reaching to the end and the code after that infinite loop is unreachable. So there is no compile time error and when you run that method it is never ends from that method.

Example 3:
  public String getThatOwnerName() {  
     throw new RuntimeException("ha ha");  
   }  

The idea here is throwing an exception without returning anything so the compiler thinks that this method is not completing normally and so there is no need to mention the return as well since you are facing issue in the middle of the method itself.


The rules for return statements in a method body are specified in §14.17.
If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

Yes. Compiler is genius than us.

3 comments: