Tuesday, March 1, 2011

Return Statesment

I think you can remember the structure of the method. In previous posts I gave you a simple short note about the method. If you can not please refer this again.

Then you could understand the place where the return statement's take place in side a method. 
The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. In other words by using return statement , it is possible to terminate the execution of a method. 
Other important fact is return statement is the final line of a method structure. If there are lines after return statement , its gives compile error.

If your using return statement in a method you have to give return data type before method name. If there is no return statement you have to type void key word.
void means method not going to return anything. 

 By looking at this coding try to understand what I've mentioned.


Don't worry about modifiers I'll explain you later.  

Important
If a method has a return value, there are three ways to catch that return value in main method.
  1. By calling method inside a System.out.print(); (as given example).
  2. By assigning to a variable. (int x = m();
  3. By joining to a calculation. ( int y = 10 + m()).
If a method don't has a return value, (when return type is void) you can simply call the method by using method name with parenthesis.

Ex:

class Return{

     static void m(){
          System.out.println("No return value");
      }
      public static void main(String args[]){

           m();

     }

}  

If you call the method in this way when it has a return value ,it complies without errors. But we missed the return value.

class AA{

     static int m(){
          System.out.println("No return value");

         return 10;
      }
      public static void main(String args[]){

           m();

     }

}
 

see it didn't give you a compile error.


If there is a line after return statement it gives you compile error.

 
class AA{

     static int m(){
          System.out.println("No return value");

         return 10;
         
         System.out.println("Final line");

      }
      public static void main(String args[]){

           m();

     }

}




-Thank you-

No comments:

Post a Comment