methods in java

Since Java is a general-purpose programming language, you’ll need certain functions to be implemented and invoked on time for a successful application development. The block of code written to perform a certain dedicated function is known as a method. In this blog, you’ll learn more on Methods in Java. 

  1. What is a Method?
  2. Different types of methods in Java
  3. How to create a method?
  4. How to call a Method/Method calling
  5. Method parameters
  6. Memory allocation for methods calls

Let’s start learning!

What is a Method?

A method is a set of code that can be named after the program scenario (E.g. For a program to add two numbers, method names can be sum ( ); ) and they can be invoked (called) at any point in a program to perform specific functions, by using the same name mentioned during declaration. 

Fig 1. Sample Java Program with a method call
  • Methods save time as well as retyping of code for a programmer.
  • Methods can be reused in any other program / application and reduce the processing time. 
  • Methods are easy to call and once the body of the method is executed, it returns to the next line of the code and continues until the program ends. 
  • Using methods helps in performing same operations multiple times 
  • It reduces the size of the program / project

Different Types of Methods in Java

There are two types of methods in Java 

1. Pre – Defined Methods/ Standard Library Methods/System defined Methods: 

These are built – in methods in Java, which are instantly available to use in your program. The Java class library will be present in java archive (i.e., *jar) file with Java Virtual Machine (JVM) and Java Runtime Environment. 

Examples:

Math functions – sqrt(), log(), min(), max(), avg(), sin(), cos(), tan(), round(),floor(), abs() etc.

String function – length( ),  substring ( ), replace ( ), charAt ( ), indexOf  ( ) , trim ( ) etc.

Sample Program: 

public class Main 
{
public static void main(String[] args) 
{
String targetString = "Java is fun to learn";
String str1= "JAVA";
String str 2= "Java";
String str 3 = "  Hello Java  ";
System.out.println("Checking Length: "+ targetString.length());
char [] charArray = str2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
}

Output:

2. User – defined Methods: 

These methods are created by the programmers for their requirement as per the programming scenario / necessity.

2.1 Method with returning a value

2.1.1 Calling method by invoking Object

SYNTAX: 

Write Method
// Before main Method
accessModifier returnType methodName(Parameters)
{
Statements
———
———
———
}
--------------------------------------------------------------------
//After main method
Call Method
//Create Object
ClassName objectName = new ClassName( );
//Call Method by invoking object
dataType variableName = object.method(values..);
or
System.out.println(object.method( ));

2.1.2 Calling method without invoking Object

SYNTAX:

accessModifier nonAccessModifier returnType methodName(Parameters)
{
Statements
————
————
————
}
Call Method
dataType variableName = methodName(values);
or
System.out.println(methodname(values);

2.2 Method without returning any value

2.2.1 Calling method by invoking Object

SYNTAX:

accessModifier returnTypeNothing methodName(parameters)
{
Statements
———-
———-
———
}
//Create Object
ClassName objectName = new ClassName();

//Call Method
object.method(values);

2.2.2 Calling method without invoking Object

 SYNTAX: 

accessModifier nonAccessModifier returnTypeNothing methoName(Parameters){
Statements
———
———
———
}
Call method
methodName(values);

How to Create a Method?

A method must be declared within a class. It must contain the name of the method for identification, preceding with parentheses ( ). Java provides some pre-defined ( system defined) methods, for example System.out.println(), but user defined methods can also be created. 

SYNTAX:

public class Main 
{
  static void mydemo() 
{
    // code to be executed
  }
     }
   Where, mydemo( ) is method name

How to call a Method? (Method Calling)

A method in java is called by its name, we declare method with a name and common braces with semicolon;

Syntax: methodname ( );

Ex: javamethod( );

In the following example, javaMethod() is used to print a text (the function), when it is called:

Sample Program: 

public class Main 
{
  static void javaMethod()
 {
    System.out.println(" Java is easy to learn ");
  }
  public static void main(String[] args)
 {
    javaMethod();
  }
}
 

Output: 

There are  two conditions where method returns to caller, they are:

  • When the return statement is executed.
  • When the control reaches the method end at the closing brace.
  • When a Java program is on execution, if it encounters a method.
  • The execution then leads to the myFunction() method and executes code inside the body of the method.
  • After the execution of the method body is successful, the program returns to the next line and continues until the end.

Method Parameters

The information passed to the methods is known as Parameters. Parameters are similar to the variables we use in normal.

Parameters are mentioned after the method name, within the common braces. Multiple  parameters  can be added using comma separators. Similar to variable declaration.

The example below has a method that takes a String in a method:

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Khan");
  }

