Open In App

Java Methods

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python.

  • A method is like a function i.e. used to expose the behavior of an object.
  • It is a set of codes that perform a particular task.

Syntax of Method:

<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}

Advantage of Method:

  • Code Reusability
  • Code Optimization

Note: Methods are time savers and help us to reuse the code without retyping the code.

To deepen your understanding of Java methods and learn how to effectively implement them in your programs, you might consider exploring structured learning resources or comprehensive

Java Programming Online courses designed to enhance your coding skills and knowledge.

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your application. In Java, there 4 types of access specifiers.

  • public: It is accessible in all classes in your application.
  • protected: It is accessible within the class in which it is defined and in its subclasses.
  • private: It is accessible only within the class in which it is defined.
  • default: It is declared/defined without using any modifier. It is accessible within the same class and package within which its class is defined.

Note: It is Optional in syntax.

2. The return type: The data type of the value returned by the method or void if does not return a value. It is Mandatory in syntax.

3. Method Name: the rules for field names apply to method names as well, but the convention is a little different. It is Mandatory in syntax.

4. Parameter list: Comma-separated list of the input parameters is defined, preceded by their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().  It is Optional in syntax.

5. Exception list: The exceptions you expect by the method can throw; you can specify these exception(s). It is Optional in syntax.

6. Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.  It is Optional in syntax.

Method Body in Java


Types of Methods in Java

There are two types of methods in Java:

1. Predefined Method

In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point.

2. User-defined Method

The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.

Ways to Create Method in Java

There are two ways to create a method in Java:

1. Instance Method: Access the instance data using the object name. Declared inside a class.

Syntax:

// Instance Method
void method_name(){
body // instance area
}

2. Static Method: Access the static data using class name. Declared inside class with static keyword.

Syntax:

//Static Method
static void method_name(){
body // static area
}

Method Signature:

It consists of the method name and a parameter list (number of parameters, type of the parameters, and order of the parameters). The return type and exceptions are not considered as part of it.

Method Signature of the above function:

 max(int x, int y) Number of parameters is 2, Type of parameter is int.

Naming a Method

In Java language method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective, noun. After the first word, the first letter of each word should be capitalized.

Rules to Name a Method:

  • While defining a method, remember that the method name must be a verb and start with a lowercase letter.
  • If the method name has more than two words, the first name must be a verb followed by an adjective or noun.
  • In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example, findSum, computeMax, setX, and getX.

Generally, a method has a unique name within the class in which it is defined but sometimes a method might have the same name as other method names within the same class as method overloading is allowed in Java .

Method Calling

The method needs to be called for use its functionality. There can be three situations when a method is called:
A method returns to the code that invoked it when:

  • It completes all the statements in the method.
  • It reaches a return statement.
  • Throws an exception.

Example:

Java
// Java Program to Illustrate Methods

// Importing required classes
import java.io.*;

// Class 1
// Helper class
class Addition {

    // Initially taking sum as 0
    // as we have not started computation
    int sum = 0;

    // Method
    // To add two numbers
    public int addTwoInt(int a, int b)
    {

        // Adding two integer value
        sum = a + b;

        // Returning summation of two values
        return sum;
    }
}

// Class 2
// Helper class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Creating object of class 1 inside main() method
        Addition add = new Addition();

        // Calling method of above class
        // to add two integer
        // using instance created
        int s = add.addTwoInt(1, 2);

        // Printing the sum of two numbers
        System.out.println("Sum of two integer values :"
                           + s);
    }
}

Output
Sum of two integer values :3

Example 2:

Java
// Java Program to Illustrate Method Calling
// Via Different Ways of Calling a Method

// Importing required classes
import java.io.*;

// Class 1
// Helper class
class Test {

    public static int i = 0;

    // Constructor of class
    Test()
    {

        // Counts the number of the objects of the class
        i++;
    }

    // Method 1
    // To access static members of the class and
    // and for getting total no of objects
    // of the same class created so far
    public static int get()
    {

        // statements to be executed....
        return i;
    }

