Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Method

• A method is a block of code which is designated to perform a specific task.
• In Java we use method to reuse the existing codes.
• We can’t declare a method inside any local context like inside another method or inside any block.
• A method gets its memory in the stack area as stack frame.
• A method gets its stack frame at the time of its invocation.
• The corresponding stack frame of a method is released automatically only after the method has been executed.

Syntax: -

<Access Modifier> <Return Type> <Method Name> (List of Parameters…){
Statement
}

Access Modifier: - An access modifier sets the scope of the method, it means using access modifier we define from where we can invoke or call the method and from where we can’t invoke it.

Return Type: - Return type defines the type of value a method returns to its caller. A return type value can be a primitive data type, an array, a user-defined data type, or a void.

When we declare a method with void, that method does not return any value to the caller. When we use a primitive data type as return type then the method returns a compatible value to the caller, and the same holds true for user-defined data type and array as well. A return type just defines the type of value that a method returns to its caller, it itself does not return any value. The function of the return statement (return) is to fetch a return value from a method to its caller. Whenever a return statement gets executed then simultaneously the control moves to the method caller along with the value that we configured with the return statement. When we use a return statement it is important to remember that a return statement must be able to return a value that is compatible with the return type otherwise we will get an incompatible type of error at compile time, and secondly a return statement must be the last statement inside the block otherwise we will get an unreachable statement error at compile time.

Method Name: - Method name is a simple java identifier which is basically used to identify a method. Since a method name is an identifier we need to follow the applicable rules.

List of a Parameter: - List of parameters is an optional part of the method, it means we can declare a method without a parameter, however it is important to know the significance of a method parameter. Generally, a parameter is basically used to issue inputs to a method at the time of its calling to perform some specific operation. In a method we can configure different types of parameters and we can define multiple numbers of parameters as per our business logic. When we define a method along with parameters then we need to issue the same argument list at the time of its calling.

When we invoke a method, the following rules have to be borne in mind: -

• Argument type must be same as the method parameter types.
• Number of arguments must be same as numbers of method parameters.
• The sequence of argument must be same as the sequence of its parameters.
• A parameter is a local variable of methods.

            
class JTC{
	public static void main(String arg[]){
		Method obj = new Method();
		obj.m1();
		int i1 = obj.m2();
		System.out.println("i1 :- "+i1);
		float avg = obj.average(10.23f,45.56f);
		System.out.println("avg :- "+avg);
	}
}
class Method{
	void m1(){
		System.out.println("m1 in Method class");
	}
	int m2(){
		System.out.println("m2 in Method class");
		return 10+20;
	}
	float average(float n1, float n2){
		System.out.println("average(float,float) in Method class");
		float sum = n1+n2;
		return sum/2;
	}
} 

        
    m1 in Method class
    m2 in Method class
    i1 :- 30
    average(float,float) in Method class
    avg :- 27.895
            

In the above program we have two classes- JTC class and Method class. First we will look into the method class where we have declared three methods- m1, m2 and average. In method m1 we can see that there are no parameters hence at the time of its calling from JTC class we cannot issue any argument; and since the return type of method m1 is void, no value is returned from m1 to its caller.
The next method in the method class is m2() which is declared along with int return type, so we can see that method m2 returns the result of 10+20 which is an int type of value. Using return statement to its caller we can get the return value of method m2 using int type of variable i1 in JTC class. The last method is average () in which we can calculate average as per the naming conventions. Since average (float, float) has two types of float parameters so we need to issue two float arguments at the time of calling and these are 10.23f and 45.56f which are used in the average method to calculate the average. As we can see that the return type of average() is a float, hence average result of 10.23f and 45.56f is returned to the caller of the method.

Types of Method: -
1. Instance Method (Non-Static Method)

• When we declare a method without static keyword, it is called an instance method.
• An instance method works on late-binding concept (is always related to an object) like other instance members.
• We can access instance and static member of their same classes from the instance method directly.
• Instance method works on late-binding hence it is a prerequisite to use its class object to invoke an instance method.

            
class JTC{
	public static void main(String arg[]){
		A a1 = new A();
		a1.m1();
		/*A.m1(); :- error :- at compile time*/
		A a2 = null;
		/*a2.m1() :- exception :- NullPointerException*/;
	}
}
class A{
	int a = 10;
	static int b = 20;
	void m1(){
		System.out.println("----m1 in A class----");
		System.out.println("a :- "+a);
		System.out.println("b :- "+b);
	}
}

        
    ----m1 in A class----
    a :- 10
    b :- 20
            

