Tutorials

Java Variables


Java Method Parameters


Parameter variables are the one that are passed as parameter in methods.

 

Most easiest example of parameter variable is String args[ ] variable in main method in java.


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

Example:


package variables;

public class parameter {

        public static void main(String[] args) {

          int firstNum = 10;
          int secondNum = 20;
                      
          add(firstNum, secondNum); //parameter variable passed
        }
           
        public static void add(int num1, int num2){ //parameter variable recieved

           int result = num1 + num2;
           System.out.println(result);

       }

}

How the above code works?

  • Two variables firstNum and secondNum is declared and assigned te value.
  • add method is called by passing both the variables firstNum and secondNum as parameters.
  • add method is declared with keyword 'static'. Reason is that add is called from within main method which is static in nature. So from within static method you cannot access any non-static method.
  • When add method recieves two parameters, it defines what kind of parameters it will accept. For example, this add method will receive two variables of integer data type.
  • Since add method is declared with return type void, so it will not return anything.
  • Two numbers will be added and its result will be stored in result variable which is also of integer data type.


Please Share this page
Views : 62