Java Methods Tutorial for Beginners
Last Updated on: 23rd Oct 2025 09:28:25 AM
Welcome to this beginner-friendly tutorial on Methods in Java! Methods, sometimes called functions in other programming languages, are reusable blocks of code that perform specific tasks. They make your code organized, modular, and easier to maintain. This tutorial is designed for beginners, with clear explanations and practical examples you can run in any Java environment (e.g., Eclipse, IntelliJ, or online compilers like Repl.it).
By the end, you’ll understand how to create, use, and customize methods to make your Java programs more efficient. Let’s get started!
What Are Methods in Java?
A method is a named block of code that performs a specific task and can be called whenever needed. Think of it like a recipe: you define the steps once (the method) and use it multiple times without rewriting the code.
Key Features:
-
Methods can take inputs (called parameters) and return outputs (called return values).
-
They help avoid code duplication and improve readability.
-
Every Java program has at least one method: main, where execution starts.
Example Analogy: A method is like a blender. You define how it works (blend fruits), give it inputs (fruits), and get an output (smoothie).
1. Defining a Method
A method is defined with a method signature that specifies its name, parameters, return type, and access level.
Syntax:
accessModifier returnType methodName(parameterList) {
// Code to execute
// Optional: return statement
}
-
accessModifier: Controls visibility (e.g., public, private). Use public for now.
-
returnType: The data type of the value returned (e.g., int, String, or void for no return).
-
methodName: A descriptive name (e.g., calculateSum).
-
parameterList: Inputs the method needs (e.g., int a, int b). Can be empty.
-
return: Sends a value back (required if returnType isn’t void).
Example: A Simple Method
Let’s create a method to print a greeting.
public class SimpleMethodExample {
// Method definition
public static void sayHello() {
System.out.println("Hello, welcome to Java!");
}
public static void main(String[] args) {
// Calling the method
sayHello();
sayHello(); // Call it again
}
}
Output:
Hello, welcome to Java!
Hello, welcome to Java!
Explanation:
-
The sayHello method has no parameters and a void return type (no return value).
-
It’s called twice in main, printing the message each time.
-
static means the method belongs to the class, not an object (more on this later).
Real-World Analogy: Like pressing a “print receipt” button on a machine—it does the same task every time you call it.
2. Methods with Parameters
Parameters let methods accept inputs to work with different data.
Syntax:
returnType methodName(parameterType parameterName) {
// Use parameterName in code
}
Example: Method with Parameters
Let’s create a method to add two numbers.
public class ParameterExample {
// Method with parameters
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum; // Return the result
}
public static void main(String[] args) {
// Call method with arguments
int result = addNumbers(5, 3);
System.out.println("Sum: " + result);
// Call with different arguments
System.out.println("Sum: " + addNumbers(10, 20));
}
}
Output:
Sum: 8
Sum: 30
Explanation:
-
The addNumbers method takes two int parameters (a, b).
-
It returns an int (the sum) using return.
-
In main, we call it with different values (arguments) and store/print the result.
Real-World Analogy: Like a vending machine where you input coins (parameters) to get a snack (return value).
3. Methods with Return Types
Methods can return data (e.g., int, String) or nothing (void). If a method has a return type, it must use return to send back a value.
Example: Method with Return Type
Let’s create a method to find the square of a number.
public class ReturnExample {
// Method that returns an int
public static int squareNumber(int num) {
return num * num;
}
public static void main(String[] args) {
int number = 4;
int result = squareNumber(number);
System.out.println("Square of " + number + " is: " + result);
}
}
Output:
Square of 4 is: 16
Explanation:
-
The squareNumber method takes an int parameter and returns an int (the square).
-
The return statement sends the result back to the caller.
-
In main, we store the returned value in result.
Beginner Tip: If the return type is void, you don’t need a return statement, but you can use return; to exit early.
4. Method Overloading
You can define multiple methods with the same name but different parameter lists (number, type, or order). This is called method overloading.
Example: Method Overloading
Let’s create methods to calculate areas for different shapes.
public class OverloadingExample {
// Area of a square
public static double calculateArea(double side) {
return side * side;
}
// Area of a rectangle
public static double calculateArea(double length, double width) {
return length * width;
}
public static void main(String[] args) {
System.out.println("Area of square (side 5): " + calculateArea(5.0));
System.out.println("Area of rectangle (4 x 6): " + calculateArea(4.0, 6.0));
}
}
Output:
Area of square (side 5): 25.0
Area of rectangle (4 x 6): 24.0
Explanation:
-
Two calculateArea methods exist: one for a square (one parameter), one for a rectangle (two parameters).
-
Java chooses the correct method based on the number of arguments.
Real-World Analogy: Like a chef with two recipes for “cake”: one for a round cake (one size parameter) and one for a sheet cake (length and width).
5. Using Methods with Input/Output
Let’s combine methods with user input using Scanner.
import java.util.Scanner;
public class CalculatorExample {
// Method to calculate power
public static double power(double base, double exponent) {
return Math.pow(base, exponent);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter base number: ");
double base = scanner.nextDouble();
System.out.print("Enter exponent: ");
double exponent = scanner.nextDouble();
double result = power(base, exponent);
System.out.println(base + " raised to " + exponent + " is: " + result);
scanner.close();
}
}
Sample Run:
Enter base number: 2
Enter exponent: 3
2.0 raised to 3.0 is: 8.0
Explanation:
-
The power method uses Math.pow to compute base raised to exponent.
-
Scanner gets user input, which is passed to the method.
-
The result is printed in main.
Real-World Analogy: Like a calculator app where you input numbers, and it computes the result using a predefined function.
6. Common Issues and Solutions
-
Problem: Method doesn’t return a value when expected.
-
Solution: Ensure the method has the correct return type and a return statement.
-
-
Problem: “Cannot find symbol” error when calling a method.
-
Solution: Check the method name, parameters, and ensure it’s defined in the class.
-
-
Problem: Infinite recursion (method calling itself endlessly).
-
Solution: Ensure recursive methods (advanced topic) have a base case to stop.
-
7. Practice Tips
-
Experiment: Create methods for different tasks, like finding the maximum of three numbers.
-
Test Code: Use an online compiler to try examples.
-
Common Mistake: Don’t forget to match the return type with the return value (e.g., int method must return an int).
-
Quiz Yourself: What does this method return for multiply(3, 4)?
public static int multiply(int x, int y) {
return x * y;
}
(Answer: 12)
Summary
-
Methods: Reusable code blocks that perform tasks.
-
Components: Access modifier, return type, name, parameters, and body.
-
Types:
-
No parameters/return (void).
-
With parameters and/or return values.
-
Overloaded (same name, different parameters).
-
-
Benefits: Code reuse, modularity, and clarity.
-
Next Steps: Combine methods with loops, conditionals, or input/output for more complex programs.
You’re now ready to create and use methods in Java! Keep practicing, and happy coding! ![]()