Methods in Java or Java methods is a powerful and popular aspect of Java programming.

What are Methods in Java?

A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions to draw a circle in the method, it will do that task. You can insert values or parameters into methods, and they will only be executed when called. They are also referred to as functions. The primary uses of methods in Java are:

  • It allows code reusability (define once and use multiple times)
  • You can break a complex program into smaller chunks of code
  • It increases code readability

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Declare Methods in Java?

You can only create a method within a class. There are a total of six components included in a method declaration. The components provide various information about the method. 

Below is the syntax to declare a method and its components list.

public int addNumbers (int a, int b){

//method body

}

Access specifier:

It is used to define the access type of the method. The above syntax sees the use of the “public” access specifier. However, Java provides four different specifiers, which are:

  • Public: You can access it from any class
  • Private: You can access it within the class where it is defined
  • Protected: Accessible only in the same package or other subclasses in another package
  • Default: It is the default access specifier used by the Java compiler if we don’t mention any other specifiers. It is accessible only from the package where it is declared

ReturnType:

It defines the return type of the method. In the above syntax, “int” is the return type. We can mention void as the return type if the method returns no value.

Method name:

It is used to give a unique name to the method. In the above syntax, “addNumbers” is the method name. This tutorial looks at some tips for naming a method, shortly.

Parameter list:

It is a list of arguments (data type and variable name) that will be used in the method. In the above syntax, “int a, int b” mentioned within the parentheses is the parameter list. You can also keep it blank if you don’t want to use any parameters in the method.

Method signature:

You don’t have to do anything additional here. The method signature is just a combination of the method name and parameter list.

Method body:

This is the set of instructions enclosed within curly brackets that the method will perform.

DeclareMethods

DeclareMethodsResults

In the above example:

  • ‘Public’ is the access specifier
  • The return type is ‘int’ (i.e. integer)
  • The method name is addNumbers
  • int x and int y are the parameters
  • addNumbers (int x, int y) is the method signature
  • The method body is:

{

int addition = x + y;

return addition;

}

Adding an Example would be great to increase the clarity about the concept

How to Name a Method?

Some of the rules and tips to name the methods in Java are:

  • Try to use a name that corresponds to the functionality (if the method is adding two numbers, use add() or sum())
  • The method name should start with a verb and in lowercase (Ex: sum(), divide(), area())
  • For a multi-word name, the first word should be a verb followed by a noun or adjective without any space and with the first letter capitalized (Ex: addIntegers(), areaOfSquare)

Java Method Parameters

Java method parameters are necessary components that let methods take data as inputs and process them accordingly. Writing reliable and reusable Java code requires understanding how to use and manage method arguments.

How to Call a Method?

As mentioned earlier, you need to call a method to execute and use its functionalities. You can call a method by using its name followed by the parentheses and a semicolon. Below is the syntax for calling a method:

add();

The example below will create an example method named exMethod() and call it to print a text.

exMethod

exMethodResult

What are the Types of Methods in Java?

Methods in Java can be broadly classified into two types:

  • Predefined
  • User-defined

Predefined Methods

As the name gives it, predefined methods in Java are the ones that the Java class libraries already define. This means that they can be called and used anywhere in our program without defining them. There are numerous predefined methods, such as length(), sqrt(), max(), and print(), and each of them is defined inside their respective classes.

The example mentioned below uses three predefined methods, which are main(), print(), and sqrt().

PredefinedMethods

PredefinedMethodsResult

User-defined Methods

Custom methods defined by the user are known as user-defined methods. It is possible to modify and tweak these methods according to the situation. Here’s an example of a user-defined method.

User-definedMethods

User-definedMethodsResults

Methods in Java can also be classified into the following types:

  • Static Method
  • Instance Method
  • Abstract Method
  • Factory Method

Creating Static Methods in Java

Static methods are the ones that belong to a class and not an instance of a class. Hence, there is no need to create an object to call it, and that’s the most significant advantage of static methods. It is possible to create a static method by using the “static” keyword. The primary method where the execution of the Java program begins is also static.

Please add the code manually by typing

CreatingStaticMethods

CreatingStaticMethodsResult

Applying Instance Methods in Java Code

The instance method is a non-static method that belongs to the class and its instance. Creating an object is necessary to call the instance method.

InstanceMethods

InstanceMethodsResult

Instance methods are further divided into two types:

  • Accessor Method

