Methods in java

 Methods:

  • A method is a set of instructions that are used to perform specified tasks that repeatedly occur in the main program.
  • It helps to avoid duplication of work and also breaks down a large program into a number of small functions.
  • It is used to divide the complex task into a manageable task.

Syntax:

  1. return_type method_name (parameter-list)

    {

    .......................

    .......................

    }

Where,

  • Return_type – Data types.
  • Method_name – User-defined name.
  • Parameter-list – Parsing variables into methods.

Types of methods:

  • There are three types of methods used in java.

1. Methods that do not return anything and without any parameters.

2. Methods with parameters passed to them and returning.

3. Methods with parameters and that are returning data.

1. Java program without parameters and not returning data:

  1. package exampleprogram;

    import java.util.Scanner;

    public class Method_Example {

        int a,b;//Global variable

        void sum()

        {

            int c;//Local variable

            c=a+b;

            System.out.println("The sum of two element is :"+c);

        }

    }

     

    class main_method

    {

     public static void main (String args[]){

        Method_Example obj=new Method_Example();

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter two numbers : ");

        obj.a = sc.nextInt();

        obj.b = sc.nextInt();

        obj.sum();

        }

    }

Output:

2. Java program with parameters and not returning data:

  1. package exampleprogram;

    public class Method_Example {

        void sum(int a, int b) {

            int c;

            c = a + b;

            System.out.println("The sum of two element is :" + c);

        }

        public static void main(String args[]) {

            Method_Example obj = new Method_Example();

            obj.sum(10, 20);

        }

    }

Output:

3. Java program with parameters and returning data:

  1. package exampleprogram;

    public class Method_Example {

        int sum(int a, int b) {

            int c;

            c = a + b;

            return c;

        }

        public static void main(String args[]) {

            Method_Example obj = new Method_Example();

            int c = obj.sum(10, 20);

            System.out.println("The sum of two element is :" + c);

        }

    }

Output:
Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Blog Archive

Service Support

Need our help to Learn or Post New Concepts Contact me

Blog Archive

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me