Passing parameters to method in Java

Today in this post I am going to tell you how to pass parameters into methods and then how to call the method with parameters in Java with simple example code.

I am going to provide the example code and discuss how it works so that you will understand how to pass parameters to a method in Java.

To do it, let’s first create a Java file and name it as PassParamToMethod.java. Inside it, create a class that is same as the java file name just like below:

public class PassParamToMethod

{

               
}

Inside the class, we are going to create our main method and a public method.

   public static void main(String[] args)

   {


   }

   public static void mymethod(int a, int b)

   {


   }

You can see in the above code, we have set two parameters. Both of these parameters are of integer types. If you want to pass string then you have to define it as the string.

Now, to call the public method mymethod inside our main method we have to call the method like this:



public static void main(String[] args) 
   {
   	   mymethod(22, 563);
   }

The above code will execute the code that is inside the public method mymethod and takes the integer value a as 22 and b as 563.

Now suppose the public method is just like below that contains the code to print integer a and b:

public static void mymethod(int a, int b)
{
  System.out.println("The parameters are: "+a+" and "+b);
}

Then the output will be like below:

The parameters are: 22 and 563

Complete example code snippet of Passing parameters to method

The complete runnable code snippet is given below which show how to pass parameters to the methods in Java.

public class PassParamToMethod
{
   public static void main(String[] args) 
   {
   	   mymethod(22, 563);
   }
   public static void mymethod(int a, int b)
   {
     System.out.println("The parameters are: "+a+" and "+b);
   }	
}

If you run the above code, then you will get the output that is given below:

The parameters are: 22 and 563

Well, we have simply passed two parameters inside a public method and then called it in the main method. I hope you have understood the fundamentals of passing parameters to methods in Java programming.

Leave a Reply

Your email address will not be published. Required fields are marked *