Methods in Java
A method groups a piece of behaviour behind a name, a parameter list and a return type, and that signature is the contract callers depend on.
-
Java Basics
- Introduction to Java
- Setting Up Java and Writing Your First Program
- Variables, Data Types and Literals in Java
- Type Casting and Type Conversion in Java
- Operators and Expressions in Java
- Input and Output in Java
- Comments, Keywords and Naming Conventions in Java
- Control Flow in Java: if, else and switch
- Loops in Java: for, while and do-while
- Methods
- Arrays and Strings
-
OOP
- Classes and Objects in Java
- Constructors in Java
- The this Keyword in Java
- The static Keyword in Java
- Encapsulation in Java
- Access Modifiers in Java
- Inheritance in Java
- Method Overriding and super in Java
- Polymorphism in Java
- Abstraction, Abstract Classes and Interfaces in Java
- Composition, Aggregation and Association in Java
- The Object Lifecycle in Java
- Core Java
- Exception Handling
-
Collections
- The Java Collections Framework
- List in Java: ArrayList, LinkedList, Vector and Stack
- Set in Java: HashSet, LinkedHashSet and TreeSet
- Map in Java: HashMap, LinkedHashMap and TreeMap
- How HashMap Works Internally in Java
- Queue and Deque in Java: ArrayDeque and PriorityQueue
- Iterators in Java
- Comparable and Comparator in Java
- Collections Utilities and Choosing the Right Collection
- Generics
- Java 8+
- Stream API
- Date and Time
- File and I/O
-
Multithreading
- Threads in Java: Processes, Runnable and Thread
- Thread Lifecycle in Java
- Synchronization in Java: synchronized and volatile
- Locks and Atomic Classes in Java
- Race Conditions and Deadlocks in Java
- The Executor Framework and Thread Pools in Java
- Future and CompletableFuture in Java
- Concurrent Collections in Java
- The Java Memory Model
- JVM and Memory
- Advanced Java
- Networking
- JDBC
- Testing
What a method is
A method is a named block of code that takes zero or more inputs and optionally produces a result. It is the smallest unit of reuse in Java, and the place where a program stops being a list of statements and starts being a design.
Why methods exist
- The same logic is written once and called from many places.
- A good name replaces a comment, because the call site reads as a sentence.
- The body can be changed without touching any caller, as long as the signature holds.
- Small units can be tested independently.
Syntax
modifiers returnType methodName(parameterList) throws ExceptionTypes {
body
}public double averageOf(int[] values) {
if (values.length == 0) {
return 0;
}
int total = 0;
for (int value : values) {
total += value;
}
return (double) total / values.length;
}The parts of a declaration
| Part | Meaning |
|---|---|
| Modifiers | Visibility such as public, plus static, final, abstract and others. |
| Return type | The type of the value produced, or void for none. |
| Method name | lowerCamelCase, normally a verb phrase. |
| Parameter list | Typed placeholders for the inputs. May be empty. |
throws clause | The checked exceptions a caller must deal with. |
The signature is the method name plus the parameter types, in order. The return type is not part of it, which is why two methods cannot differ by return type alone.
Parameters and arguments
A parameter is the variable in the declaration. An argument is the actual value supplied at the call. The words are often swapped in conversation, but the distinction matters when reading error messages.
public int discountedPrice(int price, int percent) { // parameters
return price - (price * percent / 100);
}
int payable = discountedPrice(2000, 15); // argumentsReturn values
public boolean isEligible(int age) {
return age >= 18; // every path must return a value
}
public void log(String message) {
if (message == null) {
return; // a bare return exits a void method early
}
System.out.println(message);
}A method with a non void return type must return on every reachable path, and the compiler checks it. Code after an unconditional return is unreachable and will not compile.
Instance methods and static methods
public class Circle {
private final double radius;
public Circle(double radius) {
this.radius = radius;
}
public double area() { // instance method, uses state
return Math.PI * radius * radius;
}
public static double areaOf(double radius) { // static, depends on inputs only
return Math.PI * radius * radius;
}
}An instance method needs an object because it reads or changes that object. A static method belongs to the class and is called as Circle.areaOf(4). If a method never touches instance state, making it static states that fact clearly.
Scope
public class Counter {
private int total = 0; // field: visible throughout the class
public void add(int amount) { // parameter: visible in this method
int doubled = amount * 2; // local: visible from here to the closing brace
if (doubled > 100) {
int excess = doubled - 100; // visible only inside this block
total += excess;
}
// excess is no longer in scope here
total += doubled;
}
}- A local variable lives from its declaration to the end of the enclosing block.
- A parameter behaves like a local variable of the method.
- A local variable may shadow a field of the same name;
this.totalreaches the field regardless.
Common mistakes
- Declaring a return type and then forgetting to return on one branch.
- Writing a method that both changes state and returns a value, so callers cannot tell what it does from its name.
- Passing a long list of positional parameters where a small object would be clearer.
- Leaving a method
publicwhen nothing outside the class calls it.
Best practices
- One method, one responsibility. If the name needs the word and, split it.
- Keep parameter lists short. Three or four is usually the practical limit.
- Validate arguments at the start and fail fast with a clear message.
- Give the method the narrowest visibility that still works.
- Prefer returning a value over changing a parameter, because it is far easier to reason about.
Practice
- Write a method that returns the larger of two numbers without using
Math.max. - Why will
int f() { if (x) return 1; }not compile? - Convert a method that prints a formatted invoice line into one that returns the line as a
String. What does that make easier to test? - Given a method that both saves a record and returns a count, split it into two and explain the improvement.
Conclusion
A method is a contract: a name, the inputs it accepts and the result it promises. Keep that contract small and honest, and the rest of the design tends to follow.