Methods in Java are blocks of code that perform specific tasks. They allow for code reuse and can take inputs (parameters) and return results (return values).
public class MethodExample { // Method that adds two numbers public static int addNumbers(int a, int b) { return a + b; } public static void main(String[] args) { int result = addNumbers(5, 3); System.out.println("The sum is: " + result); } }
This example defines a method addNumbers
that takes two integers as parameters, adds them, and returns the result. The method is called in the main
method.