It is used to get a private field’s value, accessor methods in Java can only read instance variables. They are always prefixed with the word ‘get’.

  • Mutator Method

It is used to get and set the value of a private field, mutator methods in Java can read and modify instance variables. They are always prefixed with the word  ‘set’.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Abstract Methods in Java

Abstract methods in Java do not have any code in them. This means that there is no need to provide the implementation code while declaring it. Instead, it is possible to declare the method body later in the program. It is known that one can declare an abstract method by using the “abstract” keyword. There is another hard rule to declare abstract methods, and it is that they can only be declared within an abstract class.

AbstractMethod

AbstractMethodResult

Factory Method

Factory methods are the ones that return an object to the class where it belongs. Usually, all static methods also fall into this type of method.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Types of Method Parameters

1. Formal Parameters

These arguments serve as stand-ins for the values supplied to the method when it is called; they are defined in the method declaration. The procedure 'public void greet(String name)' uses 'name' as an example of a formal parameter.

2. Actual Parameters

When a method call is made, the method receives these actual values or parameters. For example, 'Alice' is the actual parameter in the statement 'greet("Alice")'.

Parameter Passing in Java

Java passes parameters to methods via the pass-by-value mechanism. This indicates that a copy of the variable's value is created and passed when a variable is supplied to a method. Therefore, the original value outside the method is unaffected by changes made to the parameter inside the method.

Primitive Data Types

The actual value is passed when sending primitive data types (such as int, float, and double). The original variable remains unchanged when modifications are made to the parameter inside the method.

public class Example {
    public static void main(String[] args) {
        int num = 10;
        modifyValue(num);
        System.out.println(num); // Output: 10
    }

    public static void modifyValue(int value) {
        value = 20;
    }
}

Reference Data Types

The reference (or address) to an object is passed by value when passing objects. As a result, modifications made to the object's fields inside the method will have an impact on the source object. Reassigning the reference won't have any impact on the original reference, though.

public class Example {
    public static void main(String[] args) {
        Person person = new Person("John");
        modifyPerson(person);
        System.out.println(person.getName()); // Output: Mike
    }

    public static void modifyPerson(Person p) {
        p.setName("Mike");
    }
}

class Person {
    private String name;

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

    public String getName() {
        return name;
    }

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

Varargs (Variable Arguments)

Java's varargs (variable arguments) allow methods to take any number of parameters. This is helpful when you are unsure of the precise quantity of arguments that will be supplied to the procedure.

Syntax

Three dots (...) declare the varargs parameter. It needs to be the last parameter in the list of parameters for the method.

public static void printNumbers(int... numbers) {
    for (int num : numbers) {
        System.out.println(num);
    }
}

public static void main(String[] args) {
    printNumbers(1, 2, 3, 4, 5); // Output: 1 2 3 4 5
}

Using these ideas, Java programmers can design adaptable, practical methods and handle various input parameter types. This understanding is the foundation for creating successful Java apps.

Java Method Overloading

Java method overloading allows many methods with the same name within a class as long as their argument lists differ. This is an illustration of Java's polymorphism, which allows a single method name to carry out many functions depending on its arguments.

Key Concepts of Method Overloading

1. Method Signature

  • Method overloading is determined by the method signature, which includes the method name and the parameter list. The return type is not considered when overloading methods.
  • Two methods are considered overloaded if they have the same name but different parameter lists (different number of parameters or various types of parameters).

Compile-Time Polymorphism

  • Compile-time polymorphism, sometimes referred to as static polymorphism, is a type of method overloading. The compiler decides which method to invoke based on the method signature at build time.

Benefits of Method Overloading

  • Using the same method name for conceptually related tasks improves the readability and reusability of code.
  • It offers several options to call a method with various argument sets, simplifying the calling process.

Examples of Method Overloading

The following instances demonstrate how Java's method overloading mechanism functions:

public class Calculator {

    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Overloaded method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Overloaded method to add two double values
    public double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();

        System.out.println("Sum of two integers: " + calc.add(5, 10)); // Calls add(int, int)
        System.out.println("Sum of three integers: " + calc.add(5, 10, 15)); // Calls add(int, int, int)
        System.out.println("Sum of two doubles: " + calc.add(5.5, 10.5)); // Calls add(double, double)
    }
}

The 'Calculator' class in this example has three 'add' methods, each with a unique list of parameters:

  • This adds two integers: "add(int a, int b)".
  • To add three numbers, type 'add(int a, int b, int c)'.
  • To add two double numbers, type "add(double a, double b)".

