Methods
Method declaration, access specifiers, overloading, varargs, static methods
- Understand complete method anatomy and declaration
- Master all four access specifiers
- Implement method overloading and understand static binding
- Use variable arguments (varargs)
*Java Basics to Advanced | Lecture 3*
Table of Contents
- Access Specifiers
- Return Type
- Method Name — Naming Conventions
- Parameter List
- Throws Exception (Preview)
- System-Defined Methods
- User-Defined Methods
- Overloaded Methods
- Overridden Methods
- Static Methods
- Final Methods
- Abstract Methods
- Variable Arguments (Varargs)
- Summary Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Quick Revision Summary
1. What is a Method?
Overview
A method is one of the core building blocks of Java programs. Almost every action your program takes is performed inside a method. Understanding methods deeply is essential before moving on to constructors, memory management, and object-oriented design.
Definition
A method is a collection of instructions (statements) grouped together that perform a specific task.
Think of a method as a named block of code that:
- Accepts input (via parameters)
- Does something (computation, logic, I/O)
- Returns output (a result, or nothing —
void)
Real-World Analogy
Think of a method like a vending machine. - You insert coins (input / parameters) - The machine processes your selection (computation) - It dispenses a snack (output / return value) You can use the vending machine again and again without rebuilding it. That is reusability.
Why Methods Exist Two Key Benefits
1. Code Reusability
Without methods, you would copy-paste the same logic everywhere it is needed. With methods, you write it once and call it as many times as needed.
1public class Calculation {2
3 // Written ONCE4 public int sum(int variable1, int variable2) {5 int total = variable1 + variable2;6 System.out.println("Sum computed: " + total);7 return total;8 }9
10 // Reused here11 public int getPriceOfPen() {12 int capPrice = 2;13 int penBodyPrice = 5;14 int totalPenPrice = sum(capPrice, penBodyPrice); // ← reusing sum()15 return totalPenPrice;16 }17
18 // Reused again here19 public int getCombinedAge() {20 int youngerSisterAge = 2;21 int olderSisterAge = 5;22 return sum(youngerSisterAge, olderSisterAge); // ← reusing sum() again23 }24}The sum() method is written once and reused in multiple places. If you need to change how addition works (e.g., add logging), you change it in one place and every caller benefits automatically.
2. Code Readability
A method name communicates intent. When you see getPriceOfPen() or calculateTax(), you immediately understand what the method does — without reading every line of code inside it.
1// Without methods — hard to understand2int x = (2 + 5) * 100 / 7;3
4// With a well-named method — immediately clear5int finalPrice = calculateDiscountedPrice(basePrice, taxRate);What is a "Collection of Instructions"?
Inside a method, each statement is an instruction:
1public int sum(int variable1, int variable2) {2 int total = variable1 + variable2; // Instruction 1: add the two values3 System.out.println(total); // Instruction 2: log/print4 return total; // Instruction 3: return result5}Three instructions together form the method. There is no limit to how many instructions a method can contain.
2. Method Declaration Full Anatomy
Overview
A method declaration defines everything about the method: who can access it, what it returns, what its name is, and what inputs it accepts.
Complete Syntax
1accessSpecifier returnType methodName(parameterList) throws ExceptionType {2 // method body — instructions go here3}Visual Breakdown
1public int sum (int a, int b) throws ArithmeticException2 │ │ │ │ │3 │ │ │ │ └── Throws clause4 │ │ │ └── Parameter List5 │ │ └── Method Name6 │ └── Return Type7 └── Access Specifier2.1 Access Specifiers
Definition
An access specifier (also called an access modifier) is a keyword that controls where a method (or variable or class) can be accessed from.
There are four access specifiers in Java:
| Specifier | Keyword | Accessible From |
|---|---|---|
| Public | public | Anywhere — any class, any package |
| Private | private | Only within the same class |
| Protected | protected | Same package + subclasses in different packages |
| Default | (no keyword) | Only within the same package |
`public` Global Access
1// File: Invoice.java (in package: salesDepartment)2package salesDepartment;3
4public class Invoice {5 public void getInvoice() {6 System.out.println("Inside invoice method");7 }8}1// File: JobPortal.java (in package: humanResource)2package humanResource;3
4import salesDepartment.Invoice;5
6public class JobPortal {7 public void getInvoiceForJobPortal() {8 Invoice invoiceObject = new Invoice();9 invoiceObject.getInvoice(); // ✅ Works — public is accessible anywhere10 }11}Rule: public = accessible from any class in any package.
`private` Same Class Only
1package salesDepartment;2
3public class Invoice {4 private void getInvoice() {5 System.out.println("Inside invoice method");6 }7
8 public void printInvoice() {9 getInvoice(); // ✅ Works — same class can access private method10 }11}1package humanResource;2
3import salesDepartment.Invoice;4
5public class JobPortal {6 public void test() {7 Invoice invoiceObject = new Invoice();8 invoiceObject.getInvoice(); // ❌ Compile error: getInvoice() has private access9 }10}Rule: private = accessible only within the same class. Not even subclasses can access it.
`protected` Same Package + Subclasses
1package salesDepartment;2
3public class Invoice {4 protected void getInvoice() {5 System.out.println("Inside invoice method");6 }7}1// Same package — OK2package salesDepartment;3
4public class Order {5 public void test() {6 Invoice inv = new Invoice();7 inv.getInvoice(); // ✅ Works — Order is in same package as Invoice8 }9}1// Different package, NOT a subclass — NOT OK2package humanResource;3
4import salesDepartment.Invoice;5
6public class JobPortal {7 public void test() {8 Invoice inv = new Invoice();9 inv.getInvoice(); // ❌ Error — different package, not a subclass10 }11}1// Different package, IS a subclass — OK2package humanResource;3
4import salesDepartment.Invoice;5
6public class JobPortal extends Invoice { // ← JobPortal is a child of Invoice7 public void test() {8 getInvoice(); // ✅ Works — subclass can access protected method from parent9 }10}Rule: protected = same package (all classes) + different package (only subclasses/child classes).
`default` Same Package Only
1package salesDepartment;2
3public class Invoice {4 void getInvoice() { // ← no keyword = default access specifier5 System.out.println("Inside invoice method");6 }7}1// Same package — OK2package salesDepartment;3
4public class Order {5 public void test() {6 Invoice inv = new Invoice();7 inv.getInvoice(); // ✅ Works — same package8 }9}1// Different package — NOT OK, even for subclass2package humanResource;3
4import salesDepartment.Invoice;5
6public class JobPortal extends Invoice {7 public void test() {8 getInvoice(); // ❌ Error — default does NOT allow different package, even for child9 }10}Rule: default (no keyword) = same package only. Unlike protected, child classes in different packages cannot access default members.
Access Specifier Comparison Table
| Specifier | Same Class | Same Package | Subclass (diff. package) | Any Class (diff. package) |
|---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
| default | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
2.2 Return Type
Definition
The return type specifies what type of value the method will return after completing its task.
Every method in Java must declare a return type. If the method returns nothing, the return type is void.
Common Return Types
| Return Type | Meaning | Example |
|---|---|---|
void | Returns nothing | public void print() |
int | Returns an integer | public int getAge() |
boolean | Returns true or false | public boolean isValid() |
String | Returns a String | public String getName() |
double | Returns a decimal | public double getPrice() |
Object / custom class | Returns an object | public Employee getEmployee() |
Using `void`
1public void printInvoice() {2 System.out.println("Printing invoice...");3 // No return statement required4}With void, you can optionally write a bare return; statement to exit the method early:
1public void printInvoice(boolean isValid) {2 if (!isValid) {3 return; // ← exit early, return nothing4 }5 System.out.println("Printing invoice...");6}void method. The following is a compile error:
``java
public void test() {
return 5; // ❌ Error: cannot return a value from a void method
}
``Using a Typed Return
When the return type is not void, the method must return a value of that type using the return keyword:
1public int sum(int a, int b) {2 int total = a + b;3 return total; // ← required: must return an int4}2.3 Method Name Naming Conventions
Rules (enforced by Java)
- Must start with a letter, underscore
_, or dollar sign$(not a digit) - Cannot be a Java keyword (e.g.,
int,class,return) - Case-sensitive (
sumandSumare different method names)
Conventions (standard Java style)
| Convention | Rule | Example |
|---|---|---|
| Use a verb | Methods perform actions | getAge(), printInvoice(), calculateTax() |
| Start with lowercase | First letter must be lowercase | getEmployee() ✅, GetEmployee() ❌ |
| Use camelCase | Each word after the first starts with uppercase | getEmployeeDetails() ✅ |
| Be descriptive | Name should reveal intent | computeMonthlyTax() ✅, doStuff() ❌ |
1// ✅ Correct naming2public int getAge() { ... }3public void printInvoice() { ... }4public boolean isEligibleForLoan() { ... }5public double calculateMonthlyInterest() { ... }6
7// ❌ Incorrect naming8public int GetAge() { ... } // starts with capital9public void PrintInvoice() { ... } // starts with capital10public int 2sum() { ... } // starts with digit2.4 Parameter List
Definition
The parameter list is the set of input variables a method accepts. These variables are used inside the method body to perform the task.
Parameters are also called arguments (the terms are often used interchangeably, though technically: parameters are in the declaration, arguments are the actual values passed during a call).
Syntax
1public int sum(int variable1, int variable2) {2 // ↑ param 1 ↑ param 23}Each parameter is declared as: dataType parameterName
Multiple parameters are separated by commas.
Rules
- A method can have zero or more parameters
- Each parameter must have an explicit type
- Parameter names must be unique within the method
1// Zero parameters2public void printHello() {3 System.out.println("Hello!");4}5
6// One parameter7public void printMessage(String message) {8 System.out.println(message);9}10
11// Multiple parameters12public int add(int a, int b) {13 return a + b;14}15
16// Mixed types17public void createUser(String name, int age, boolean isActive) {18 // ...19}2.5 Throws Exception (Preview)
A method can optionally declare that it may throw an exception during execution. This is done using the throws keyword in the method signature.
1public void getInvoice() throws ArithmeticException {2 // This method might throw an ArithmeticException (e.g., divide by zero)3}Any method that calls getInvoice() must then handle (or further declare) that exception. This mechanism is Java's way of communicating potential failure modes between methods.
We will cover:
- Checked vs. unchecked exceptions
try-catch-finally- Custom exceptions
- Exception propagation
…in the dedicated Exception Handling lecture.
3. Packages in Java (Supporting Concept)
Definition
A package is a namespace that groups related classes together — like a folder on your file system that organizes files.
Packages serve two purposes:
- Organization — group similar classes together
- Access control — access specifiers like
protectedanddefaultuse package boundaries
Example
1project/2├── salesDepartment/ ← package3│ ├── Invoice.java4│ └── Order.java5│6└── humanResource/ ← another package7 ├── JobPortal.java8 └── Application.java1// Declaring a package — first line of the file2package salesDepartment;3
4public class Invoice {5 // ...6}1// Importing from another package2package humanResource;3
4import salesDepartment.Invoice; // ← import the class5
6public class JobPortal {7 public void test() {8 Invoice inv = new Invoice();9 // ...10 }11}4. Types of Methods
Overview
4.1 System-Defined Methods
Definition
System-defined methods
are methods that are already written, compiled, and provided by Java as part of its standard class libraries. You use them without writing any code yourself.
These are provided by the JRE class libraries (recall from the Java Overview lecture: JRE = JVM + Class Libraries).
Examples
1public class SystemMethodDemo {2 public static void main(String[] args) {3
4 // Math library — java.lang.Math5 int variable = 25;6 double squareRoot = Math.sqrt(variable); // system-defined7 System.out.println("Square root: " + squareRoot); // Output: 5.08
9 int absValue = Math.abs(-42); // system-defined10 System.out.println("Absolute: " + absValue); // Output: 4211
12 // Arrays library — java.util.Arrays13 int[] arr = {5, 3, 1, 4, 2};14 java.util.Arrays.sort(arr); // system-defined15 System.out.println(java.util.Arrays.toString(arr)); // Output: [1, 2, 3, 4, 5]16
17 // String library — java.lang.String18 String name = "hello";19 System.out.println(name.toUpperCase()); // system-defined → Output: HELLO20 System.out.println(name.length()); // system-defined → Output: 521 }22}4.2 User-Defined Methods
Definition
User-defined methods
are methods created by the programmer based on the specific needs of their program.
1public class Calculation {2
3 // User-defined — the programmer wrote this4 public int sum(int a, int b) {5 int total = a + b;6 System.out.println("Sum: " + total);7 return total;8 }9
10 public int getPriceOfPen() {11 int capPrice = 2;12 int penBodyPrice = 5;13 return sum(capPrice, penBodyPrice); // calls another user-defined method14 }15}The distinction is simple: if Java gave it to you → system-defined. If you wrote it → user-defined.
4.3 Overloaded Methods
Definition
Method overloading
is when more than one method with the same name exists in the same class, but with different parameter lists.
This is part of polymorphism — specifically compile-time (static) polymorphism or static binding.
Rules of Overloading
| Rule | Detail |
|---|---|
| Same name | All overloaded methods share the same name |
| Different parameters | Must differ in number, type, or order of parameters |
| Return type is NOT considered | Two methods with same name and same parameters but different return types is a compile error |
| Same class | All overloads are in the same class |
Code Example
1public class Invoice {2
3 // Version 1 — no parameters4 public void getInvoice() {5 System.out.println("Invoice with no parameters");6 }7
8 // Version 2 — one String parameter9 public void getInvoice(String invoiceId) {10 System.out.println("Invoice ID: " + invoiceId);11 }12
13 // Version 3 — one int parameter14 public void getInvoice(int amount) {15 System.out.println("Invoice Amount: " + amount);16 }17
18 // Version 4 — two int parameters19 public void getInvoice(int amount, int tax) {20 System.out.println("Amount: " + amount + ", Tax: " + tax);21 }22}Calling Overloaded Methods
1public class Order {2 public static void main(String[] args) {3 Invoice invoiceObj = new Invoice();4
5 invoiceObj.getInvoice(); // calls Version 16 invoiceObj.getInvoice("INV-001"); // calls Version 27 invoiceObj.getInvoice(500); // calls Version 38 invoiceObj.getInvoice(500, 90); // calls Version 49 }10}Invoice with no parameters Invoice ID: INV-001 Invoice Amount: 500 Amount: 500, Tax: 90
Java decides at compile time which version to call based on the arguments you pass. This is why overloading is called static (compile-time) binding.
Invalid Overloading Return Type Alone is NOT Enough
1public class Invoice {2 public void getInvoice() { } // Version A3
4 public int getInvoice() { // ❌ COMPILE ERROR5 return 0;6 }7 // Error: method getInvoice() is already defined in class Invoice8}To fix — make the parameters different:
1public void getInvoice() { } // no params → valid2
3public int getInvoice(String z) { // different param → valid overload4 return 0;5}4.4 Overridden Methods
Definition
Method overriding
is when a subclass (child class) provides its own implementation of a method that is already defined in its parent class. The method signature (name, return type, parameters, access specifier) must be exactly the same.
This is runtime (dynamic) polymorphism — also called dynamic binding.
Code Example
1// Parent class2public class Person {3 public void profession() {4 System.out.println("I am a person class");5 }6}1// Child class2public class Doctor extends Person {3
4 @Override // annotation — tells compiler this is intentionally overriding a parent method5 public void profession() {6 System.out.println("I am a Doctor class — doing something different");7 }8}The `@Override` Annotation
The @Override annotation is optional but strongly recommended. It tells the compiler: "I intend to override a parent method here." If you accidentally mistype the method name, the compiler will catch the mistake.
1@Override2public void profesion() { // ← typo: 'profesion' instead of 'profession'3// ❌ Compile error: method does not override or implement a method from a supertypeInvoking Overridden Methods Dynamic Dispatch
1public class Main {2 public static void main(String[] args) {3
4 // Parent reference holding a child object5 Person obj = new Doctor();6
7 // Which profession() is called?8 obj.profession(); // → "I am a Doctor class — doing something different"9 }10}Even though obj is declared as type Person, it holds an instance of Doctor. At runtime, the JVM checks the actual object type and calls Doctor's profession().
If Doctor did not have its own profession(), JVM would walk up the inheritance chain and call Person's version.
Overriding Rules
| Rule | Detail |
|---|---|
| Same method name | Exact match required |
| Same parameter list | Exact match required |
| Same or covariant return type | Return type must match (or be a subtype) |
| Same or less restrictive access | Cannot narrow access (public → private is illegal) |
@Override annotation | Optional but highly recommended |
4.5 Static Methods
Definition
A static method is a method that is associated with the class itself, not with any individual object (instance). It can be called using the class name without creating an object.
Static vs. Instance Methods The Core Difference
1public class A {2
3 public void method1() { // instance method — belongs to each object4 System.out.println("method1");5 }6
7 public static void method2() { // static method — belongs to the class8 System.out.println("method2");9 }10}1public class Main {2 public static void main(String[] args) {3
4 A object1 = new A();5 A object2 = new A();6
7 // Calling instance method — needs an object8 object1.method1(); // ✅9 object2.method1(); // ✅10
11 // Calling static method — use class name, no object needed12 A.method2(); // ✅13 }14}Memory Visualization
1Heap Memory2┌─────────────────────────────┐3│ Object1 (instance of A) │4│ ├── method1 (copy) │5│ │6│ Object2 (instance of A) │7│ ├── method1 (copy) │8└─────────────────────────────┘9
10Method Area / Class Area11┌─────────────────────────────┐12│ Class A │13│ └── method2 (ONE copy) │ ← static: ONE shared copy for all objects14└─────────────────────────────┘Calling a Static Method from Code
1public class Calculation {2
3 public static int getPriceOfPen() {4 int capPrice = 2;5 int penBodyPrice = 5;6 return capPrice + penBodyPrice;7 }8}9
10public class Main {11 public static void main(String[] args) {12 int price = Calculation.getPriceOfPen(); // ← called via class name13 System.out.println("Pen price: " + price); // Output: Pen price: 714 }15}Critical Rule: Static Methods Cannot Access Non-Static Members
This is one of the most frequently asked Java interview questions.
1public class Calculation {2
3 int stockPrice = 20; // instance variable (non-static)4 static int carPrice = 40; // class variable (static)5
6 public static void staticMethod() {7
8 carPrice = 50; // ✅ OK — carPrice is also static9 // stockPrice = 30; // ❌ COMPILE ERROR — cannot access non-static variable10
11 // int result = print(); // ❌ COMPILE ERROR — cannot call non-static method12
13 // To access non-static: you MUST provide an object reference14 Calculation obj = new Calculation();15 obj.stockPrice = 30; // ✅ OK — now we specify WHICH object's stockPrice16 obj.print(); // ✅ OK — now we specify WHICH object's print()17 }18
19 public int print() {20 return stockPrice;21 }22}Why Can't Static Methods Access Instance Variables?
The reason is conceptual:
- Instance variables (
stockPrice) exist per object. Object1 has its ownstockPrice, Object2 has its ownstockPrice. - Static methods belong to the class, not to any object.
- If a static method tries to access
stockPrice, the question becomes: which object'sstockPrice? There is no answer — the static method has no object context. - Static variables (
carPrice) exist once for the entire class, so there is no ambiguity.
1object1.stockPrice = 202object2.stockPrice = 353
4Static method asks: "Give me stockPrice"5JVM responds: "Which one? object1's? object2's?"6→ No answer → Compile errorDanger: Sharing Mutable State in Static Methods
1public class Calculation {2 static int carPrice = 40; // shared state3
4 public static int sumTwo(int a, int b) {5 int total = a + b;6 carPrice = carPrice + total; // ← MUTATING SHARED STATIC STATE7 return carPrice;8 }9}If Thread 1 calls sumTwo(2, 1) and Thread 2 calls sumTwo(5, 2) simultaneously:
- Thread 1 computes:
carPrice = 40 + 3 = 43 - Thread 2 reads
carPriceas43(not40) - Thread 2 computes:
carPrice = 43 + 7 = 50(expected:40 + 7 = 47)
This is a race condition — shared mutable static state causes unexpected results in multi-threaded programs.
static if it reads from or writes to an instance variable.Static Methods Cannot Be Overridden
1public class Person {2 public static void profession() {3 System.out.println("Person class");4 }5}6
7public class Doctor extends Person {8 // This is NOT overriding — it is METHOD HIDING9 public static void profession() {10 System.out.println("Doctor class");11 }12}1Person obj = new Doctor();2obj.profession(); // → "Person class" ← calls Person's static method!3// No dynamic dispatch happens — static methods are resolved at COMPILE TIMECompare with true overriding (non-static):
1Person obj = new Doctor();2obj.profession(); // → "Doctor class" ← dynamic dispatch at runtimeThis is the key distinction:
- Instance methods → dynamic binding → resolved at runtime based on object type
- Static methods → static binding → resolved at compile time based on reference type
The phenomenon where a subclass defines a static method with the same signature as the parent's static method is called method hiding, not overriding.
When Should You Make a Method Static?
Make a method static when:
✅ It does not use any instance variable (non-static field) ✅ It does not modify the state of any object ✅ It only computes using its arguments ✅ It is a utility method that any code can call independently
1// ✅ Good candidate for static — only uses parameters2public static int sum(int a, int b) {3 return a + b;4}5
6// ❌ Bad candidate for static — uses instance variable7public int sumTwo(int a, int b) {8 carPrice = carPrice + a + b; // modifies instance state9 return carPrice;10}4.6 Final Methods
Definition
A final method is a method that cannot be overridden by any subclass. The implementation is locked in the class that declares it final.
Syntax
1public class Person {2 public final void profession() { // ← final keyword3 System.out.println("I am a person");4 }5}1public class Doctor extends Person {2 @Override3 public void profession() { // ❌ COMPILE ERROR: cannot override final method4 System.out.println("I am a doctor");5 }6}Why Use `final` on Methods?
When you mark a method final, you are saying:
"This implementation is definitive. No subclass should change it."
Use cases:
- Security-sensitive code where changing behavior could create vulnerabilities
- Core algorithms that must not be altered in subclasses
- Template method pattern (core steps are
final, hook methods are overridable)
Logic Behind `final` and Overriding
If a child class cannot change the method, then there is no point in overriding it — overriding exists to provide a different implementation. If the implementation must stay the same, the child class can simply inherit and use the method as-is.
4.7 Abstract Methods
Definition
An abstract method has a declaration but no body (no implementation). The implementation is delegated entirely to subclasses.
Rules
| Rule | Detail |
|---|---|
| Must be inside an abstract class | You cannot have an abstract method in a concrete (regular) class |
| No method body | Only the signature is declared; ends with ; not {} |
| Subclass must implement it | The first non-abstract child class must provide the implementation |
Cannot be final | abstract and final are contradictory (abstract demands overriding; final forbids it) |
Cannot be static | Static methods don't participate in polymorphism |
Syntax
1// Abstract class — cannot be instantiated directly2public abstract class Person {3
4 // Abstract method — declaration only, no body5 public abstract void print();6
7 // Can also have regular (concrete) methods8 public void greet() {9 System.out.println("Hello from Person");10 }11}1// Concrete child class — MUST implement all abstract methods2public class Doctor extends Person {3
4 @Override5 public void print() { // ← providing the required implementation6 System.out.println("Doctor implementation of print");7 }8}What Happens If Child Doesn't Implement?
1public class Doctor extends Person {2 // Forgot to implement print()3 // ❌ COMPILE ERROR: Doctor is not abstract and does not override abstract method print() in Person4}The child class must either:
- Implement all abstract methods from the parent, OR
- Also be declared abstract (deferring implementation to its own subclass)
Abstract vs. Final They Are Opposites
abstract | final | |
|---|---|---|
| Purpose | Force subclasses to implement | Prevent subclasses from overriding |
| Overrideable? | Must be overridden | Cannot be overridden |
| Can combine? | ❌ Cannot be abstract final | ❌ Cannot be final abstract |
5. Variable Arguments (Varargs)
Overview
Varargs (Variable Arguments) is a Java feature that allows a method to accept a variable number of arguments of the same type — from zero arguments to any number.
The Problem Varargs Solves
Suppose you want a sum() method that adds however many numbers the caller provides. Without varargs, you'd have to create many overloads:
1public int sum(int a) { return a; }2public int sum(int a, int b) { return a + b; }3public int sum(int a, int b, int c) { return a + b + c; }4public int sum(int a, int b, int c, int d) { return a + b + c + d; }5// ... this never ends!This approach doesn't scale. What if someone wants to sum 10, 20, or 100 numbers?
Solution: Varargs Syntax
1public int sum(int... variable) {2 // ↑ three dots = varargs3 // 'variable' is treated as an int array inside the method4 int output = 0;5 for (int val : variable) {6 output = output + val;7 }8 return output;9}The ... (three dots) after the type declares a varargs parameter. Inside the method, it behaves as an array.
Complete Code Example
1public class Calculation {2
3 public int sum(int... variable) {4 int output = 0;5 for (int val : variable) {6 output += val;7 }8 return output;9 }10
11 public static void main(String[] args) {12 Calculation calc = new Calculation();13
14 System.out.println(calc.sum()); // Output: 0 (zero args)15 System.out.println(calc.sum(3)); // Output: 3 (one arg)16 System.out.println(calc.sum(3, 8)); // Output: 11 (two args)17 System.out.println(calc.sum(3, 8, 9, 10)); // Output: 30 (four args)18 System.out.println(calc.sum(1, 2, 3, 4, 5, 6, 7)); // Output: 2819 }20}All five calls use the same single method. No overloading needed.
Varargs With Other Parameters
Varargs can be combined with other parameters:
1public void printInfo(String label, int... numbers) {2 System.out.print(label + ": ");3 for (int n : numbers) {4 System.out.print(n + " ");5 }6 System.out.println();7}1printInfo("Scores", 85, 90, 78, 92);2// Output: Scores: 85 90 78 92Two Strict Rules of Varargs
Rule 1: Only ONE varargs parameter per method
1// ❌ COMPILE ERROR — two varargs parameters2public void method(int... a, String... b) { }3
4// ✅ OK — only one varargs5public void method(int... a) { }Rule 2: Varargs MUST be the LAST parameter
1// ❌ COMPILE ERROR — varargs is not last2public void method(int... numbers, String label) { }3
4// ✅ OK — varargs is last5public void method(String label, int... numbers) { }Why must it be last?
If varargs were first, Java would not know where the varargs portion ends and where the next fixed parameter begins:
1// If varargs were first (hypothetically):2method(1, 2, 3, 4, "hello");3// Is "hello" the label? Are 1,2,3,4 the numbers?4// OR are 1,2,3 the numbers and 4 is something else? → Ambiguous!By placing varargs last, Java assigns all initial arguments to the fixed parameters, and everything remaining goes into the varargs:
1method("hello", 1, 2, 3, 4);2// "hello" → label (String)3// 1, 2, 3, 4 → numbers (int...)4// ✅ UnambiguousHow Varargs Works Internally
At the bytecode level, Java converts a varargs call into an array creation:
1calc.sum(3, 8, 9)2// is equivalent to:3calc.sum(new int[]{3, 8, 9})You can also pass an array directly to a varargs method:
1int[] myArray = {1, 2, 3, 4, 5};2System.out.println(calc.sum(myArray)); // ✅ WorksVarargs Rules Summary Table
| Rule | Correct | Incorrect |
|---|---|---|
| One varargs per method | void m(int... a) | void m(int... a, int... b) |
| Must be last parameter | void m(String s, int... n) | void m(int... n, String s) |
| Treated as array inside | for (int x : n) | ✅ |
| Can accept zero arguments | m() → array length 0 | ✅ |
| Can pass explicit array | m(new int[]{1,2,3}) | ✅ |
6. Summary Diagrams
Method Declaration Anatomy
Complete Types-of-Methods Overview
Overloading vs. Overriding Comparison
| Feature | Overloading | Overriding |
|---|---|---|
| Also known as | Static / Compile-time Polymorphism | Dynamic / Runtime Polymorphism |
| Location | Same class | Parent and Child class |
| Method name | Same | Same |
| Parameters | Must be different | Must be same |
| Return type | Not considered | Must be same (or covariant) |
| Access specifier | Can differ | Cannot be more restrictive |
| Resolved at | Compile time | Runtime |
7. Common Mistakes
Mistake 1: Thinking Return Type Alone Differentiates Overloads
1// ❌ WRONG — this is NOT valid overloading2public void getInvoice() { }3public int getInvoice() { return 0; } // COMPILE ERRORFix: Change the parameters to create a valid overload.
Mistake 2: Accessing Non-Static Members from Static Method
1public class MyClass {2 int instanceVar = 10;3
4 public static void myStatic() {5 System.out.println(instanceVar); // ❌ COMPILE ERROR6 }7}Fix: Either make instanceVar static, or pass an object reference:
1public static void myStatic(MyClass obj) {2 System.out.println(obj.instanceVar); // ✅ OK3}Mistake 3: Thinking Static Methods Are Overridden
1Person obj = new Doctor();2obj.profession(); // If profession() is static → calls Person's version3 // NOT Doctor's version — this is method HIDING not overridingMistake 4: Placing Varargs Before Other Parameters
1// ❌ COMPILE ERROR2public void method(int... numbers, String label) { }3
4// ✅ CORRECT5public void method(String label, int... numbers) { }Mistake 5: Trying to Override an Abstract Method with Wrong Signature
1public abstract class Person {2 public abstract void print();3}4
5public class Doctor extends Person {6 public void print(String msg) { } // ❌ — different signature, NOT implementing abstract method7 // COMPILE ERROR: Doctor must implement abstract method print() from Person8}Mistake 6: Making a Static Method Abstract or Final Making a Final Method Abstract
1public abstract class A {2 public abstract static void method(); // ❌ ILLEGAL COMBINATION3 public abstract final void method2(); // ❌ ILLEGAL COMBINATION4}8. Best Practices
- Always choose the most restrictive access specifier that still meets your needs. Default to
private; only widen when necessary. - Use
@Overrideannotation whenever you intend to override a method — it catches typos and signature mismatches. - Name methods as verbs —
calculateTax(),printReport(),isValid(). - Use
camelCasestarting with lowercase for all method names. - Make methods static only when they don't depend on instance state — purity and predictability.
- Keep methods short and focused — a method should do one thing. If it's doing many things, break it up.
- Use varargs sparingly — they are powerful but can make method signatures ambiguous if overused.
- Mark methods
finalwhen you want to guarantee behavior is not changed by subclasses. - Prefer abstract methods over empty default implementations when child classes must provide behavior.
- Avoid mutating static variables inside static methods — it leads to thread-safety issues.
9. Interview Notes
Commonly Asked Questions
Q1: What is method overloading vs. method overriding?
Answer:
- Overloading — Same class, same name, different parameters. Resolved at compile time (static binding).
- Overriding — Parent and child class, same name + same signature. Resolved at runtime (dynamic binding).
Q2: Can you overload a method by changing only the return type?
Answer: No. Return type is not considered during overload resolution. You will get a compile error.
Q3: Can a static method be overridden?
Answer: No. Static methods cannot be overridden. If a subclass defines a static method with the same signature as the parent's static method, it is called method hiding, not overriding. Static methods use static (compile-time) binding and are resolved based on the reference type, not the object type.
Q4: Why can't a static method access instance variables?
Answer: Static methods are associated with the class, not with any specific object. Instance variables belong to individual objects. Since a static method has no object context, it doesn't know which object's instance variable to access. You must provide an explicit object reference.
Q5: What is the difference between `final`, `static`, and `abstract` methods?
Answer:
final— Cannot be overridden by subclasses.static— Belongs to the class, not an object; called via class name.abstract— Has no body; subclass must provide implementation.
Q6: What are the rules for varargs?
Answer:
- Only one varargs parameter per method.
- Varargs must be the last parameter.
- Inside the method, it is treated as an array.
Q7: When should you declare a method `static`?
Answer: Declare a method static when it does not use any instance variable (non-static field), does not modify the object's state, and performs its computation purely on its arguments. Utility methods and factory methods are common candidates.
Q8: What is the difference between `protected` and `default` access?
Answer:
protected— Accessible in same package AND in subclasses of different packages.default(no keyword) — Accessible only in the same package. Subclasses in different packages cannot access it.
Q9: What does `void` mean as a return type?
Answer: void means the method does not return any value. It can have no return statement, or a bare return; to exit early.
Q10: Can an abstract method be `final` or `static`?
Answer: No. abstract and final are contradictory — abstract requires the method to be overridden, while final prevents overriding. abstract and static are also incompatible — static methods don't participate in dynamic polymorphism, but abstract methods exist specifically for dynamic polymorphism.
10. Practice Questions
Easy
- What is a method? What two benefits does it provide?
- List the four access specifiers in Java and the access level each provides.
- What does
voidas a return type mean? - What is the naming convention for methods in Java? Give two correct and two incorrect examples.
- What is the difference between a system-defined and a user-defined method?
- Write a method that takes two
intparameters and returns their product.
Medium
- Explain why overloading is called "compile-time polymorphism" and overriding is called "runtime polymorphism."
- Can you overload a method by changing only the return type? Why or why not?
- Why can't a
staticmethod access an instance variable directly? - Write an example of method overloading with three versions of a
display()method. - Write a
finalmethod in a parent class and show what happens when a child tries to override it. - Write a varargs method that finds the maximum value among any number of integers passed.
- What is
method hidingin Java? How does it differ from method overriding?
Hard
- A static variable
countis shared among all objects. A static method increments it. Explain the thread-safety risk and propose a solution. - Why is it illegal to combine
abstractandfinalon the same method? Write a conceptual explanation. - Consider:
Person obj = new Doctor();. Ifprofession()is non-static in Person and overridden in Doctor, which version is called? What ifprofession()is static? Explain both cases with the concepts of static binding and dynamic binding. - Design a class
MathUtilswith overloadedadd()methods that handle: two ints, three ints, two doubles, and a varargs int version. Show how Java chooses which method to call. - Given the four access specifiers, design a class hierarchy across two packages that demonstrates all four specifiers with working and failing access examples.
11. Quick Revision Summary
1☕ JAVA METHODS — KEY POINTS2
3✅ Method = Collection of instructions that perform a specific task4✅ Benefits: Code Reusability + Code Readability5
6📋 METHOD ANATOMY:7 accessSpecifier returnType methodName(params) throws Exception { body }8
9🔐 ACCESS SPECIFIERS:10 public → any class, any package11 private → same class only12 protected → same package + child classes in diff package13 default → same package only (no child in diff package)14
15🔄 RETURN TYPE:16 void → returns nothing17 int, boolean, String, etc. → must use return statement18
19📛 NAMING:20 • Verb, camelCase, start lowercase21 • getAge() ✅ | GetAge() ❌ | 2sum() ❌22
23📦 TYPES OF METHODS:24 System-Defined → provided by Java (Math.sqrt, Arrays.sort)25 User-Defined → programmer creates26 Overloaded → same name, diff params, SAME CLASS (compile-time)27 Overridden → same name+signature, CHILD CLASS (runtime)28 Static → belongs to CLASS, not object; no instance vars29 Final → cannot be overridden30 Abstract → no body; child MUST implement; only in abstract class31
32⚡ STATIC METHOD RULES:33 • Called via ClassName.method()34 • Cannot access non-static (instance) variables or methods35 • Cannot be overridden (it's method hiding, not overriding)36 • Use ONLY when: no instance variables needed, pure computation37
38🔢 VARARGS:39 Syntax: type... paramName40 • Treated as array inside method41 • Only ONE varargs per method42 • MUST be LAST parameter43 • Can receive 0 to many arguments44
45⚠️ KEY INTERVIEW POINTS:46 • Return type alone does NOT create valid overloads47 • Static methods → static binding (compile time)48 • Instance methods → dynamic binding (runtime)49 • abstract + final = ILLEGAL combination50 • protected ≠ default (protected allows child in diff package)End of Chapter — Methods in Java
throws, try-catch-finally, custom exceptionsStudy Guide generated from: Java Basics to Advanced — Lecture 3: Methods in Java
Mastery check
How well can you recall this?
Finished this lesson?