Methods in Java

by | Aug 7, 2021 | Java

Home » Java » Methods in Java

Methods in Java

Methods in Java, sometimes also referred to as functions, is a conglomerate of statements that when executed performs a certain task and returns the output of the task to the statement that calls the method. Although, methods can have return types, this is not a mandate. A method in Java can perform certain tasks without returning any value. Once a method has already been created, this allows us to reuse that bit of code upon requirement by just invoking the method in the driver class. A hard rule for methods is that it has to be part of a class in Java. Other languages like C, C++, and Python do not have this rule. Breaking down your code into methods is a very good practice as it saves a lot of time by means of code reusability.

Method Declaration

Method Declaration can be broken down into the following six components:

  • Modifiers – Modifiers determine the access type of the method or the scope of the method in simpler terms, that is, to what extent can this method be called or invoked from in your code. Java allows the following 4 access specifiers:
    • public: Public gives universal access to all classes inside the application concerned.
    • protected: Only accessible inside the class the method has been decided upon as well as subclasses of that class.
    • private: Only accessible within the scope of the class.
    • default (declared without any modifier): This is the default scope a class can obtain. Data is accessible within the same class and package within which the class has been defined.
  • Return Type: This is the data type of the value that will be returned after execution of the method. If no value is returned by a method, it is given a void return type.
  • Method Name: Method Name is the name that is used to invoke the method from others parts of your source code. The naming convention goes the same way as naming variables and fields.
  • Parameter List: During the method declaration, after the method name is a comma separated list of the input parameters. All the parameters and their data types are mentioned within the enclosed parenthesis. An empty bracket signifies that there are no parameters associated with the method.
  • Exception List: If you think that the method might run into exceptions, you can add an exception list in the method signature.
  • Method Body: This is the designated space between curly brackets where you code the kind of execution that you want the method to exhibit.

Example

For example, if there is a method coded as follows in Java:

public int max (int x, int y)
{
if (x > y)
return x;
else
return y;
}

Method Signature

The method signature is a subpart of the method declaration. The signature just contains the method name and the parameter list (number of parameters, type of parameters, and order of the parameters). Exceptions and return types are not part of the signature. Therefore, according to the logic, the method signature of the method is:

max (int x, int y)

How to Name a Method?

Method names are generally contained of a single word and the word is written in lower case. More often than not, the name is a verb or starts with a verb if there are two words together. In case of two words, after the first word, the next word will start with a capital letter. For example: getSum(), findSum(). Normally, method names are unique and should not match with the name of any other entity of your program. However, methods with the same name are often intentionally coded to enable method overloading.

Calling A Method in Java

In order for you to make a method work, you will have to call it. Invoking a method from a different part of your code is called method call. A method returns to the code that called it in the following situations:

  • It completes execution of all the statements in the method.
  • A return statement is encountered.
  • An exception is thrown

Sample Code

import java.io.*;

class Addition
{
int sum = 0;

public int addTwoInt (int a, int b)
{
sum = a + b;
return sum;
}
}

class Demo
{
public static void main (String args [])
{
Addition add = new Addition ();

int s = add.addTwoInt(1,2);
System.out.println (“Sum of two integer values :” + s);
}
}

 

OUTPUT

Sum of two integer values :3

Sample Code to understand the various ways in which you can call a method

import java.io.*;
class Demo
{
public static int i = 0;

Demo ()
{
i++;
}

public static int get()
{
return i;
}

public int m1 ()
{
System.out.println (“Inside the method m1 by object of Demo class”);

this.m2();
return 1;
}

public void m2()
{
System.out.println (“In method m2 came from m1”);
}
}

class Driver
{
public static void main (String args [])
{
Demo obj = new Demo ();

int I = obj.m1();
System.out.println (“Control returned afrer method m1 :” + i);
int no_of_objects = Demo.get();

System.out.println (“No instances created till now”);
System.out.println (“no_of_objects”);
}
}

 

OUTPUT

Inside the method m1 of object of Demo class
In method m2 came from method m1
Control returned after method m1 :1
No of instances created till now: 1

Memory Allocation for method calls

The way in which method calls are handled is through the implementation of stacks. A stack frame is created whenever methods are called in the stack area. Thereafter, the local variables handle the arguments passed and the value that has to be returned form the method is also stored in the stack frame. After finishing up with the execution of the method, the then created stack frame gets deleted automatically. A stack pointer register is used to point out the position in the stack at the moment. It tracks the top of the stack and then the top is thereafter adjusted properly.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author