Method with different parameters


Parameter less

In Java method when no parameter or argument passing is required, we will use parameter less method.

Program
public class Main 
{
  public void Show()
  {
    System.out.println("This is an example of parameter less method");
  }
  public static void main(String[] args) 
  {
    Main obj=new Main();
    obj.Show();
  }
}

Method with parameters

In Java, if we want to use parameters in the method, then we have to use the method with parameters. It can be integer, float, string or any data type.

Program
public class Main 
{
  public void Show(int a,int b)
  {
    int sum=a+b;
    System.out.println("Sum = "+sum);
  }
  public void Show1(float a,float b)
  {
    float sum=a+b;
    System.out.println("Sum = "+sum);
  }
  public void FullName(String a,String b)
  {
    System.out.println("Full Name = "+a+" "+b);
  }
  public static void main(String[] args) 
  {
    Main obj=new Main();
    obj.Show(10,20);
    obj.Show1(12.32F,10.9F);
    obj.FullName("chandan","payra");
  }
}


Passing object as a parameter to the method

In Java method we want to use the value of one object in another object then we can use the object as parameter.

Program
public class Main 
{
  int _a;
  int _b;
  public Main(int a, int b)
  {
    _a = a;
    _b = b;
  }
  public boolean Check(Main obj)
  {
   if(obj._a == _a && obj._b == _b)
      return true;
   else
      return false;
  }
  public static void main(String[] args) 
  {
    Main m1=new Main(10,20);
    Main m2=new Main(10,20);
    Main m3=new Main(20,30);
    
    System.out.println("m1 == m2 : " + m1.Check(m2));
    System.out.println("m1 == m3 : " + m1.Check(m3));
  }
}

Parameter as varargs in the method

In Java method we can use variable arguments or arrays of parameters when the size of the parameter list is large. But keep in mind that the parameter array or variable argument must be the last parameter in the parameter list.

Program
public class Main 
{
  public void Sum(int a,int b,int c,int d,int e)
  {
    int s=a+b+c+d+e;
    System.out.println("Sum = "+s);
  }
  public void SumWithArg(int ...args)
  {
    int s=0;
    for(int i: args)
     s+=i;
    System.out.println("SumWithArg = "+s);
  }
  public static void main(String[] args) 
  {
    Main m1=new Main();
    m1.Sum(1,2,3,4,5);
    m1.SumWithArg(1,2,3,4,5,6,7);
  }
}