how to write a method in java

how to write a method in java

1 month ago 22
Nature

To write a method in Java, follow these key steps:

Basic Structure of a Java Method

A method in Java is a block of code that performs a specific task. It consists of:

  • Access modifier (optional): Defines the visibility of the method (e.g., public, private).
  • Return type : The data type of the value the method returns. Use void if it returns nothing.
  • Method name : A meaningful identifier for the method.
  • Parameter list : Zero or more parameters enclosed in parentheses (). Parameters are optional.
  • Method body : Code enclosed in curly braces {} that defines what the method does.

Syntax

java

modifier returnType methodName(parameterList) {
    // method body
    // optional return statement if returnType is not void
}

Example: Writing a Simple Method

java

public class Main {

    // Method with no return value and no parameters
    public static void myMethod() {
        System.out.println("I just got executed!");
    }

    public static void main(String[] args) {
        // Calling the method
        myMethod();
    }
}

This method myMethod() prints a message when called

Example: Method with Parameters and Return Value

java

public class Main {

    // Method that takes two integers and returns their sum
    public int addNumbers(int a, int b) {
        int sum = a + b;
        return sum;
    }

    public static void main(String[] args) {
        Main obj = new Main(); // create an object to call the method
        int result = obj.addNumbers(25, 15);
        System.out.println("Sum is: " + result);
    }
}

Here, addNumbers takes two parameters and returns their sum

Notes

  • If a method returns a value, use the return keyword to return a value matching the declared return type.
  • If the method does not return a value, declare it as void and omit the return statement.
  • Methods must be declared inside a class.
  • To call a non-static method, create an object of the class first.
  • Static methods can be called directly using the class name or from within other static methods

This is the fundamental way to write and use methods in Java.

Read Entire Article