Core Java Tutorial

Main  
 

Methods

It is also know as function.Methods in java are used to perform certain actions(operations).In general methods will decalre inside a class outside the main method.

      Syntax:
              modifier returntype method name(arg0, arg1,...argn){
                     .......
                 }

Here if your return type is void then it don't retun any value but if it is other dta type like int, String, double etc.. then that method should return particular return values corresponding to them.

      If return type is void then
            public class MethodsDemo{
                 public void mul(){
                 int b=5;
                 int c=b*b;
                  System.out.println("value of c is :"+c);
                 }
              public static void main(String[] args){
                  MethodsDemo methodDemo = new MethodsDemo();
                   methodDemo.mul(); // calling method
             }
           }

        If return type is int then
              public class MethodsDemo{
                 public int mul(){
                 int b=5;
                 int c=b*b;
                  System.out.println("value of c is :"+c);
                  return c;
                 }
                public static void main(String[] args){
                  MethodsDemo methodDemo = new MethodsDemo();
                   methodDemo.mul(); // calling method
             }
           }

Method Overloading

If two methods have same name with different paramaters(arguments) then it is amethod overloading concept.Using this concept you can use code again and again if you need to use(i.e code reusability is possible in method overloading).

       Ex:
          public class MethodOverloadingDemo{
               public static void main(String[] args){
               MethodOverloadingDemo methodOverloadingDemo = new MethodOverloadingDemo ();
                     methodOverloadingDemo.mul(4.6,7.8); // Method 2 will call
                     methodOverloadingDemo.mul(3,2);  // Method 1 will call
  }
          // Method 1 
          public int mul(int a, int b){
                 int c=a*b;
                  System.out.println("value of c is :"+c);
                  return c;
                 }
           // Method 2
           public double mul(double a,double b){
                 double c=a*b;
                  System.out.println("value of c is :"+c);
                  return c;
                 }
}

   Output: value of c is: 35.87999999995
   Output: value of c is: 6             
Main