    // Method 2
    // Instance method calling object directly
    // that is created inside another class 'GFG'.

    // Can also be called by object directly created in the
    // same class and from another method defined in the
    // same class and return integer value as return type is
    // int.
    public int m1()
    {

        // Display message only
        System.out.println(
            "Inside the method m1 by object of GFG class");

        // Calling m2() method within the same class.
        this.m2();

        // Statements to be executed if any
        return 1;
    }

    // Method 3
    // Returns nothing
    public void m2()
    {

        // Print statement
        System.out.println(
            "In method m2 came from method m1");
    }
}

// Class 2
// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Creating object of above class inside the class
        Test obj = new Test();

        // Calling method 2 inside main() method
        int i = obj.m1();

        // Display message only
        System.out.println(
            "Control returned after method m1 :" + i);

        // Call m2() method
        // obj.m2();
        int no_of_objects = Test.get();

        // Print statement
        System.out.print(
            "No of instances created till now : ");

        System.out.println(no_of_objects);
    }
}

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

The control flow of the above program is as follows:

Control Flow diagram of the Program


Passing Parameters to a method

There are some cases when we don’t know the number of parameters to be passed or an unexpected case to use more parameters than declared number of parameters. In such cases we can use

  • Passing Array as an Argument
  • Passing Variable-arguments as an Argument
  • Method Overloading.

Memory Allocation for Methods Calls

Methods calls are implemented through a stack. Whenever a method is called a stack frame is created within the stack area and after that, the arguments passed to and the local variables and value to be returned by this called method are stored in this stack frame and when execution of the called method is finished, the allocated stack frame would be deleted. There is a stack pointer register that tracks the top of the stack which is adjusted accordingly.

Example: pseudo-code for implementing methods

Java
// Define a class
public class Example {

    // Define instance variables
    private int number;
    private String name;

    // Define accessor (getter) methods
    public int getNumber() {
      return number; 
    }

    public String getName() {
      return name; 
    }

    // Define mutator (setter) methods
    public void setNumber(int number)
    {
        this.number = number;
    }

    public void setName(String name) { this.name = name; }

    // Define other methods
    public void printDetails()
    {
        System.out.println("Number: " + number);
        System.out.println("Name: " + name);
    }
}

// Use the methods in another part of the code
Example example = new Example();
example.setNumber(123);
example.setName("GFG Write");
example.printDetails();

There are several advantages to using methods in Java, including:

  • Reusability : Methods allow you to write code once and use it many times, making your code more modular and easier to maintain.
  • Abstraction : Methods allow you to abstract away complex logic and provide a simple interface for others to use. This makes your code more readable and easier to understand.
  • Improved readability : By breaking up your code into smaller, well-named methods, you can make your code more readable and easier to understand.
  • Encapsulation : Methods allow you to encapsulate complex logic and data, making it easier to manage and maintain.
  • Separation of concern s: By using methods, you can separate different parts of your code and assign different responsibilities to different methods, improving the structure and organization of your code.
  • Improved modularity : Methods allow you to break up your code into smaller, more manageable units, improving the modularity of your code.
  • Improved testability : By breaking up your code into smaller, more manageable units, you can make it easier to test and debug your code.
  • Improved performance: By organizing your code into well-structured methods, you can improve performance by reducing the amount of code that needs to be executed and by making it easier to cache and optimize your code.

FAQs in Methods in Java

Q. What is a method in Java programming?

Java Method is a collection of statements that perform some specific task and return the result to the caller.

Q. What are parts of method in Java?