Depending on the inputs passed in, the compiler chooses which function to run when the 'add' method is invoked.

Rules for Method Overloading

1. Different Number of Parameters

When a method has more parameters than necessary, it can become overloaded.

public void print(String message) { }

public void print(String message, int times) { }

2. Different Types of Parameters

Having too many different kinds of parameters can overwhelm a method.

public void display(int number) { }

public void display(String text) { }

3. Different Order of Parameters

Changing the parameters' order can potentially overload a method.

public void process(int a, double b) { }

public void process(double a, int b) { }

Java Scope

The accessibility and lifetime of variables and other elements within a program are referred to as the program's scope in Java. Comprehending the scope is crucial for effectively regulating the visibility and lifecycle of variables, preventing mistakes and guaranteeing optimal memory utilization. Java defines various scope types, including:

Types of Scopes in Java

1. Class Scope (Static Variables)

Class-level variables, commonly referred to as static variables, are variables declared inside a class but outside of any constructor, function, or block. All of the class's static methods can access these variables, and they keep their value in between method calls.

public class MyClass {
    static int staticVariable = 10; // Class scope
}

2. Instance Scope (Instance Variables)

Class-level variables, commonly referred to as static variables, are variables declared inside a class but outside of any constructor, function, or block. All of the class's static methods can access these variables, and they keep their value in between method calls.

public class MyClass {
    int instanceVariable = 20; // Instance scope
}

3. Method Scope (Local Variables)

Declared variables are specific to a method and are not global to it. When the method is invoked, they are generated; when it ends, they are destroyed. External to the method, local variables are not available.

public void myMethod() {
    int localVariable = 30; // Method scope
}

4. Block Scope

Variables like loops and conditionals that are declared inside a code block are only accessible from within that block. These variables are lost as soon as the block is exited.

public void myMethod() {
    if (true) {
        int blockVariable = 40; // Block scope
    }
    // blockVariable is not accessible here
}

Examples of Variable Scope

public class ScopeExample {
    // Class scope variable
    static int classVar = 100;

    // Instance scope variable
    int instanceVar = 200;

    public void method() {
        // Method scope variable
        int methodVar = 300;

        // Block scope variable
        for (int i = 0; i < 5; i++) {
            int blockVar = 400;
            System.out.println("Block variable: " + blockVar);
        }
        // blockVar is not accessible here
    }

    public static void main(String[] args) {
        ScopeExample example = new ScopeExample();
        example.method();

        System.out.println("Class variable: " + classVar);
        System.out.println("Instance variable: " + example.instanceVar);
        // methodVar is not accessible here
    }
}

In this example:

  • 'classVar' is reachable by all class methods and has class scope.
  • 'instanceVar' is specific to each instance of 'ScopeExample' and has instance scope.
  • 'methodVar' can only be accessed within'method()' and has method scope.
  • "blockVar" is limited to the for-loop block and has a block scope.

By limiting variables' lifespans, knowing and utilizing Java's variable scope effectively helps manage memory and guarantees that variables are available when needed.

Java Recursion

In Java programming, recursion is the process by which a method calls itself to address an issue. This method is frequently applied to decompose complex problems into easier-to-manage, more minor matters. Recursion is a useful tool, but it must be used carefully to prevent problems like infinite loops and high memory utilization.

How Recursion Works

Recursion consists of two key components:

1. Base Case

This is the circumstance in which the recursion concludes. A stack overflow fault would result from the method calling itself endlessly without a base case.

2. Recursive Case

At this point, to move closer to the base case, the method calls itself with altered parameters.

Example of Recursion: Factorial Calculation

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. The factorial function can be defined recursively as:

  • n!=n×(n−1)!
  • Base case: 0!=1

This is an example of a Java recursive implementation of the factorial function:

public class RecursionExample {
    // Recursive method to calculate factorial
    public static int factorial(int n) {
        if (n == 0) {
            return 1; // Base case
        } else {
            return n * factorial(n - 1); // Recursive case
        }
    }

    public static void main(String[] args) {
        int number = 5;
        int result = factorial(number);
        System.out.println("Factorial of " + number + " is " + result);
    }
}

In this example:

The ‘factorial’ method calls itself with the parameter ‘n - 1’ until it reaches the base case where n=0. 

Benefits of Recursion

1. Simplifies Code

