← Back to Chapters

Java Methods — Introduction

? Java Methods — Introduction

? Quick Overview

In Java, a method is a block of code that performs a specific task. Methods help break large programs into smaller, reusable, and manageable pieces.

? Key Concepts

  • A method runs only when it is called
  • Methods improve code reusability
  • Each method has a name, return type, and parameters
  • Java programs mainly run inside the main() method

? Syntax / Theory

A Java method consists of access modifier, return type, method name, parameters, and method body.

? View Code Example
// Basic structure of a Java method
accessModifier returnType methodName(parameters) {
    // method body
}

? Code Example(s)

? View Code Example
// Java program demonstrating a simple method
class MethodDemo {
    static void greet() {
        System.out.println("Hello, welcome to Java methods!");
    }

    public static void main(String[] args) {
        greet();
    }
}

?️ Live Output / Explanation

Output

Hello, welcome to Java methods!

The greet() method is called from the main() method. When called, it executes the code inside it and prints the message.

? Interactive Playground

Experiment with passing parameters. Enter numbers below and click "Run Method" to see how Java processes the inputs.

// Visualizing Method Call
int sum = addNumbers(5, 10);

// Method Definition
static int addNumbers(int a, int b) {
  return a + b;
}
> System.out.println(sum);
Output: 15

✅ Tips & Best Practices

  • Use meaningful method names
  • Keep methods short and focused
  • Reuse methods instead of duplicating code
  • Follow camelCase naming convention

? Try It Yourself

  • Create a method that adds two numbers
  • Create a method that prints your name
  • Call one method from another method