Methods
Methods
Complete lesson for Methods using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Methods
Section: Methods. Java methods (not free functions): signature, instance vs static, overloading, varargs, pass-by-value, and return types.
What is a method?
- A method is a named block of code that belongs to a class or to an object. It can take parameters, do work, and optionally return a value.
- Java has no free-standing functions like C or Python. Every piece of behavior lives inside a class as a method (instance or
static). - Real-life idea: a method is a skill of a type —
Account.deposit,String.length,Math.max— not a loose recipe sitting outside any type.
| Part | Meaning | Example |
|---|---|---|
| Name | How you call it | add, greet, main |
| Parameters | Input values | int a, int b |
| Return type | What comes back | int, String, void |
| Body | The statements that run | { return a + b; } |
public class MethodBasics {
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hi, " + name);
}
public static void main(String[] args) {
greet("Ada");
System.out.println(add(2, 3));
}
} Differences between function and method
- In theory, a function is a reusable procedure. A method is a function that belongs to an object or a class.
- C and C++ allow free functions (
int add(int a, int b)at file scope). Java does not —addmust sit inside a class. - People still say “function” in casual talk. In Java interviews, say method. C++ member functions are methods; free functions are not.
| Point | Function | Method |
|---|---|---|
| Definition | A standalone reusable block of code | A function that belongs to a class or object |
| Where it lives | File / namespace / module (C, C++, Python) | Always inside a class (Java) |
| Java support | No top-level functions | The only option — instance or static |
| Typical call | add(2, 3) with no owner | obj.add(2, 3) or Math.max(2, 3) |
this / receiver | None | Instance methods have this (the current object) |
| Access to fields | Only through arguments | Can read/write the object’s fields (if instance) |
| OOP role | Optional helper | The unit of behavior in a class |
| C / C++ | Free function is normal | Member function = method |
| Python | def add(a, b): at module level | def add(self, b): on a class |
| Lambdas in Java | Not free functions | Objects that implement a functional interface (still methods under the hood) |
Anatomy of a Java method
- Order: modifiers, return type, name, parameter list, optional
throws, then a body (or;ifabstract/native). voidmeans no return value.return;exits early from a void method. A non-void method must return on every path.- Access modifiers (
public,private,protected, package-private) control who can call the method.
| Piece | Required? | Notes |
|---|---|---|
| Modifiers | No | public, static, final, abstract, … |
| Return type | Yes | void or a type (int, String, …) |
| Name | Yes | Verb style: calculateTax |
(parameters) | Yes (may be empty) | Types + names; varargs last |
throws list | No | Checked exceptions the caller must handle |
{ body } | Yes (unless abstract/native) | The work |
Instance methods vs static methods
- Instance methods need an object. They can use
thisand instance fields. staticmethods belong to the class. Call them asClassName.method(...). They cannot usethisor instance fields.- Real-life:
account.deposit(100)is instance (this account).Math.max(a, b)is static (no particular Math object).
| Point | Instance method | Static method |
|---|---|---|
| Belongs to | An object | The class |
| Call | obj.work() | Class.work() |
this | Yes | No |
| Instance fields | Yes | No (only static fields) |
| Typical use | Object behavior | Utilities, main, factories |
public class Account {
int balance;
void deposit(int amount) {
this.balance += amount;
}
static int max(int a, int b) {
return a > b ? a : b;
}
public static void main(String[] args) {
Account a = new Account();
a.deposit(50);
System.out.println(a.balance);
System.out.println(Account.max(3, 9));
}
} Overloading vs overriding (preview)
- Overloading: same method name, different parameter lists, chosen at compile time. Return type alone cannot distinguish overloads.
- Overriding: same signature in a subclass, chosen at runtime — covered fully under polymorphism.
| Idea | Overloading | Overriding |
|---|---|---|
| Where | Same class (or inherited name) | Subclass / implementing class |
| Parameters | Must differ | Must match (same signature) |
| When chosen | Compile time | Runtime (virtual dispatch) |
| Keywords | None special | @Override, cannot be static |
Varargs and pass-by-value
void log(String... parts)is an array parameter. It must be the last parameter. A calllog()passes a zero-length array, notnull.- Java is pass-by-value. For primitives the bits are copied. For objects the reference is copied: the method can mutate the object, but
obj = somethingElsedoes not change the caller variable.
public class PassByValue {
static void bump(int n) {
n = 100;
}
static void addItem(java.util.ArrayList<String> list) {
list.add("x");
}
public static void main(String[] args) {
int n = 1;
bump(n);
System.out.println(n); // still 1
java.util.ArrayList<String> list = new java.util.ArrayList<>();
addItem(list);
System.out.println(list); // [x]
}
} Advanced — Methods
Signatures, hiding, and main
- The JVM signature is name + parameter types (type erasure applies to generics).
throwsis not part of the overload key. - A static method with the same signature in a subclass hides the parent method; it does not override.
maincan be overloaded, but the launcher only callspublic static void main(String[]).- Avoid too many overloads that differ only by
intvsIntegeror array vs varargs — the compiler most-specific rule surprises people.
Why Java uses methods, not free functions
- Encapsulation: behavior stays next to the data it uses (
balance+deposit). - Polymorphism needs methods on types so a subclass can override
draw()orcompareTo. - You can still write “function-like” code as
statichelpers (Math,Collections) — they are methods on a class, not file-scope functions. - Java 8+ lambdas look like tiny functions, but they compile to objects with a single method (
apply,test,run).
Tricky Interview Points
Q1) Difference between a function and a method?
Answer A function is a standalone reusable block. A method is a function that belongs to a class or object. Java has only methods — no top-level functions like C or Python.
Q2) Does Java have functions?
Answer Not as top-level functions. You write methods on classes (instance or static). Lambdas are instances of functional interfaces, not free functions.
Q3) What is pass-by-value in Java?
Answer Arguments are copied. For primitives the bits are copied. For objects the reference is copied, so the callee can change the object state but not the caller reference variable.
Q4) Can you overload by return type only?
Answer No. The parameter list must differ. Return type is not part of the overload identity.
Q5) What are varargs?
Answer A variable-arity parameter written Type... name. The compiler packs arguments into an array. Only one varargs, and it must be last.
Q6) static method vs instance method?
Answer static belongs to the class and cannot use this or instance fields. Instance methods need an object and can use this.
Q7) Is main a special keyword?
Answer No. It is a method the launcher looks up by signature. You can have other methods named main.
Q8) What is a method signature in Java?
Answer Name plus parameter types. Modifiers, return type, and throws are not part of the overload signature.
Q9) Can a static method call an instance method?
Answer Only through an object reference. From main you write obj.work(), not work(), unless work is also static.
Q10) C++ free function vs Java static method?
Answer A C++ free function lives at namespace/file scope. A Java static method still belongs to a class (Math.max). Same call style, different ownership.
Simple Programs
Instance method vs static helper
public class TempConverter {
double celsius;
void setCelsius(double c) {
this.celsius = c;
}
double toFahrenheit() {
return celsius * 9 / 5 + 32;
}
static double freezePointF() {
return 32;
}
public static void main(String[] args) {
TempConverter t = new TempConverter();
t.setCelsius(100);
System.out.println(t.toFahrenheit());
System.out.println(TempConverter.freezePointF());
}
} Overload and varargs
public class OverloadDemo {
static int max(int a, int b) {
return a > b ? a : b;
}
static int max(int a, int b, int c) {
return max(max(a, b), c);
}
static int sum(int... nums) {
int s = 0;
for (int n : nums) s += n;
return s;
}
public static void main(String[] args) {
System.out.println(max(4, 9));
System.out.println(max(4, 9, 1));
System.out.println(sum(1, 2, 3, 4));
}
} Pass-by-value for int vs list
import java.util.ArrayList;
public class PassDemo {
static void setZero(int n) {
n = 0;
}
static void clear(ArrayList<String> list) {
list.clear();
}
public static void main(String[] args) {
int n = 7;
setZero(n);
System.out.println(n); // 7
ArrayList<String> list = new ArrayList<>();
list.add("keep?");
clear(list);
System.out.println(list.size()); // 0
}
} Problem Solving Tricks
- Name methods as verbs:
calculateTax, nottax. - Keep parameter lists short; wrap many options in an object or a builder.
- Do not overload
staticand instance methods with the same name unless you enjoy confusing readers. - Document units (
millis,indexInclusive) in the method name or Javadoc. - Say method in Java interviews, not function — unless you are contrasting with C/C++.
- Call
staticmethods on the class name (Math.max), not on an instance. - A void method can still change object state; “no return” is not “no effect”.
Practice Programs List
- Write a class
Boxwith instance methodssetSizeandvolume, plus a staticcubeVolume(int side). - Write overloaded
areamethods for circle (radius) and rectangle (width, height). - Write
average(double... values)that throws if length is 0. - Show pass-by-value: a method that does
x = 100on anintand one that doeslist.addon anArrayList. - Overload
printforint,String, andint[]. - Split a god method that reads, computes, and prints into three methods.
- From
main, call an instance method (neednew) and a static method (class name). - Explain in comments why
add(2, 3)is illegal in Java unlessaddisstaticin the same class (or imported statically). - Write two classes and show that a method in
Acannot be called like a C function fromBwithoutAor anAobject. - List three real-life examples of instance methods and three of static methods.