Recursion can simplify code by making it shorter and more understandable, especially for issues like tree traversals and some mathematical processes that naturally have a recursive structure.

2. Elegant Solutions

Recursion is an elegant way to solve several problems, including the Tower of Hanoi, the Fibonacci sequence, and the quicksort method.

Drawbacks of Recursion Performance

1. Performance

Recursive methods may perform more slowly than their iterative equivalents because of the overhead of repeated method calls and the potential for stack overflow in deep recursions.

2. Memory Usage

If the recursion depth is too great, it may result in stack overflow and excessive memory usage since each recursive call adds a new layer to the call stack.

Conclusion

In this tutorial, you were introduced to everything about methods in Java. It’s time to implement your learning and do some practicals. You can also refer to our methods and encapsulation tutorial to delve deeper into this concept. This tutorial will help you learn how to apply the OOPs concepts of access modifiers and encapsulation to Java classes. It will enable you to get a strong grasp on Java programming. But if you want to excel in overall Java development, Simplilearn’s Full Stack Developer - MERN Stack is the best way to do so. The 60 hours of applied learning and 35 coding-related exercises make the course adept at helping you become an expert developer. You will work on the most popular Java frameworks, including Hibernate and Spring during this course. Have any questions for us? Leave them in the comments section, and our experts will get back to you sovon. Happy learning!

FAQs

1. What Is the Difference Between a Method Declaration and a Method Call?

Aspect

Method Declaration

Method Call

Definition

A method declaration defines a new method, specifying its name, return type, parameters, and body.

A method call invokes a method that has already been declared, executing its body with the specified arguments.

Purpose

To specify what the method will do when it is called, including its parameters and return type.

To execute the method’s code and perform the defined task.

Components

- Method name <br> - Return type <br> - Parameter list <br> - Method body

- Method name <br> - Arguments (if any)

Syntax Example

java<br> public int add(int a, int b) { <br> return a + b; <br> }<br>

java<br> int result = add(5, 3);<br>

Location

Typically inside a class definition, can be declared as public, private, protected, or default.

Can be inside another method, constructor, or initialization block.

Return Type

Specify a return type (e.g., int, void, String).

Does not specify a return type; the method being called determines the return type.

Parameters

Declares the type and number of parameters the method will accept.

Passes actual values (arguments) to the method's parameters.

Execution

Defines what happens when the method is called but does not execute independently.

Executes the code within the method declaration.

Example

java<br> public void greet(String name) { <br> System.out.println("Hello, " + name); <br> }<br>

java<br> greet("Alice");<br>

Overloading

Methods can be overloaded by declaring multiple methods with the same name but different parameter lists.

Method calls specify which overloaded method to invoke based on the arguments provided.

Scope

Determines the scope of the method within the class (e.g., instance method, static method).

Depends on where the method call is made (e.g., within an instance method, within a static context).

2. What Is Method Overriding?

With Java, a subclass can give a particular implementation of a method already defined in its superclass by using a feature called method overriding. The name, parameters, and return type of the overridden method in the subclass must match those of the method in the superclass. This idea is essential to polymorphism because it allows a subclass to modify or expand the functionality of a superclass method. Runtime polymorphism is achieved by method overriding, in which the method that is called at runtime is chosen depending on the actual type of the object, not its reference type. Subclasses can specify their behaviors while still utilizing the superclass's familiar interface.

Subclasses like "Circle" and "Rectangle" can override a superclass's "draw()" method, for instance, to provide unique implementations for drawing circles and rectangles, respectively. The ability to override methods improves the code's flexibility and maintainability, which facilitates handling modifications and system expansion. 

3. What Is the Purpose of the ‘Return’ Statement in a Method?

In a method, the 'return' statement ends the technique and may optionally return a value to the caller. It puts an end to the method's execution and returns the computation's result to where the method was called. This is essential for procedures that carry out computations or actions that require a result. The 'return' statement in void methods can be used to end the method early, usually for error handling or specific situations, without returning any value.

4. What Is the ‘This’ Keyword in Java Methods?

The "this" keyword in Java refers to the current object within a constructor or instance method. When two variables have the same name, they distinguish between instance and local variables. In constructors and setters, the 'this' keyword is beneficial as it clarifies which variable is being discussed. 'this' can also be used to call additional constructors inside the same class, guaranteeing cleaner initialization and code reuse. Developers can improve code readability and prevent any conflicts between class attributes and parameters or local variables by using 'this' to refer to the class instance explicitly.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449