Methods (Functions)
Overview
As your program grows, putting all your code in one massive file becomes a nightmare to read and fix. A Method (often called a function) is a way to group a specific block of code, give it a name, and reuse it anywhere you want.
Think of a method like a coffee machine. You give it inputs (coffee beans and water), it does some internal logic (brewing), and gives you an output (a cup of coffee). You don't need to know *how* it brews, you just call it when you need coffee!
1. Inputs (Parameters)
Methods can take inputs, called parameters. For example, an `addNumbers` method needs to know *which* two numbers to add.
2. Output (Return Type)
Methods often calculate something and give the result back to you. We define the type of data it gives back (like `int` or `String`). If it doesn't give anything back, we use the keyword `void`.
3. Reusability (DRY Principle)
DRY stands for 'Don't Repeat Yourself'. If you find yourself copying and pasting the same 5 lines of code, you should put them inside a method instead!
Syntax
A method that takes two integers, adds them, and 'returns' the result.
public class Calculator {
// Method signature: returns an 'int', takes two 'int' parameters
public static int add(int num1, int num2) {
int sum = num1 + num2;
return sum; // Gives the result back to whoever called it
}
// A 'void' method returns nothing. It just does an action.
public static void sayHello(String name) {
System.out.println("Hello there, " + name + "!");
}
}How to use the methods we created above.
public static void main(String[] args) {
// Calling the void method
sayHello("Kartik");
// Calling the return method and saving the answer
int finalAnswer = add(10, 5);
System.out.println("The answer is: " + finalAnswer);
}Common Pitfalls
- Forgetting to write a `return` statement in a method that promises to return a value. The compiler will scream at you.
- Trying to return a value in a `void` method. `void` literally means 'nothing', so you can't return data.
Interview Tips
- A golden rule in software engineering: A method should do exactly ONE thing. If your method is validating a user, saving to a database, AND sending an email, it's doing too much. Break it into 3 smaller methods.
Real-World Example
Methods encapsulate logic so other parts of the app can use it safely and easily.
public class TaxCalculator {
// Anyone in the app can call this to calculate tax instantly
public static double calculateTotalWithTax(double price) {
double taxRate = 0.08; // 8% tax
double taxAmount = price * taxRate;
return price + taxAmount;
}
public static void main(String[] args) {
double total = calculateTotalWithTax(100.0);
System.out.println("Total to pay: $" + total); // $108.0
}
}