In this program we have a class A where we have declared an instance method m1. As we have discussed earlier, an instance method works on late-binding concept, that is why here we use an object of class A to invoke method m1 from class JTC. Since we are creating object of class A, hence we are able to use instance and static member of class A, which are int a = 10 and static int b = 20 respectively, from the m1() method directly.

Note: - An instance method is basically used to perform object specific service or execute a code which is dependent on the object.

            
class JTC{
	public static void main(String arg[]){
		Student s1 = new Student();
		s1.sid = 101;
		s1.sname = "Student-1";
		s1.semail = "student1@jtcindia.org";
		Student s2 = new Student();
		s2.sid = 102;
		s2.sname = "Student-2";
		s2.semail = "student2@jtcindia.org";
		s1.showDetails();
		s2.showDetails();
	}
}
class Student{
	int sid;
	String sname;
	String semail;

	void showDetails(){
		System.out.println("----Student Details----");
		System.out.println("Sid :- "+sid);
		System.out.println("Sname :- "+sname);
		System.out.println("Semail :- "+semail);
	}
}        
        
    ----Student Details----
    Sid :- 101
    Sname :- Student-1
    Semail :- student1@jtcindia.org
    ----Student Details----
    Sid :- 102
    Sname :- Student-2
    Semail :- student2@jtcindia.org
            

In the above example we have a class student where we are including particulars of Student like student id (sid), student name (sname) and student email (semail). Here we have an instance method which is showdetails() so as to print the student’s details, the student details are called objects of the class student. For example from the JTC class we have two different student class objects: Student s1 = new Student() and Student s2 = new Student() and using s1 and s2 we are invoking showDetails() method for the student classes. For the first invocation current working student class object is s1 (s1.showDetails()) so showDetails() prints the details of student s1. The same process also ensues with s2, the second object of the student class.

2. Static Method: -

• When we declare a method with static keyword, it is called static method.
• A static method works on early-binding concept (depends on the class loading).
• We can access only static member from the static method directly.
• In order to access any instance member from static method we will first have to create an object of that class.
• We can invoke a static method using three different ways: -

a. By using the class name.
b. By using the class reference variable that has null value.
c. By using the class object.

            
class JTC{
	public static void main(String arg[]){
		A.m1();
		A a1 = null;
		a1.m1();
		A a2 = new A();
		a2.m1();
	}
}
class A{
	int a = 10;
	static int b = 20;

	static void m1(){
		System.out.println("m1 in A class");
		/*System.out.println("a :- "+a);*/
		System.out.println("a :- "+new A().a);
		System.out.println("b :- "+b);
	}
}
        
    m1 in A class
    a :- 10
    b :- 20
    m1 in A class
    a :- 10
    b :- 20
    m1 in A class
    a :- 10
    b :- 20
            

In the above program we have a class A in which we have declared an instance variable int a = 10 and a static variable static int b = 20 and we have a static method m1(). Since it is a static method we are only able to directly access the static variable i.e. the static int b = 20; in order to access int a = 10, which is an instance type of variable, we use an object of class A. Second important thing which we should note here is that we are able to invoke a static method using: the class name, class reference variable of null value, and class object.

Method Chaining and Method Memory Management: -

When we are working with a method then it is essential to know about internal memory management of method.

Important aspects related to internal memory management of method are as follows: -

• Method gets its memory inside the stack area.
• Memory is allocated to a method inside the stack area only at the time of its invocation and this memory is also known as stack frame.
• Once the method execution gets completed, its corresponding stack frame is released from the stack area.
• Stack area works on last-In-first-out (LIFO) concept.

            
class JTC{
	public static void main(String arg[]){
		new A().m1();
	}
}
class A{
	void m1(){
		System.out.println("First - m1()");
		m2();
		System.out.println("Last - m1()");
	}
	void m2(){
		System.out.println("First - m2()");
		m3();
		System.out.println("Last - m2()");
	}
	void m3(){
		System.out.println("m3() in A class");
	}
}

        
    First - m1()
    First - m2()
    m3() in A class
    Last - m2()
    Last - m1()
            

In the above program three different methods i.e. m1, m2 and m3 are in class A. Out of the three declared methods first we invoke m1() from main method from m1() we invoke m2() and from m2() finally we are invoke m3().