CS Engineering Gyan

Methods in Java

As programs grow larger, writing all the logic inside a single main method quickly becomes messy and difficult to manage. Imagine repeating the same calculation in five different places throughout your code, only to later realize it needs to be changed. Updating every single occurrence manually would be time-consuming and prone to errors. This is exactly the kind of problem methods are designed to solve.

A method in Java is a block of code that performs a specific task and can be reused wherever needed, simply by calling its name. Instead of writing the same logic repeatedly, you define it once inside a method and call that method every time the task needs to be performed.

In this tutorial, you will learn how to declare and call methods, how parameters and return values work, the difference between static and non-static methods, how method overloading allows multiple versions of the same method, and how recursion enables a method to call itself.


What is a Method in Java?

A method is a named block of code designed to perform a particular task. It can accept input values, process them, and optionally return a result back to the part of the program that called it. Methods help break down complex programs into smaller, manageable, and reusable pieces.

Example

public class MethodIntroExample {

    static void printWelcomeMessage() {

        System.out.println("Welcome to CS Engineering Gyan!");

    }

    public static void main(String[] args) {

        printWelcomeMessage();

    }

}

Output

Welcome to CS Engineering Gyan!

Here, printWelcomeMessage is a method that displays a fixed message. Instead of writing the print statement directly inside the main method, it is defined separately and simply called when needed.


Structure of a Method

Every method in Java follows a consistent structure, made up of several important parts that define how it behaves and how it can be used.

Syntax

accessModifier returnType methodName(parameterList) {

    // method body

    return value;

}
Component Description
Access Modifier Controls who can access the method, such as public or private.
Return Type Specifies the type of value the method will return, or void if nothing is returned.
Method Name The identifier used to call the method elsewhere in the program.
Parameter List Defines the values the method accepts as input, if any.
Method Body Contains the actual instructions the method executes.

Understanding each of these parts makes it much easier to read unfamiliar code and design your own methods with a clear purpose in mind.


Methods Without Parameters or Return Values

The simplest type of method neither accepts input nor returns a value. These methods are often used for tasks like displaying fixed information or performing an action that does not depend on external input.

Example

public class SimpleMethodExample {

    static void showChannelInfo() {

        System.out.println("Channel: CS Engineering Gyan");

        System.out.println("Category: Programming Tutorials");

    }

    public static void main(String[] args) {

        showChannelInfo();

    }

}

Output

Channel: CS Engineering Gyan

Category: Programming Tutorials

The void keyword indicates that this method does not return any value. It simply performs an action, in this case, printing information to the console.


Methods with Parameters

Parameters allow a method to accept input values from the code that calls it, making the method far more flexible and reusable for different situations.

Example

public class ParameterExample {

    static void displayVideoInfo(String title, int views) {

        System.out.println("CS Engineering Gyan - " + title + " (" + views + " views)");

    }

    public static void main(String[] args) {

        displayVideoInfo("Java Methods Explained", 4300);

        displayVideoInfo("Arrays in Java", 5100);

    }

}

Output

CS Engineering Gyan - Java Methods Explained (4300 views)

CS Engineering Gyan - Arrays in Java (5100 views)

In this example, the same method is called twice with different values, avoiding the need to write separate print statements for each video's information individually.


Methods with Return Values

Many methods are designed to calculate a result and send it back to the caller, rather than printing it directly. This is done using the return keyword, along with a return type other than void.

Example

public class ReturnValueExample {

    static int calculateTotalViews(int mondayViews, int tuesdayViews) {

        return mondayViews + tuesdayViews;

    }

    public static void main(String[] args) {

        int total = calculateTotalViews(1500, 1800);

        System.out.println("CS Engineering Gyan total views: " + total);

    }

}

Output

CS Engineering Gyan total views: 3300

Here, the method calculateTotalViews returns an integer value, which is then stored inside the variable total and used later in the program. This separation between calculation and usage makes code more organized and reusable.


Static vs Non-Static Methods

Java methods can be classified as either static or non-static, depending on whether they belong to the class itself or to individual objects created from that class.

Static Methods Non-Static Methods
Belong to the class rather than any specific object. Belong to individual objects created from the class.
Can be called directly using the class name. Require an object to be created before calling.
Cannot directly access non-static variables or methods. Can access both static and non-static members freely.

Example

class Channel {

    String name = "CS Engineering Gyan";

    void displayName() {

        System.out.println("Channel Name: " + name);

    }

}

public class NonStaticExample {

    public static void main(String[] args) {

        Channel channel = new Channel();

        channel.displayName();

    }

}

Output

Channel Name: CS Engineering Gyan

Since displayName is a non-static method, it must be called using an object of the Channel class, unlike static methods, which can be called directly using the class name without creating an object first.


Method Overloading

Method overloading allows a class to have multiple methods with the same name, as long as their parameter lists differ in number, type, or order. This makes it possible to perform similar operations on different kinds of input using a single, consistent method name.

