Using Methods in Java

In Java, methods are blocks of code designed to perform actions when called from another part of the program. Each method has an access modifier (public or private), a return type (such as int, String, or void for methods that do not return anything), a method name, and possibly some parameters enclosed in parentheses. These parameters act as input to the method. The actual code the method must execute is defined in a pair of curly braces. If a method is designed to return some value, you can use its output in various ways, such as as part of a calculation or by assigning it to a variable. In this Java Methods Example, we create a method and call it from another method. Click Execute to run the Java Methods Example online and see the results.
Using Methods in Java Execute
public class MethodDemo {
    public int addNumbers(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        MethodDemo demo = new MethodDemo();

        int result = demo.addNumbers(5, 3);
        System.out.println("Sum: " + result);
    }
}
Updated: Viewed: 43 times