DEV Community

Jane for Mastering Backend

Posted on • Originally published at masteringbackend.com

Methods and Functions in Java

Methods and Functions in Java

This post is part of the "Java Backend Development: Zero to Hero" series

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)  
}

Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
    }
}

Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output

Sum: 15
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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)
}



Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Example:


public int add(int a, int b) {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

  • 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.

access explained

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");
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

  • 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!");
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Method with a return type (int)

public int multiply(int a, int b) {
    return a * b;
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Method returning a String

public String getGreeting(String name) {
    return "Hello, " + name + "!";
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

  • 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
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:

Hello from MasterBackend!
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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();
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


Static Method Called!
Non-Static Method Called!
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

  • 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
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


Hello, Welcome to Java Programming!
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


Hello, Ayush! Welcome to Java.
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


The number is: 100
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


The sum is: 30
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


Number: 10
Number: 20, Text: Java
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

Output:


Message from Child class
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Use our Online Code Editor

3. Differences Between Overloading and Overriding

over loading and overriding explained

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.

Have a great one!!!

Author: by Ayush Shrivastava


Thank you for being a part of the community

Before you go:

Whenever you’re ready

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

  • The MB Platform: Join thousands of 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 Boot Camp to produce great backend engineers.
  • Join Backend Weekly: If you like posts 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.

Read Full “Java Backend Development: Zero to Hero”

This guide helps aspiring developers master Java backend development from the ground up. It covers Java Core, Spring Boot, RESTful APIs, Hibernate, Spring Security, Microservices, and design patterns, ensuring a strong foundation and practical skills. Whether you’re a beginner or looking to enhance your expertise, this step-by-step resource equips you to become a backend development expert. click here to read

Top comments (0)