Java:Java Methods: Static Methods, Return Values, and Overloading
Java•Methods

Java Methods: Static Methods, Return Values, and Overloading

Methods encapsulate reusable logic in Java classes. Method overloading allows multiple methods with identical names but distinct parameter lists.

Syntax

public static return_type methodName(Type param1) { return val; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
staticKeywordBelongs to the class rather than an object instance.
OverloadingFeatureSame method name with different parameter types/counts.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Java locally:

public class Main {
    // 1. Method overloading: integer sum
    public static int add(int a, int b) {
        return a + b;
    }

    // 2. Overloaded method: double sum
    public static double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        int intResult = add(15, 25);
        double doubleResult = add(12.5, 7.5);

        System.out.println("Integer Sum: " + intResult);
        System.out.println("Double Sum:  " + doubleResult);
    }
}
Expected Output:
Integer Sum: 40
Double Sum:  20.0

How It Works: Step-by-Step

  • Lines 3-5: Defines add method for two integer arguments.
  • Lines 8-10: Overloads add method with double parameters.
  • Lines 13-14: Java compiler automatically routes calls based on argument types.

Key Concepts

  • Method overloading is resolved at compile time based on parameter types.
  • static methods can be called without instantiating an object of the class.
  • Java passes all arguments by value (for objects, it passes the reference by value).

Common Mistake: Trying to overload methods by return type alone

Overloading requires different parameter counts or types; varying only the return type is a compile error.

❌ Incorrect
int calc(int x) { return x; }
double calc(int x) { return x; } // Compile Error: already defined
✅ Correct
int calc(int x) { return x; }
double calc(double x) { return x; }

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler