Free lesson · Java Basic To Advance
Methods Basics
Functions With a Receiver
A method in Java is a named block of code that takes inputs, performs work, and optionally returns a value. Conceptually, methods are functions — but in Java, every method belongs to a class. There are no standalone functions at the top level the way Python or JavaScript has them.
This single design choice — that everything is in a class — has shaped Java's structure for 30 years. Even the main method, the entry point of every Java program, lives inside a class.
Module 6 covers methods in depth. We start with the basics: declaration, parameters, calling conventions, the method signature. Later Topics cover parameters in detail (6.2), return types (6.3), overloading (6.4), varargs (6.5), recursion (6.6), and pass-by-value semantics (6.7). The module closes with a Signature Interview Lens (6.8).
I'm Olena, continuing through Module 6. Methods are where Java code starts to feel like real engineering — small, named, reusable units of behavior rather than long imperative scripts.
What a Method Looks Like
A complete method declaration:
public static int add(int a, int b) {
return a + b;
}
The parts:
public— access modifier (visible to everyone). Topic 7.5 covers access modifiers in detail.static— this method belongs to the class, not to instances. We cover static in detail in Topic 7.7.int— the return type. The method returns an int.add— the method name. Conventionally camelCase, verb-form.(int a, int b)— the parameter list. Two int parameters named a and b.{ ... }— the method body. The code that runs when the method is called.return a + b;— returns a value. Required for non-void methods.
To call this method:
int sum = add(3, 5);
// sum is 8
The values 3 and 5 are the arguments — the actual values passed in. Inside the method, the parameters a and b are bound to these values. The method computes a + b and returns the result, which gets assigned to sum.
The Method Signature
A method's signature is the part the compiler uses to identify it: name plus parameter types. Return type is NOT part of the signature.
public int add(int a, int b) // signature: add(int, int)
public double add(int a, int b) // SAME signature — would be a compile error
public int add(double a, double b) // different signature: add(double, double)
public int add(int a, int b, int c) // different signature: add(int, int, int)
This matters for method overloading (Topic 6.4) — you can have multiple methods with the same name but different parameter types. They have different signatures even though they share a name.
Two methods can't have the same signature in the same class. The compiler rejects this:
public class Calculator {
public int divide(int a, int b) { return a / b; }
public double divide(int a, int b) { return (double) a / b; } // compile error
}
Even though the return types differ, the signature is the same. The compiler can't distinguish them at call sites.
Interactive animation: Renaming parameters or changing only the return type leaves the signature the same, so the compiler rejects the second method.
Calling Methods
When you call a method, several things happen:
- The arguments are evaluated (left to right)
- A new stack frame is created for the method call
- Parameters are bound to the argument values
- The method body executes
- The return value (if any) is computed
- The stack frame is destroyed
- Execution resumes after the call site
public class Demo {
public static int multiply(int x, int y) {
return x * y;
}
public static void main(String[] args) {
int result = multiply(3, 4); // step 1: evaluate args (3, 4)
// step 2-3: create frame, bind x=3, y=4
// step 4-5: compute 3*4 = 12
// step 6: destroy frame
// step 7: assign 12 to result
System.out.println(result);
}
}
The stack frame is where local variables and parameters live for the duration of the call. When the method returns, the frame is popped off the stack and its variables are gone.
Static vs Instance Methods
The static keyword changes who can call a method:
Static methods belong to the class itself. You call them through the class name:
public class MathUtil {
public static int square(int n) {
return n * n;
}
}
int result = MathUtil.square(5); // call through class
You can call a static method without creating an instance of the class. Math.max(a, b) is a static method — you never write new Math().
Instance methods belong to objects. You call them through an instance:
public class Calculator {
public int square(int n) {
return n * n;
}
}
Calculator calc = new Calculator(); // create instance
int result = calc.square(5); // call through instance
Each instance has its own state, and instance methods can access that state via this (Topic 7.4). Static methods can't access instance state — they're independent of any particular object.
For utilities and helpers that don't need object state, static methods are appropriate. For methods that operate on an object's data, instance methods are right.
We cover the static/instance distinction in depth in Module 7. For now, the patterns above are enough.
graph TD
A[Method Call] --> B{Static or Instance?}
B -->|Static| C[Called through class name<br/>ClassName.method(...)]
B -->|Instance| D[Called through object<br/>object.method(...)]
C --> E[No object state available<br/>Independent of instances]
D --> F[Has access to this<br/>Operates on instance state]
style C fill:#7c3aed,color:#fff
style D fill:#10b981,color:#fff
This diagram shows the distinction between static and instance methods. Static methods belong to the class itself and are called through the class name. They don't have access to instance state — they can't use this — but they can be called without creating an object. Instance methods belong to individual objects. They're called through an object reference and have access to that object's state via the this keyword. Each instance method call operates on the specific object it's called on. Utility methods like Math.max are static. Methods that operate on an object's data like list.add are instance methods.
The main Method
The entry point of every Java program is a special method:
public static void main(String[] args) {
// program starts here
}
Mandatory characteristics:
public— must be public so the JVM can call itstatic— no instance is created before main runsvoid— returns nothingString[] args— receives command-line arguments
The parameter name (args) can be anything — arguments, commandLineArgs, whatever — but args is the convention.
Calling a program with arguments:
java MyProgram hello world 42
Inside main, args contains ["hello", "world", "42"]. Arguments are always Strings — you have to parse numbers yourself with Integer.parseInt() etc.
Modern Java (21+) also accepts an instance main method as a preview feature (JEP 463):
void main() {
System.out.println("Hello, World!");
}
This is intended to lower the barrier for beginners — no public static String[] args required. But for production code, the traditional signature is still the norm.
Interactive animation: Calling an instance method from static main fails - make the method static, or call it through an object.
void Methods
Methods that perform an action but don't return a value use void:
public static void greet(String name) {
System.out.println("Hello, " + name);
}
greet("Olena"); // prints "Hello, Olena"
Inside a void method, you can use return; (without a value) to exit early, but you can't return a value:
public static void process(int n) {
if (n < 0) {
return; // exit early
}
// do work
}
For methods with return values, the compiler enforces that every code path returns:
public static int sign(int n) {
if (n > 0) return 1;
if (n < 0) return -1;
// compile error — what if n == 0?
}
The compiler can't prove that one of the conditions is always true, so it requires either an else returning a value or a default return at the end:
public static int sign(int n) {
if (n > 0) return 1;
if (n < 0) return -1;
return 0;
}
Local Variables
Variables declared inside a method are local variables — visible only within that method. They don't persist between calls.
public static int counter() {
int count = 0;
count++;
return count;
}
System.out.println(counter()); // 1
System.out.println(counter()); // 1 — not 2! Each call starts fresh
Each method call creates fresh local variables, initialized as written in the method body. To maintain state across calls, you need instance variables (covered in Module 7) or static variables.
Local variables must be initialized before use:
public static int example() {
int x;
return x; // compile error — x not initialized
}
The compiler tracks definite assignment and rejects code that reads from a possibly-uninitialized variable. This is one of Java's safety features.
Method Naming and Style
Java conventions for method names:
- camelCase —
getUserName,calculateTotal,isValid - Verb-form — methods do things, so they should sound like actions
- Descriptive —
getName()is better thangn()ornameGetter() - No abbreviations unless universally recognized (
url,id,http)
Common prefixes:
| Prefix | Meaning |
|---|---|
get |
Returns a value (accessor) |
set |
Stores a value (mutator) |
is, has, can |
Returns a boolean |
create |
Constructs and returns a new object |
parse |
Converts between formats |
validate |
Checks correctness |
process |
Generic action |
We covered naming conventions in detail in Topic 2.8. Apply them consistently.
Common Pitfalls
Warning: Forgetting to assign the return value.
add(3, 4);computes 7 but throws it away. The return value must be assigned, passed somewhere, or used in an expression.Missing return on some code paths. Methods returning non-void must return from every path. Use
if/else if/elsechains carefully, or have a default return at the end.Calling instance methods statically (or vice versa).
Calculator.add(3, 4)fails ifaddis an instance method.new Calculator().square()works but is wasteful ifsquareis static. Match the call style to the method's nature.Confusing parameters with arguments. Parameters are the names in the method declaration. Arguments are the values passed at the call site. The distinction matters in technical discussions.
Trying to declare two methods with the same signature. Overloading requires different parameter types. Changing only the return type isn't enough — it's a compile error.
Why This Matters in Interviews
Interview: Method-related questions appear at every level. Junior: "What's a method?" Mid: "What's the difference between static and instance methods?" Senior: "What's method overloading vs overriding?" (overloading covered in 6.4; overriding in Module 8). Staff: "How does method dispatch work in the JVM?" (covered later in concurrency and runtime modules).
Topic 6.8 covers the full Interview Lens for methods.
Try It
Exercise: Write each:
- A static method
max3that takes three ints and returns the largest- A static method
isPalindromethat takes a String and returns boolean- A void method
printGridthat prints an n×n grid of stars- A method with multiple
returnstatements that returns "positive", "negative", or "zero" based on input- A method that takes
String[] argsand prints each argument on its own lineFor each, identify: return type, parameters, whether it should be static, naming convention. Then call it from
mainand verify the output.