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:
| Parameter | Type | Description |
|---|---|---|
| static | Keyword | Belongs to the class rather than an object instance. |
| Overloading | Feature | Same method name with different parameter types/counts. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Java Lambda Expressions and Functional Interfaces
Write concise functional code using Java 8+ lambda expressions and Predicates.
Java Classes and Object-Oriented Programming (OOP)
Construct blueprints with constructors, private fields, getters, and setters.
Java Exception Handling: try, catch, finally, and throws
Catch and throw checked and unchecked exceptions safely using try-catch-finally blocks.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.