  public static void main(String[] args) {
    myMethod("Salman");
    myMethod("Shahrukh");
    myMethod("Aamir");
  }
}

Output:

Methods with multiple parameters: 

public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

  public static void main(String[] args) {
    myMethod("Sneha", 25);
    myMethod("Sanjana", 21);
    myMethod("Anju", 20);
  }
}

OUTPUT:

Return Values:

We have learnt only void keyword in the method which means it should not return any value. If the value to be returned by the method then  you can use data types such as int, char etc. So use the return keyword instead of void in the method: 

In this example we are passing value 19 to the method to add it with 5: 

public class Main
 {
  static int sum(int x) 
{
    return 5 + x;
  }
  public static void main(String[] args) 
{
    System.out.println(sum(19));
  }
}

OUTPUT: 24

Memory Allocation for Method Calls

In order to make static memory allocation and execution of the codes/ methods we use STACK MEMORY in Java. Access to this memory is in Last-In-First-Out (LIFO) order as the stack by nature follows LIFO. A new block on stack top is created when we call new method that contains specific values related to that method, like parameters and reference objects. After method execution is complete, its stack frame is cleared, the execution returns back to the calling method and the empty pace will be available for the upcoming method.

Key Features of Stack Memory

  • It increases and decreases as new methods are called and returned respectively.
  • Variables lifetime inside a stack until the method that created them is in execution.
  • The memory space is automatically allocated and deallocated as per method execution
  • If this memory is full, Java throws error i.e.,java.lang.StackOverFlowError
  • Access to this memory is fast.This memory is thread safe as each thread operates in its own Stack

Example Program to understand Memory Allocation:

class Person {
    int id;
    String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class PersonBuilder {
    private static Person buildPerson(int id, String name) {
        return new Person(id, name);
    }

    public static void main(String[] args) {
        int id = 23;
        String name = "John";
        Person person = null;
        person = buildPerson(id, name);
    }
}

  1. After the cursor enters the main ( ) function, a memory space in the stack will be created to store the method parameters and references  related to  the method.  
    • The value of integer id will be stored in the stack memory directly. 
    • The reference variable person of type Person will also be created in stack memory which will point to the actual object in the heap space.
  2. On top of the previous stack, the call to the constructor Person(int, String) from main() will allocate further memory. This will store:
    • The this object is reference to the calling object in the stack
    • The value id in the stack memory
    • The actual string from the string pool in heap memory will be pointed by the reference variable of String argument name.
  3. The next method called by the main method is buildPerson( ), for which the memory allocation will be on top of the previous one on the stack.
  4.  All the variables will be stored in heap memory including the newly created object person of type Person.

Summary

Before we conclude this article, let’s quickly summarize the features of the stack memory.

ParameterStack Memory
ApplicationStack is used to execute the threads individually one after the other. Having separate blocks, which is cleared later and replaced by next method/thread.
SizeStack is usually smaller than heap , its size limits depends upon the operating system architecture.
StorageIt stores only primitive variables and references to objects created in Heap Space
OrderIt follows LIFO ( Last in First Out ) memory allocation system
LifeThe memory allocated to the parameters of a method inside a stack only exists as long as the current method is running.
EfficiencyIt has much faster memory allocation capacity than heap
Allocation/DeallocationStack memory is automatically allocated/ deallocated according to the method’s nature when it is called or when the execution is complete

This brings us to the end of the blog on Methods in Java. If you wish to learn more such concepts, head over to Great Learning Academy and take up the Free Online Courses.

java

Also read: Java Tutorial for Beginners | An Overview of Java

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

17 + eleven =