Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Methods in Java

Methods and Functions in Java

Java is an object-oriented programming language that follows a structured approach to coding. One key component of Java programming is methods (functions in some contexts). Methods help ensure code reusability, modularity, and maintainability. In this blog, we will explore methods in Java, their types, and the best practices for writing efficient methods.

A method in Java is a block of code that performs a specific task. It is defined using a specific structure that includes a name, return type, parameters (optional), and method body.

Syntax of a Method

access_modifier return_type method_name(parameter_list) {  
    // Method body (logic to be executed)  
    return value; // (Only required if return_type is not void)  
}
 

Components of a Method

  • Access Modifier – Defines the visibility of the method (public, private, protected, or default).

  • Return Type – Specifies the type of value the method returns (void if no value is returned).

  • Method Name – A unique name to identify the method.

  • Parameter List – Inputs passed to the method (can be empty).

  • Method Body – The logic inside the method.

  • Return Statement – (If applicable) Returns a value when the method completes execution.

Example: A Simple Method Definition

class MasterBackend {
    // Method to add two numbers (with input and with output)
    int addNumbers(int a, int b) {
        return a + b; // Returning the sum
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        int result = obj.addNumbers(5, 10); // Calling the method
        System.out.println("Sum: " + result);
    }
}
 

Output

Sum: 15

This method addNumbers takes two integers as input and returns their sum.

Method Declaration in Java

A method declaration defines the structure of a method before it is executed. It includes the method name, return type, parameters, and access modifiers.

1. Syntax of a Method

A method in Java follows this general syntax:

acess_modifier return_type method_name(parameter_list) {
    // Method body (logic to execute)
    return value; // (If return type is not void)
}

 
 

Example:


public int add(int a, int b) {
    return a + b;
}
  • public → Access modifier (Defines method visibility)

  • int → Return type (Method returns an integer value)

  • add → Method name

  • (int a, int b) → Parameters (Method takes two integers as input)

  • return a + b; → The method returns the sum of a and b

2. Access Modifiers

Access modifiers define the visibility and accessibility of a method.

Modifier

Description

Accessibility

public

Accessible from anywhere.

Any class inside or outside the package.

private

Accessible only within the same class.

Same class only.

protected

Accessible within the same package and subclasses.

Same package + subclasses (even in different packages).

default (No modifier)

Accessible within the same package only.

Same package only.

Example of Access Modifiers:


class MasterBackend {
    public void publicMethod() {
        System.out.println("Public Method");
    }

    private void privateMethod() {
        System.out.println("Private Method");
    }

    protected void protectedMethod() {
        System.out.println("Protected Method");
    }

    void defaultMethod() { // No modifier means 'default'
        System.out.println("Default Method");
    }
}
  • publicMethod() can be called from anywhere.

  • privateMethod() can only be accessed within the same class.

  • protectedMethod() is accessible in the same package and by subclasses.

  • defaultMethod() is accessible only within the same package.

3. Return Type (void vs. other data types)

A method must specify a return type, which determines what the method will return.

  • void → No return value.

  • Primitive types → int, double, boolean, etc.

  • Reference types → String, ArrayList, custom objects, etc.

Examples:

Method with void (No return value)

public void printMessage() {
    System.out.println("Hello from MasterBackend!");
}
Method with a return type (int)

public int multiply(int a, int b) {
    return a * b;
}
Method returning a String

public String getGreeting(String name) {
    return "Hello, " + name + "!";
}

4. Method Name and Parameters

  • Method Name: It should be meaningful, following the camelCase naming convention.

  • Parameters: Values passed to the method inside parentheses () (optional).

Example:


public double calculateDiscount(double price, double discountRate) {
    return price - (price * discountRate / 100);
}
  • calculateDiscount → Meaningful method name

  • (double price, double discountRate) → Two parameters

Method Calling

In Java, methods can be called using objects or directly, depending on whether they are instance methods or static methods.

1. Calling Methods Using Objects

Instance methods require an object to be called.

Example:


class MasterBackend {
    // Instance method (Non-static)
    void showMessage() {
        System.out.println("Hello from MasterBackend!");
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend(); // Creating an object
        obj.showMessage(); // Calling the method using the object
    }
}

Output:

Hello from MasterBackend!

Here, showMessage() is an instance method, and we call it using an object of the class.

2. Calling Static vs. Non-Static Methods

  • Static methods belong to the class and can be called without creating an object.

  • Non-static methods belong to an instance of the class and require an object to be called.

Example:

class MasterBackend {
    // Static method
    static void staticMethod() {
        System.out.println("Static Method Called!");
    }

    // Non-static method
    void nonStaticMethod() {
        System.out.println("Non-Static Method Called!");
    }

    public static void main(String[] args) {
        // Calling a static method
        MasterBackend.staticMethod();

        // Calling a non-static method
        MasterBackend obj = new MasterBackend();
        obj.nonStaticMethod();
    }
}

Output:


