Method

Method

Method are use to perform some operation it contain set of instruction
to perform some operation

Syntax-

Modifier Returntype Methodname (argument);

Note:
In class you can define static or Non static method.

Advantage of Method

  • Re-usability
  • Decomposition
  • If you use method then your code became more readable and good.
Method argument

  • Used to pass some value in method
  • You can define multiple argument.
Sample Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Method
{
 
          static int b=13; //global
          public int k=12;//non static data member
 
 
          static void test()
             {
 
                 final int a=12; //local variable
                  System.out.println("running test method");
 
               }
 
 
           public static void main(String[] args)
 
            {
 
             System.out.println("*************************");
 
             System.out.println("b value"+b);
 
             test(); //calling static method test of same class
 
             System.out.println("*************************");
 
    }  
 
}
 
OUTPUT:
*************************
b value13
running test method
*************************

Passing argument in method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.spy.javaforlearn;
 
public class Method 
{
 
 
	//single argument method
	public void Test(int a)
	{
 
		System.out.println("Running single arg method");
 
	}
 
 
	//multi argument method
	public void run(int a,int b)
	{
		System.out.println("running multi arg method");
 
	}
 
 
	public static void main(String[] args) 
	{
 
		Method ref=new Method();
 
		//calling single arg method
		ref.Test(10);
 
 
		//calling multi arg method
		ref.run(10, 20);
 
	}
 
 
}

Leave a Reply

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