Scientech Easy Java methods | Method declaration | Calling methods in Java | Scientech Easy

Monday, August 27, 2018

Java methods | Method declaration | Calling methods in Java

In this tutorial, we will learn Java methods, method declaration, types of methods, and how to call the methods in Java from main? with example and programs in an easy way. We will also learn the purpose of using methods in the Java program with practical examples.

Methods in Java

A method is a set of code used to write the logic of the applications which perform some specific task. When a method is called, it returns the value to the caller. It can also perform a task without returning any value.
What is the purpose/use of the methods in Java?
The purpose of using methods in the Java program is to write the logic of the applications.
Let's see with a simple example.
Program source code 1In this example, we are performing addition of two numbers.
    class Addition{ // Declare the two instance variables int a=10; int b=20; System.out.println(a+b);// It is invalid syntax because inside the class we cannot write directly business logic of the application. Therefore, we declare the method inside the class and write the logic inside the methods. // Now declares one method. void add(){ // Write logic of adding two number and print it on the console. System.out.println(a+b); }
From the above program, it is clear that methods are used to write the business logic. (Remember this point).

Method declaration in Java

The methods must be declared inside the class. In general, methods have six fundamental parts such as modifiers, Method name, the return type, Parameter list, Exception list, and the body. The basic form to declare the method is:
method_modifiers   return_type   method_name(Parameter_list) throws Exceptions {
        // Method body 
   }
The method modifiers define the access type of the methods but it is optional to use. It may be static, final, abstract, synchronized, and one of the access modifiers private, default, protected, and public. If the method is abstract, the implementation is omitted and the method body is replaced with a single semicolon. 
The return type defines the type of data that comes back from the method after calling it.
The method name with the parameter list(number of parameters, type of parameters, and order of parameters ) is called the method signature
Examples of method signature are:
   add(int a, int b)
   m1(String name)
   sub()
The return type and exceptions are not part of the method signature. The method name should be functionality name related to logic.
The parameter list is a comma-separated list of zero or more parameter declaration. The basic form to declare the parameter list is:
        parameter-modifier   data-type  parameter-name
The parameter-modifier may be final. If the parameter is final, it cannot be modified inside the method. The data-type may be int, float, char, double etc. Each parameter-name must be a distinct name. If there is more than one parameter, they are separated by commas. If there are no parameters, you include an empty pair of parentheses (). 

The method parameter list makes it possible to pass the value to the method. It is declared inside the parentheses after the method name and the scope of the parameter list is inside the method body but these are optional. The method may contain zero parameters.
The exceptions may be thrown by the methods. In this case, you can specify these exceptions.

The method body is a block-statement which contain statements as well as the declaration of the local variables and local classes. The method body may also contain return statements. If the return type is void, the method will not return any value, and there will be no any return statement inside the method body. If the return type is non-void but a data-type like an int, float, double etc, the method will return a value. It will not be possible for execution to reach the end of the method body without executing a return statement.

Here are some examples of the method declarations.
➝ public void add(int a, int b) //add is the functionality name. It will execute whenever we will pass the input values of a and b. Once the functionality is completed, void represents don't return any value. The public is the access modifiers which represents that this method can be accessed from anywhere.
➝ private int m2() // here m2 is the functionality name with no arguments. Once the functionality is completed, it must return an integer value. The private access modifier represents that it can be accessed only within the class.
➝ protected int sub(int a) throws Exception. We will discuss more detail examples of the programs.

Types of methods in Java

Generally, there are two types of methods in Java but programmers can develop any kind of method depending on the scenario.
1. Instance method: Since instance is linked with an object. Therefore, it is memory allocated during an object creation and can be accessed using the object reference variable. 
Example of instance method declaration:
  void m1(){
       // This area is called an instance area/ Non-static area.
      // logic here.
   }
2. Static method: When you declare any method as static, it is called the static method. Since static is linked with class. Therefore, It is called using the class name. The static methods also load into memory during class loaded and before object creation. 
Example of static method declaration:
    static void m2(){
         // This area is called a static area.
        // logic here.
      }

Calling methods in Java

How to call a method in Java?
The process of calling a method is very simple. Just remember the below practical concept showing in the image. 
Java methods,methods in Java, method declaration, types of methods, how to call the methods in Java from main? with practical example and programs
Concept: Calling methods in Java
➲ There are two types of area in Java. First is the Instance area and second is the Static area. 
➲ If you call instance variables or instance methods from instance area within the instance area(same area),  you don't need to use object reference variable for calling instance variables or methods. You directly call it. 
➲ If you call instance variables or methods from the instance area within the static area (different area), you cannot call directly them. You will have to use object reference variables for calling them.
➲ If we call static variables or methods from the static area or instance area, we don't need to use the class name for calling the static members. We can invoke directly.
➲ When you want to call static variables and methods from the outside the class, the static members can be accessed by using the class name only. (Remember this point)
     
➲ When a program calls a method, the execution of control gets transferred to the called method. 
Let's consider an example:
Program source code 2:
    package callingMethodExample; public class Addition { // Instance area/Non-static area. // Declare the instance variables. int a=10; int b=20; // Declare static variables. static int c=40; static int d=50; // Declare instance method. void add(){ // Instance area/Non-static area. // within instance area, we can directly call the instance variables from instance area(Same area) without using object reference variable. System.out.println("First number a = " +a); System.out.println("Second number b = " +b); // logic of addition. int x=a+b; System.out.println("Addition of two numbers x = " +x); // directly called. // We can call directly static variables from instance area without using the class name. System.out.println("Third number c = " +c); // Since we are calling the static method from the static area within the same class. So we don't need to use the class name to call the static members sum(); } static void sum(){ // Static area. // We cannot call instance members/Non-static members within the static area.(Remember) System.out.println(b); // Invalid syntax. // You can directly call static members from the static area within the same class. System.out.println("Fourth number d = " +d); } public static void main(String[] args) { // Static area. // Create the object of the class. Addition ad=new Addition(); // Since we are calling the instance method from instance area within the static area. So Object reference variable will be used. ad.add(); sum(); System.out.println("Second number is:" +ad.b); } }
    Output: First number a = 10 Second number b = 20 Addition of two numbers x = 30 Third number c = 40 Fourth number d = 50 Fourth number d = 50 Second number b = 20
From the above program, One question arises which is asked by the interviewer in the interview.

Why cannot a static method directly access non-static members?

We cannot directly access non-static members from a static method. That is we cannot directly call instance members within static area because there is a logical concept behind such restriction. Since static members such as static variables, methods, or blocks are linked with the class and they get memory once when the class is loaded but non-static members like instance variables, method, or block get memory after the object creation of the class. Therefore, If we call any non-static members from the static area, it means that when the class is loaded, the static members also loaded and it will look for the non-static members which are not in existence because we have not created an instance till now. Hence there is the ambiguity. That's why we cannot call the non-static member from the static area.

Note: Non-static method can access static members in Java. we will discuss in the static tutorial.

Since a static method cannot access directly the non-static members but if we create the object of the class within the static method then, in this case, we can access non-static members within the static method.
Let's see a simple example.
Program source code 3:
    package callingMethodExample; public class Subtraction { int a=40; int b=50; void sub(){ int y=a-b; System.out.println("Subtraction of two number y = " +y); } static void subtract(){ // creating the object of the class within static area to call the instance members. Subtraction st=new Subtraction(); st.sub(); } public static void main(String[] args) { subtract(); } } Output: Subtraction of two number y = -10
Program source code 4: In this program, concepts are the same. Just remember the above points.
    public class Test { void m1(){ m2(); // Instance method calling. System.out.println("m1 method is calling"); } void m2(){ m3();// Static method calling. System.out.println("m2 method is calling"); } static void m3(){ System.out.println("static m3 method is calling"); } static void m4(){ System.out.println("static m4 method is calling"); } public static void main(String[] args) { Test t=new Test(); t.m1(); m4(); Addition.sum();// here we are calling static method using the class name from outside the class Addition of program source code 2 } }
    Output: static m3 method is calling m2 method is calling m1 method is calling static m4 method is calling Fourth number d = 50
How to call methods in Java?

As you can see the above image of the program 4, we are calling m1() method but m1() method is calling m2() and the control of execution goes to m2() but m2() is calling static m3() method. After completing of m3(), once again the control of execution goes to m2(). After completion of m2(), the control of execution again goes to m1(). After that, static m4() method is called and printing the message on the console. Now the control of execution goes to class Addition of program source code 2 for calling the static method. 

Final word:
I hope that we have covered almost all important topics in this tutorial with example and practical programs which are very important for the Interview. You always believe in practical knowledge, not theoretical knowledge. In the next tutorial, we will discuss how to pass parameter in methods with practical concepts?.

More on methods:
1. How to call a method with Parameters in Java?
2. Return type in Java from basic to project level.


Next ➝ How to call a method with Parameters? 



Popular