R
Rishtaara
Java Fundamentals
Lesson 10 of 36Article15 min

Methods & Challenge

A method is a named function inside a class. It can take parameters and return a value.

Methods — reusable blocks of code

A method is a named function inside a class. It can take parameters and return a value.

Syntax: accessModifier returnType methodName(params) { body }. void means no return value.

Real-life example: A method is a recipe card — "makeChai()" always makes chai the same way when you call it.

Simple methods
public class Calculator {
    static int add(int a, int b) {
        return a + b;
    }

    static void greet(String name) {
        System.out.println("Hello, " + name);
    }

    public static void main(String[] args) {
        System.out.println(add(5, 3)); // 8
        greet("Asha");
    }
}

Challenge — practice methods

Try writing: maxOfThree(a,b,c), isEven(n), and printTable(n) that prints multiplication table.

Keep methods small — one job each. Test with main before moving on.

Real-life example: Challenge is like homework — you learn by doing, not just reading the recipe.

Challenge: Write a method celsiusToFahrenheit(double c) that returns (c * 9/5) + 32. Call it from main with 25.