Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Java Methods

Method Declaration Syntax

A method is a reusable block of code that performs a specific task. The general syntax is:

Method Syntax
accessModifier returnType methodName(parameterList) {
    // method body
    return value; // if returnType is not void
}
Method Declaration & Overloading
public class Methods {

    // Static method — no object needed
    public static int add(int a, int b) {
        return a + b;
    }

    // Method overloading — same name, different parameters
    public static double add(double a, double b) {
        return a + b;
    }

    public static int add(int a, int b, int c) {
        return a + b + c;
    }

    // void method — no return value
    public static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        System.out.println(add(3, 4));          // 7   (int version)
        System.out.println(add(1.5, 2.5));      // 4.0 (double version)
        System.out.println(add(1, 2, 3));       // 6   (3-param version)
        greet("Alice");                          // Hello, Alice!
    }
}

Varargs (Variable Arguments)

Varargs let a method accept any number of arguments of the same type. The varargs parameter must be the last parameter and is treated as an array inside the method.

Varargs & Recursion
public class VarargsRecursion {

    // Varargs — accepts 0 or more int arguments
    public static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }

    // Recursion — factorial
    public static long factorial(int n) {
        if (n <= 1) return 1;          // base case
        return n * factorial(n - 1);   // recursive call
    }

    public static void main(String[] args) {
        // Varargs
        System.out.println(sum());           // 0
        System.out.println(sum(5));          // 5
        System.out.println(sum(1, 2, 3));    // 6
        System.out.println(sum(1,2,3,4,5));  // 15

        // Recursion
        System.out.println(factorial(5));    // 120
        System.out.println(factorial(10));   // 3628800
    }
}

Static vs Instance Methods

FeatureStatic MethodInstance Method
Belongs toThe classAn object (instance)
Called withClassName.method()object.method()
Can access instance fields?NoYes
Can access static fields?YesYes
Typical useUtility/helper methodsObject behavior

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.