Methods in Java

Method in Java is a block of code which performs a particular task when it gets executed. A method can be defined by   modifier  return-type  method name followed by parenthesis(), containing parameters. The following program shows a method FirstMethod() which takes no parameter and gets executed when it is called.

package com.company;

   public class Methods {

       static void FirstMethod() {
           System.out.println("Method is called");
       }

       public static void  main (String[] args) {
           FirstMethod();

       }
   }

Output:

Method is called

The following program shows method FirstMethod() with parameters ‘quote’ and ‘num’ and gets executed when it is called.

package com.company;

    public class Methods {

        static void FirstMethod(String quote, int num) {
        System.out.println(quote + " and integer num is " + num);
    }

        public static void  main (String[] args) {
        FirstMethod("Method is called", 3);
    }
}

Output:

Method is called and integer num is 3

A method when has the keyword static, it can be accessed without creating an object. However if a method does not have the keyword static then an  object of the class is required to access the method. The following program shows method FirstMethod(), which does not have the static keyword, so an object of the class is created to access this method.

package com.company;

    class Methods {
        
        public void FirstMethod(String quote, int num) { 
            System.out.println(quote + " and integer num is " + num);

        }

            public static void  main (String[] args) {

               Methods obj = new Methods();
               obj.FirstMethod("Method is called", 3);

            }
    }

Output:

Method is called and integer num is 3

A method returns a value with a  return keyword inside the method. The type of value the method returns should be used before the method name. If a method does not return a value, keyword void is used before the method name. 

The following program shows method FirstMethod() which returns an int value.

package com.company;

public class Methods {
    static int FirstMethod(int num1, int num2) {

        System.out.println("Numbers to be added are " + num1 + " and " +num2);
        return  num1 + num2;
    }
    public static void  main (String[] args) {

        System.out.println("After addition the value is " + FirstMethod(3,5));
    }
}

Output:

Numbers to be added are 3 and 5
After addition the value is 8
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments