← Back to Chapters

Method Declaration & Calling in Java

? Method Declaration & Calling in Java

? Quick Overview

In Java, a method is a block of code that performs a specific task. Methods help in code reusability, modular programming, and better readability. A method must be declared before it can be called.

? Key Concepts

  • Method declaration defines what the method does
  • Method calling executes the method
  • Methods may return a value or be void
  • Parameters allow passing data to methods

? Syntax / Theory

A method declaration consists of:

  • Access modifier
  • Return type
  • Method name
  • Parameter list
  • Method body
? View Code Example
// General syntax of a method declaration in Java
accessModifier returnType methodName(parameters) {
// method body
}

? Code Example(s)

? View Code Example
// Example demonstrating method declaration and calling
class Calculator {

// Method declaration
static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {

// Method calling
int result = add(10, 20);
System.out.println(result);
}
}

? Live Output / Explanation

Output

30

The add() method receives two integers, adds them, and returns the result. The returned value is stored in the variable result and printed.

? Interactive Method Simulator

Enter values below to simulate calling the add() method dynamically.

int result = add( , );
> System output will appear here...

? Tips & Best Practices

  • Use meaningful method names that describe the action
  • Keep methods short and focused on one task
  • Reuse methods to avoid duplicate code
  • Prefer parameters instead of hardcoded values

? Try It Yourself

  • Create a method to subtract two numbers
  • Write a method that returns the square of a number
  • Create a method without return value that prints a message