0
0
Javaprogramming~15 mins

Method declaration in Java

Choose your learning style8 modes available
menu_bookIntroduction

Methods help you organize your code into small, reusable actions. They make your program easier to read and use.

When you want to repeat a task many times without rewriting code.
When you want to break a big problem into smaller, manageable parts.
When you want to give a name to a set of instructions for clarity.
When you want to reuse code in different places of your program.
When you want to make your program easier to test and fix.
regular_expressionSyntax
Java
accessModifier returnType methodName(parameterList) {
    // method body
}

accessModifier controls who can use the method (like public or private).

returnType is the type of value the method gives back, or void if it returns nothing.

emoji_objectsExamples
line_end_arrow_notchA method that prints a greeting and returns nothing.
Java
public void sayHello() {
    System.out.println("Hello!");
}
line_end_arrow_notchA method that adds two numbers and returns the result.
Java
private int add(int a, int b) {
    return a + b;
}
line_end_arrow_notchA method that checks if a number is even and returns true or false.
Java
public boolean isEven(int number) {
    return number % 2 == 0;
}
code_blocksSample Program

This program has two methods: one to greet the user and one to add two numbers. The main method calls them to show how methods work.

Java
public class Main {
    public static void main(String[] args) {
        greetUser();
        int sum = addNumbers(5, 7);
        System.out.println("Sum: " + sum);
    }

    public static void greetUser() {
        System.out.println("Welcome to the program!");
    }

    public static int addNumbers(int x, int y) {
        return x + y;
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Method names usually start with a lowercase letter and use camelCase.

line_end_arrow_notch

Parameters inside parentheses are inputs the method needs to work.

line_end_arrow_notch

Use return to send a value back from the method.

list_alt_checkSummary

Methods group code into reusable blocks with a name.

They can take inputs (parameters) and give back outputs (return values).

Declaring methods helps keep your code clean and organized.