Static Method Called!
Non-Static Method Called!
  • Static method (staticMethod()) is called using the class name.

  • Non-static method (nonStaticMethod()) requires an object.

Types of methods

  • Without Input and Without Output

  • With Input and Without Output

  • Without Input and With Output

  • With Input and With Output

1. Without Input and Output

These methods do not take parameters or return values. When called, they simply execute a block of code.

Example:

class MasterBackend {
    // Method without input and without output
    void greet() {
        System.out.println("Hello, Welcome to Java Programming!");
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        obj.greet(); // Calling the method
    }
}

Output:


Hello, Welcome to Java Programming!

This method just prints a message. It neither accepts input nor returns any value.

2. With Input and Without Output

These methods take parameters (input) but do not return anything. They perform an action based on the given input.

Example:


class MasterBackend {
    // Method with input and without output
    void displayMessage(String name) {
        System.out.println("Hello, " + name + "! Welcome to Java.");
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        obj.displayMessage("Ayush"); // Passing an input
    }
}

Output:


Hello, Ayush! Welcome to Java.

Here, the method displayMessage accepts a String parameter but does not return anything.

3. Without Input and With Output

These methods do not take any parameters but return a value.

Example:


class MasterBackend {
    // Method without input and with output
    int getNumber() {
        return 100; // Returning a value
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        int number = obj.getNumber(); // Storing the returned value
        System.out.println("The number is: " + number);
    }
}

Output:


The number is: 100

The method getNumber does not take any input but returns an integer value.

4. With Input and With Output

These methods take input parameters and also return a value.

Example:


class MasterBackend {
    // Method with input and with output
    int addNumbers(int a, int b) {
        return a + b; // Returning the sum
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        int sum = obj.addNumbers(10, 20); // Passing inputs and storing output
        System.out.println("The sum is: " + sum);
    }
}

Output:


The sum is: 30

The method addNumbers takes two integer parameters and returns their sum.

Method Overloading

Method Overloading allows multiple methods within the same class with the same name but different parameters (e.g., different numbers, types, or sequences of parameters).

1. Defining Multiple Methods with the Same Name but Different Parameters

Java determines which method to call based on the arguments passed.

Example:

class MasterBackend {
    // Method with one parameter
    void display(int num) {
        System.out.println("Number: " + num);
    }

    // Overloaded method with two parameters
    void display(int num, String text) {
        System.out.println("Number: " + num + ", Text: " + text);
    }

    public static void main(String[] args) {
        MasterBackend obj = new MasterBackend();
        obj.display(10); // Calls the first method
        obj.display(20, "Java"); // Calls the second method
    }
}

Output:


Number: 10
Number: 20, Text: Java

Here, the method is overloaded based on the number of parameters.

Method Overriding

Method Overriding occurs when a subclass provides a new implementation of a method that already exists in its superclass.

1. Overriding Methods in Subclasses

A subclass can override a method from its parent class using the same method signature.

Example:

class Parent {
    void showMessage() {
        System.out.println("Message from Parent class");
    }
}

class Child extends Parent {
    // Overriding the method
    @Override
    void showMessage() {
        System.out.println("Message from Child class");
    }

    public static void main(String[] args) {
        Child obj = new Child();
        obj.showMessage(); // Calls the overridden method in Child class
    }
}

Output:


Message from Child class

Here, showMessage() is overridden in the Child class.

2. @Override Annotation

The @Override annotation ensures that a method correctly overrides a method from its parent class.

Benefits of @Override:

  • Helps catch errors if the method signature does not match.

  • Improves code readability.

Example Without @Override (Incorrect Overriding)

class Parent {
    void showMessage() {
        System.out.println("Message from Parent");
    }
}

class Child extends Parent {
    // Mistakenly changed method signature (wrong overriding)
    void showMessage(int num) { // This is NOT overriding
        System.out.println("Message from Child: " + num);
    }
}

Here, showMessage(int num) is not actually overriding the parent method because its signature is different.

With @Override, Java will catch such errors:


class Child extends Parent {
    @Override
    void showMessage(int num) { // Compilation Error: Method does not override parent method
        System.out.println("Message from Child: " + num);
    }
}

3. Differences Between Overloading and Overriding

Feature

Method Overloading

Method Overriding

Definition

Multiple methods with the same name but different parameters.

A method in a subclass redefines a method from the parent class.

Parameters

Must be different (number, type, or order).

Must be exactly the same as the parent method.

Return Type

Can be the same or different.

Must be the same (or covariant return type).

Access Modifier

Can be changed.

Cannot be more restrictive than the parent method.

Inheritance Needed?

No, can exist in the same class.

Yes, requires inheritance (subclass and superclass).

Static Methods?

Can be overloaded.

Cannot be overridden, but can be hidden (method hiding).

Use Case

Used when we need similar functionalities with different inputs.

Used to modify behavior of a method from the parent class.

Conclusion

Java methods play a crucial role in structuring programs by enabling code reusability, modularity, and better organization. They help in breaking down large codebases into smaller, manageable blocks, making the program easier to read, maintain, and debug.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board