Java Methods


Methods in Java are blocks of code designed to perform a specific task. They help you organize and reuse code, making programs more readable and efficient. Instead of writing the same logic multiple times, you can write it once inside a method and call it whenever needed.

What Is a Method in Java?

A method is a collection of statements grouped together to perform an operation. For example, a method can calculate the sum of numbers, print a message, or return a value based on inputs. You can think of it as a small machine inside your program that takes input, processes it, and gives an output.

Example:

public static void greet() {
    System.out.println("Welcome to Java Methods!");
}

Here, greet() is a method that prints a message when called.

Importance of Methods

Methods make code modular and organized. Instead of writing a long block of code, you can divide your logic into smaller, reusable sections. This improves clarity, reduces errors, and saves time during debugging or updates.

Syntax of a Java Method

The basic syntax of a method is as follows:

modifier returnType methodName(parameters) {
    // method body
}

Let’s break this down:

  • modifier: Defines access level (like public, private, or protected).

  • returnType: Defines the type of value the method will return. If it returns nothing, use void.

  • methodName: The name used to identify and call the method.

  • parameters: Optional values passed to the method.

  • method body: Contains the actual statements that define the method’s behavior.

Example:

public static int add(int a, int b) {
    return a + b;
}

Here, add() takes two integers as parameters and returns their sum.

Calling a Method

To execute a method, you must call it. If the method is in the same class and declared as static, you can call it directly using its name.

public class Main {
    public static void main(String[] args) {
        greet(); // calling the greet method
        int sum = add(5, 10);
        System.out.println("Sum: " + sum);
    }

    public static void greet() {
        System.out.println("Hello, Java!");
    }

    public static int add(int a, int b) {
        return a + b;
    }
}

If the method is not static, you must create an object of the class to call it:

Main obj = new Main();
obj.greet();

Return Type in Methods

A method can return a value of any data type, such as int, double, String, or even an object. If a method doesn’t return anything, its return type is void.

Example of a method returning a value:

public static int multiply(int x, int y) {
    return x * y;
}

Example of a method with void return type:

public static void displayMessage() {
    System.out.println("This method doesn’t return anything.");
}

Static and Non-Static Methods

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

  • Non-static methods belong to an instance and require an object to be invoked.

Example:

public class Example {
    public void instanceMethod() {
        System.out.println("This is a non-static method.");
    }

    public static void staticMethod() {
        System.out.println("This is a static method.");
    }

    public static void main(String[] args) {
        staticMethod(); // no object needed
        Example obj = new Example();
        obj.instanceMethod(); // object required
    }
}

Method Parameters

Methods can take parameters (also called arguments) to work with data passed from outside. You can pass multiple parameters, separated by commas.

Example:

public static void introduce(String name, int age) {
    System.out.println("My name is " + name + " and I am " + age + " years old.");
}

When you call this method:

introduce("Riya", 22);

It will print:
My name is Riya and I am 22 years old.

Method with Return Value Example

Let’s look at a simple example that returns a calculated result:

public static double calculateAverage(double a, double b, double c) {
    return (a + b + c) / 3;
}

You can call it in the main method:

double avg = calculateAverage(10.5, 8.0, 9.5);
System.out.println("Average: " + avg);

Method Reusability

One of the biggest benefits of methods is code reusability. Once a method is written, it can be used multiple times in different parts of the program or even in other classes by importing them.

Methods with Conditions and Loops

Methods can include if-else conditions or loops to make them more dynamic.
Example:

public static void checkEvenOdd(int number) {
    if (number % 2 == 0)
        System.out.println(number + " is Even.");
    else
        System.out.println(number + " is Odd.");
}

This makes methods versatile and practical for handling logic-based operations.

Method Naming Conventions

  • Always use a verb or action-oriented name, like calculateTotal() or printMessage().

  • Start with a lowercase letter and use camelCase for multiple words.

  • Be descriptive enough to indicate what the method does.

Summary of the Tutorial

Java methods are the foundation of modular programming. They let you divide large programs into smaller, reusable blocks that are easier to maintain and test. Every Java program uses methods, including the main() method, which serves as the entry point. Understanding how to declare, call, and structure methods is essential to writing clean and efficient Java code.


Practice Questions

  1. Write a Java program to create a method that prints “Welcome to Java Programming” and call it from the main method.

  2. Create a Java method that takes two numbers as input and returns their sum. Call this method from the main method and print the result.

  3. Write a program that defines a method to check whether a given number is even or odd and display the result.

  4. Develop a Java program with a method that takes a name as input and prints a personalized greeting message.

  5. Write a method that accepts two numbers and returns the larger one. Call this method with different pairs of numbers.

  6. Create a Java method that calculates the square of a given number and returns the result.

  7. Write a program that defines a method to find the factorial of a number and prints the result in the main method.

  8. Develop a Java method that takes three subject marks as arguments and returns the average of the marks.

  9. Write a method that accepts a string and returns the number of vowels present in that string.

  10. Create a Java program that defines a method to check whether a given year is a leap year or not and prints the result accordingly.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top