Methods help you organize your code into small, reusable actions. They make your program easier to read and use.
0
0
Method declaration in Java
Introduction
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.
Syntax
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.
Examples
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; }
Sample 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
Important 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.
Summary
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.