The 5 methods parts in Java are mentioned below:

  1. Modifiers
  2. Return Type
  3. Method Name
  4. Parameters
  5. Method Body

    Related Articles:




    Previous Article
    Next Article

    Similar Reads

    Static methods vs Instance methods in Java
    In this article, we are going to learn about Static Methods and Instance Methods in Java. Java Instance MethodsInstance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the method is defined. public void geek(String name) {
    5 min read
    Java.util.BitSet class methods in Java with Examples | Set 2
    Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
    4 min read
    Java.io.BufferedWriter class methods in Java
    Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the Writer.Class Declaration public class BufferedWri
    5 min read
    Can we Overload or Override static methods in java ?
    Let us first define Overloading and Overriding. Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made accor
    5 min read
    Utility Methods of Wrapper Classes in Java
    Prerequisite: Wrapper Classes The objective of the Wrapper class is to define several utility methods which are required for the primitive types. There are 4 utility methods for primitive type which is defined by the Wrapper class: 1. valueOf() method: We can use the valueOf() method to create a Wrapper object for a given primitive or String. There
    4 min read
    Private Methods in Java 9 Interfaces
    Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible. Interfaces till Java 7 In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface. // Java 7 progr
    4 min read
    BigInteger max() and min() Methods in Java
    Prerequisite: BigInteger Basics BigInteger max() method: The max() method of the BigInteger returns the BigInteger whose value is the greater between current BigInteger and BigInteger passed as a parameter to the method. If both the values are equal, either may be returned. There is a similar method compareTo() available on BigInteger class. The ma
    3 min read
    Green vs Native Threads and Deprecated Methods in Java
    A multi-threaded process as we all know has several sequences of control, where each sequence is governed by a thread and is capable of performing independent tasks concurrently. In Java, multithreading concept is implemented by using the following two models. Green Thread model Native Thread Model Green Thread Model In this model, threads are comp
    5 min read
    FloatBuffer get() methods in Java with Examples
    get() The get() method of java.nio.FloatBuffer Class is used to reads the float at the given buffer's current position, and then increments the position. Syntax : public abstract float get() Return Value: This method returns the float value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's curre
    5 min read
    FloatBuffer put() methods in Java with Examples
    put(float f) The put(float f) method of java.nio.FloatBuffer Class is used to write the given float into the newly created float buffer at the current position, and then increments the position. Syntax : public abstract FloatBuffer put(float f) Parameters: This method takes the float value f as a parameter which is to be written in float buffer. Re
    6 min read
    LongBuffer get() methods in Java
    get() The get() method of java.nio.LongBuffer Class is used to read the Long at the given buffer's current position, and then increment the position. Syntax : public abstract Long get() Return Value: This method returns the Long value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's current pos
    5 min read
    IntBuffer get() methods in Java | Set 1
    get() The get() method of java.nio.IntBuffer Class is used to reads the int at the given buffer's current position, and then increments the position. Syntax : public abstract int get() Return Value: This method returns the int value at the buffer's current position. Throws: This method throws BufferUnderflowException - If the buffer's current posit
    5 min read
    LongBuffer put() methods in Java
    put(Long i) The put(Long i) method of java.nio.LongBuffer Class is used to write the given Long value into the newly created Long buffer at the current position, and then increments the position. Syntax: public abstract LongBuffer put(Long i) Parameters: This method takes the Long value i as a parameter which is to be written in Long buffer. Return
    6 min read
    CharBuffer get() methods in Java
    The get() method of java.nio.CharBuffer Class is used to reads the char at the given buffer's current position, and then increments the position. Syntax: public abstract char get() Return Value: This method returns the char value at the buffer's current position. Exceptions: This method throws BufferUnderflowException - If the buffer's current posi
    5 min read
    IntBuffer put() methods in Java | Set 1
    put(int i) The put(int i) method of java.nio.IntBuffer Class is used to write the given int into the newly created int buffer at the current position, and then increments the position. Syntax : public abstract IntBuffer put(int i) Parameters: This method takes the int value i as a parameter which is to be written in int buffer. Return Value: This m
    6 min read
    DoubleBuffer put() methods in Java with Examples | Set 1
    put(double f) The put(double f) method of java.nio.DoubleBuffer Class is used to write the given double into the newly created double buffer at the current position, and then increments the position. Syntax: public abstract DoubleBuffer put(double f) Parameters: This method takes the double value f as a parameter which is to be written in double bu
    6 min read
    CharBuffer put() methods in Java
    put(char i) The put(char i) method of java.nio.CharBuffer Class is used to write the given character into the newly created char buffer at the current position and then increments the position. Syntax : public abstract CharBuffer put(char i) Parameters: This method takes the char value i as a parameter which is to be written in char buffer. Return
    6 min read
    Differences between wait() and join() methods in Java
    The wait() and join() methods are used to pause the current thread. The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution. wait() is mainly used for shared resources, a thread notifies other waiting thread when a resource becomes free. On the other hand join() is used
    2 min read
    DoubleBuffer get() methods in Java with Examples
    The get() method of java.nio.DoubleBuffer Class is used to reads the double at the given buffer’s current position, and then increments the position. Syntax: public abstract double get() Return Value: This method returns the double value at the buffer’s current position. Exception: This method throws BufferUnderflowException if the buffer’s current
    3 min read
    Java TreeMap Special Methods
    TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Due to the implementation of the NavigableMap interface and sorted data, TreeMap provides cer
    10 min read
    ByteBuffer put() methods in Java with Examples | Set -1
    put(byte b) The put(byte b) method of java.nio.ByteBuffer Class is used to write the given byte into the newly created byte buffer at the current position, and then increments the position. Syntax : public abstract ByteBuffer put(byte f) Parameters: This method takes the byte value b as a parameter which is to be written in byte buffer. Return Valu
    6 min read
    ByteBuffer putFloat() methods in Java with Examples
    putFloat(float value) The putFloat(float value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given float value, in the current byte order, into this buffer at the current position, and then increments the position by four. Syntax: public abstract ByteBuffer putFloat(float value) Parameters: This method takes a para
    7 min read
    ByteBuffer putChar() methods in Java with Examples
    putChar(char value) The putChar(char value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given char value, in the current byte order, into this buffer at the current position, and then increments the position by two. Syntax: public abstract ByteBuffer putChar(char value) Parameters: This method takes the char value
    6 min read
    ByteBuffer putDouble() methods in Java with Examples
    putDouble(double value) The putDouble(double value) method of java.nio.ByteBuffer Class is used to write eight bytes containing the given double value, in the current byte order, into this buffer at the current position, and then increments the position by eight. Syntax: public abstract ByteBuffer putDouble?(double value) Parameters: This method ta
    6 min read
    ByteBuffer putInt() methods in Java with Examples
    putInt(int value) The putInt(int value) method of java.nio.ByteBuffer Class is used to write four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. Syntax : public abstract ByteBuffer putInt(int value) Parameters: This method takes the int value to be
    7 min read
    ByteBuffer putLong() methods in Java with Examples
    putLong(int value) The putLong(int value) method of java.nio.ByteBuffer Class is used to write eight bytes containing the given long value, in the current byte order, into this buffer at the current position, and then increments the position by eight. Syntax: public abstract ByteBuffer putLong(long value) Parameters: This method takes a long value
    6 min read
    ByteBuffer putShort() methods in Java with Examples
    putShort(int value) The putShort(int value) method of java.nio.ByteBuffer Class is used to write two bytes containing the given short value, in the current byte order, into this buffer at the current position, and then increments the position by two. Syntax: public abstract ByteBuffer putShort(short value) Parameters: This method takes the short va
    6 min read
    ByteBuffer wrap() methods in Java with Examples
    wrap(byte[] array) The wrap() method of java.nio.ByteBuffer Class is used to wraps a byte array into a buffer. The new buffer will be backed by the given byte array, i.e., modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity and limit will be array.length, its position will be zero, its mark will
    4 min read
    ByteBuffer flip() methods in Java with Examples
    The flip() method of java.nio.ByteBuffer Class is used to flip this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations. For exam
    3 min read
    ByteBuffer limit() methods in Java with Examples
    The limit() method of java.nio.ByteBuffer Class is used to set this buffer's limit. If the position is larger than the new limit then it is set to the new limit. If the mark is defined and larger than the new limit then it is discarded. Syntax: public ByteBuffer limit(int newLimit) Return Value: This method returns this buffer. Below are the exampl
    2 min read
    Article Tags :
    Practice Tags :
    three90RightbarBannerImg