Example

public class OverloadingExample {

    static int addViews(int views1, int views2) {

        return views1 + views2;

    }

    static int addViews(int views1, int views2, int views3) {

        return views1 + views2 + views3;

    }

    public static void main(String[] args) {

        System.out.println("CS Engineering Gyan two-day total: " + addViews(1200, 1400));

        System.out.println("CS Engineering Gyan three-day total: " + addViews(1200, 1400, 1600));

    }

}

Output

CS Engineering Gyan two-day total: 2600

CS Engineering Gyan three-day total: 4200

Java automatically determines which version of addViews to call based on the number of arguments passed during the method call, allowing both versions to coexist under the same method name.


Passing Arrays to Methods

Methods can also accept arrays as parameters, which is especially useful when a calculation needs to be performed on a collection of related values rather than just one or two individual numbers.

Example

public class ArrayParameterExample {

    static int calculateTotal(int[] weeklyViews) {

        int total = 0;

        for (int views : weeklyViews) {

            total += views;

        }

        return total;

    }

    public static void main(String[] args) {

        int[] views = {1500, 1800, 2100, 1950, 2200};

        int weeklyTotal = calculateTotal(views);

        System.out.println("CS Engineering Gyan weekly total views: " + weeklyTotal);

    }

}

Output

CS Engineering Gyan weekly total views: 9550

This approach keeps the main method clean and readable, while the actual calculation logic is handled separately inside its own dedicated method.


Recursion in Java

Recursion occurs when a method calls itself in order to solve a problem by breaking it down into smaller, similar subproblems. Every recursive method requires a base case, a condition that stops the recursive calls from continuing indefinitely.

Example

public class RecursionExample {

    static int calculateFactorial(int number) {

        if (number == 0) {

            return 1;

        }

        return number * calculateFactorial(number - 1);

    }

    public static void main(String[] args) {

        int result = calculateFactorial(5);

        System.out.println("Factorial of 5: " + result);

    }

}

Output

Factorial of 5: 120

In this example, calculateFactorial keeps calling itself with a smaller number each time, until it reaches the base case where the number equals zero, at which point the recursive calls begin returning their results back up the chain.


Why Use Methods?


Method Signature and Overloading Rules

A method's signature consists of its name along with the number, type, and order of its parameters. Java uses this signature to distinguish between overloaded methods that share the same name.

Rule Description
Different number of parameters Two methods with the same name can have a different number of parameters.
Different parameter types Methods can share a name if their parameter data types are different.
Different parameter order Changing the order of different data types in the parameter list also creates a valid overload.
Return type alone is not enough Changing only the return type, without changing parameters, does not count as valid overloading.

Best Practices While Writing Methods


Common Mistakes Beginners Make

Mistake Correct Practice
Forgetting to include a return statement in a non-void method. Ensure every possible path in a non-void method returns a value.
Calling a non-static method directly from a static context without an object. Create an object of the class first before calling non-static methods.
Writing a recursive method without a proper base case. Always define a clear stopping condition to prevent infinite recursion.
Confusing method overloading with simply changing the return type. Remember that valid overloading requires a different parameter list, not just a different return type.

Frequently Asked Interview Questions

  1. What is a method in Java?
    A method is a reusable block of code designed to perform a specific task, which can accept input and optionally return a result.
  2. What is the difference between a parameter and an argument?
    A parameter is the variable defined in the method declaration, while an argument is the actual value passed during a method call.
  3. What does the void keyword mean in a method declaration?
    It indicates that the method does not return any value.
  4. What is method overloading?
    Method overloading allows multiple methods to share the same name as long as their parameter lists differ.
  5. What is the difference between static and non-static methods?
    Static methods belong to the class and can be called without an object, while non-static methods require an object to be called.
  6. What is recursion in Java?
    Recursion is when a method calls itself to solve a problem by breaking it into smaller subproblems.
  7. Why is a base case important in a recursive method?
    A base case stops the recursive calls from continuing indefinitely, preventing infinite recursion.
  8. Can an array be passed as a parameter to a method?
    Yes, arrays can be passed to methods just like any other data type, allowing operations on collections of values.

Summary

Methods are one of the most important tools for organizing Java programs into clean, reusable, and maintainable pieces of code. By learning how to declare methods, pass parameters, return values, and distinguish between static and non-static behavior, you gain the ability to structure programs far more efficiently than relying on a single, lengthy main method.

Concepts such as method overloading and recursion further extend what methods can accomplish, allowing the same method name to handle different situations, or enabling a method to solve problems by calling itself with smaller inputs. Together, these tools form an essential foundation for writing well-structured Java programs.

With a solid understanding of methods, you are now ready to explore Object-Oriented Programming concepts, where methods play a central role in defining the behavior of classes and objects.


← Previous: Arrays in Java Next: Object-Oriented Programming →

Home Visit Our YouTube Channel