Java Methods Tutorial: Complete Beginner Guide with Examples (2026)
⏱️ Reading Time: 25 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
What is a Method in Java?
A method in Java is a named block of code that performs a specific task. It is the fundamental unit of reusable logic in Java programming.
Think of a method as a recipe card in a kitchen:
- It has a name (e.g., "Chocolate Cake")
- It lists ingredients (parameters)
- It describes the process (method body)
- It produces a result (return value) — or just performs an action (void)
Once you write the recipe, you can use it again and again without rewriting the entire process.
1// A simple method that greets the user 2public static void greet() { 3 System.out.println("Welcome to Java!"); 4}
Why Do We Need Methods?
"I once wrote a 500-line program in a single main() method. When I had to change the tax calculation logic, I spent 3 hours finding all 12 places where I had copy-pasted it. Methods would have saved me 2 hours and 55 minutes." — Every developer who learned methods the hard way.
Without methods, every program is a wall of code that repeats itself. Methods bring structure and intelligence to your code.
| Without Methods | With Methods |
|---|---|
500 lines in main() | 50 lines in main(), 10 methods of 45 lines each |
| Same logic copy-pasted 12 times | One method called 12 times |
| Changing logic in 12 places | Change logic in 1 place |
| No one understands your code | Team members read method names and understand |
| Impossible to unit test | Each method tested independently |
Real-world applications:
- E-commerce:
calculateDiscount(),validateCoupon(),generateInvoice() - Banking:
transferFunds(),checkBalance(),authenticateUser() - Social Media:
createPost(),likePost(),sendNotification() - Healthcare:
calculateBMI(),checkAllergy(),scheduleAppointment()
Method Declaration Syntax
Every method in Java follows a strict structure. Understanding each part is essential.
Syntax
1accessModifier staticOrInstance returnType methodName(parameterList) { 2 // Method body — the actual logic 3 return value; // Optional: only if returnType is not void 4}
Anatomy of a Method
1public static int add(int a, int b)
| Part | Name | Purpose | Example |
|---|---|---|---|
public | Access Modifier | Who can call this method? | public, private, protected, default |
static | Modifier | Belongs to class (static) or object (instance)? | static (for now) |
int | Return Type | What type of value does the method give back? | int, double, String, void |
add | Method Name | The identifier used to call the method | Should be a verb or verb phrase |
(int a, int b) | Parameter List | Input values the method needs | int a, String name, double price |
Example: Complete Method Declaration
1public class MethodAnatomy { 2 3 // Method declaration 4 public static int add(int a, int b) { 5 int sum = a + b; // Method body 6 return sum; // Return statement 7 } 8 9 public static void main(String[] args) { 10 int result = add(5, 3); // Method call 11 System.out.println("Sum: " + result); // Output: Sum: 8 12 } 13}
Calling a Method
A method does nothing until it is called. Calling a method means telling Java to execute that block of code.
Syntax
1methodName(arguments);
Example: Simple Method Call
1public class MethodCallDemo { 2 3 static void greet() { 4 System.out.println("Hello, Java Developer!"); 5 } 6 7 public static void main(String[] args) { 8 greet(); // First call 9 greet(); // Second call — same code, reused! 10 greet(); // Third call 11 } 12}
Output:
1Hello, Java Developer! 2Hello, Java Developer! 3Hello, Java Developer!
Calling a Method Multiple Times
1public class ReusableGreeting { 2 3 static void greetUser(String name) { 4 System.out.println("👋 Welcome, " + name + "!"); 5 } 6 7 public static void main(String[] args) { 8 greetUser("Ankit"); 9 greetUser("Rahul"); 10 greetUser("Priya"); 11 } 12}
Output:
1👋 Welcome, Ankit! 2👋 Welcome, Rahul! 3👋 Welcome, Priya!
Key Insight: You wrote the logic once. You used it three times. That is the power of methods.
Parameters vs Arguments
This is the #1 point of confusion for beginners. Let us settle it forever.
| Term | Definition | Where It Lives | Analogy |
|---|---|---|---|
| Parameter | The variable declared in the method signature | Method definition | Recipe ingredient placeholder ("2 cups flour") |
| Argument | The actual value passed when calling the method | Method call | The actual flour you pour in ("2 cups of wheat flour") |
Visual Example
1// Method DEFINITION — 'name' is a PARAMETER 2static void welcome(String name) { // ← Parameter 3 System.out.println("Welcome " + name); 4} 5 6// Method CALL — "Ankit" is an ARGUMENT 7welcome("Ankit"); // ← Argument 8welcome("Rahul"); // ← Argument
Multiple Parameters
1static void createUser(String name, int age, String city) { 2 System.out.println("Name: " + name); 3 System.out.println("Age: " + age); 4 System.out.println("City: " + city); 5} 6 7// Calling with three arguments 8createUser("Ankit", 25, "Mumbai");
Output:
1Name: Ankit 2Age: 25 3City: Mumbai
Order matters! Arguments must match the parameter types and order exactly.
Return Types
A method can return a value to the code that called it. The return type declares what kind of value the method will send back.
How Return Works
1public class ReturnDemo { 2 3 static int square(int number) { 4 return number * number; // Sends the result back 5 } 6 7 public static void main(String[] args) { 8 int result = square(6); // 'result' receives the returned value 9 System.out.println("Square of 6: " + result); // 36 10 11 // You can also use the return value directly 12 System.out.println("Square of 8: " + square(8)); // 64 13 } 14}
Return Type Rules
| Rule | Explanation |
|---|---|
| Type must match | If you declare int, you must return an int |
| Only one return per path | Each execution path returns one value |
| Return ends the method | Code after return does not execute |
| Can return expressions | return a + b; is valid |
Example: Multiple Return Paths
1static String getGrade(int marks) { 2 if (marks >= 90) { 3 return "A+"; // Path 1 4 } else if (marks >= 80) { 5 return "A"; // Path 2 6 } else if (marks >= 70) { 7 return "B"; // Path 3 8 } else { 9 return "C"; // Path 4 (default) 10 } 11 // Every path returns a String — compiler is happy 12}
The void Return Type
When a method performs an action but does not need to send data back, use the void return type.
1static void displayHeader() { 2 System.out.println("========== WELCOME =========="); 3 System.out.println(" Tech3Space Portal "); 4 System.out.println("============================="); 5} 6 7static void printError(String message) { 8 System.out.println("❌ ERROR: " + message); 9}
void Methods Cannot Return Values
1// WRONG — Compilation error! 2static void greet() { 3 return "Hello"; // ❌ Cannot return a value from void method 4} 5 6// CORRECT 7static void greet() { 8 System.out.println("Hello"); 9 return; // Optional: explicit return in void method 10}
Tip: In
voidmethods, you can usereturn;alone to exit early, but you cannot return a value.
Method Overloading
Method overloading allows multiple methods in the same class to share the same name but have different parameter lists. Java automatically picks the right method based on the arguments you provide.
Why Overload?
Imagine a calculator app. Users might want to add 2 numbers, 3 numbers, or decimals. Instead of naming them add2(), add3(), addDouble(), you simply name them all add():
1public class Calculator { 2 3 // Version 1: Two integers 4 static int add(int a, int b) { 5 return a + b; 6 } 7 8 // Version 2: Three integers 9 static int add(int a, int b, int c) { 10 return a + b + c; 11 } 12 13 // Version 3: Two doubles 14 static double add(double a, double b) { 15 return a + b; 16 } 17 18 public static void main(String[] args) { 19 System.out.println(add(10, 20)); // Calls version 1 → 30 20 System.out.println(add(10, 20, 30)); // Calls version 2 → 60 21 System.out.println(add(2.5, 3.5)); // Calls version 3 → 6.0 22 } 23}
Rules for Method Overloading
| Rule | Valid? | Example |
|---|---|---|
| Different parameter count | ✅ Yes | add(int, int) vs add(int, int, int) |
| Different parameter types | ✅ Yes | add(int, int) vs add(double, double) |
| Different parameter order | ✅ Yes | print(String, int) vs print(int, String) |
| Different return type only | ❌ No | int add(int, int) vs double add(int, int) — NOT allowed |
The compiler decides which method to call at compile time based on the argument types. This is called compile-time polymorphism.
Recursion
Recursion is a programming technique where a method calls itself to solve a problem by breaking it into smaller, identical sub-problems.
Every recursive method needs two essential components:
- Base Case — The simplest version of the problem that can be solved directly (stops recursion)
- Recursive Case — The method calls itself with a smaller/simpler input
Example: Factorial
The factorial of n (written as n!) is the product of all positive integers from 1 to n.
5! = 5 × 4 × 3 × 2 × 1 = 120
1public class RecursionDemo { 2 3 static int factorial(int n) { 4 // Base case: 0! = 1 and 1! = 1 5 if (n == 0 || n == 1) { 6 return 1; 7 } 8 9 // Recursive case: n! = n × (n-1)! 10 return n * factorial(n - 1); 11 } 12 13 public static void main(String[] args) { 14 System.out.println("5! = " + factorial(5)); // 120 15 System.out.println("7! = " + factorial(7)); // 5040 16 } 17}
How Recursion Unfolds
factorial(5)
→ 5 × factorial(4)
→ 4 × factorial(3)
→ 3 × factorial(2)
→ 2 × factorial(1)
→ 1 (base case reached!)
→ 2 × 1 = 2
→ 3 × 2 = 6
→ 4 × 6 = 24
→ 5 × 24 = 120
Recursion vs Iteration
| Factor | Recursion | Iteration |
|---|---|---|
| Code clarity | Often cleaner for tree/graph problems | Simpler for linear tasks |
| Memory usage | Higher (stack frames) | Lower (single loop) |
| Risk | StackOverflowError if base case is wrong | Infinite loop if condition is wrong |
| Performance | Slower due to function call overhead | Faster for simple counting |
| Best for | Trees, graphs, divide-and-conquer | Loops, sequential processing |
⚠️ The StackOverflowError Trap
1// DANGEROUS — No base case! 2static void infiniteRecursion() { 3 infiniteRecursion(); // Calls itself forever 4}
Without a base case, the method calls itself until the call stack runs out of memory, crashing your program with a StackOverflowError.
Variable Arguments (Varargs)
Varargs (Variable Arguments) allow a method to accept any number of arguments of the same type. You do not need to overload the method for every possible count.
Syntax
1static returnType methodName(dataType... variableName) { 2 // variableName is treated as an array inside the method 3}
Example: Flexible Sum Method
1public class VarargsDemo { 2 3 static int sum(int... numbers) { 4 int total = 0; 5 for (int num : numbers) { 6 total += num; 7 } 8 return total; 9 } 10 11 public static void main(String[] args) { 12 System.out.println(sum(10, 20)); // 2 args → 30 13 System.out.println(sum(10, 20, 30)); // 3 args → 60 14 System.out.println(sum(5, 10, 15, 20, 25)); // 5 args → 75 15 System.out.println(sum()); // 0 args → 0 16 } 17}
Varargs Rules
| Rule | Explanation |
|---|---|
| Only one varargs parameter | You cannot have method(int... a, String... b) |
| Must be the last parameter | method(String name, int... scores) ✅ but method(int... scores, String name) ❌ |
| Treated as an array inside | You can use .length and array indexing |
Varargs + Regular Parameters
1static double average(String studentName, double... scores) { 2 double total = 0; 3 for (double score : scores) { 4 total += score; 5 } 6 return scores.length > 0 ? total / scores.length : 0; 7} 8 9// Usage 10System.out.println(average("Rahul", 85, 90, 78)); // 84.33
Method Memory & Call Stack
When you call a method, Java creates a stack frame on the call stack. This frame stores:
- The method's parameters
- Local variables
- The return address (where to go back when the method finishes)
Visualizing the Call Stack
1public class StackDemo { 2 3 static int add(int a, int b) { 4 int result = a + b; // Local variable in add()'s frame 5 return result; 6 } 7 8 static int multiply(int x, int y) { 9 int sum = add(x, y); // Calls add() — new frame pushed 10 return sum * 2; 11 } 12 13 public static void main(String[] args) { 14 int answer = multiply(3, 4); // Calls multiply() — new frame 15 System.out.println(answer); // 14 16 } 17}
Stack Visualization
Step 1: main() calls multiply(3, 4)
┌─────────────────┐
│ main() frame │
│ args, answer │
├─────────────────┤
│ multiply() frame│
│ x=3, y=4, sum │
└─────────────────┘
Step 2: multiply() calls add(3, 4)
┌─────────────────┐
│ main() frame │
├─────────────────┤
│ multiply() frame│
├─────────────────┤
│ add() frame │
│ a=3, b=4 │
│ result=7 │
└─────────────────┘
Step 3: add() returns 7, frame popped
┌─────────────────┐
│ main() frame │
├─────────────────┤
│ multiply() frame│
│ sum = 7 │
└─────────────────┘
Step 4: multiply() returns 14, frame popped
┌─────────────────┐
│ main() frame │
│ answer = 14 │
└─────────────────┘
Why this matters: Deep recursion creates many stack frames. If recursion goes too deep (e.g.,
factorial(100000)), you get aStackOverflowError. That is why iterative solutions are preferred for deep repetition.
Real-World Use Cases
Use Case 1: E-Commerce Order Processor
1public class OrderProcessor { 2 3 static double calculateDiscount(double total, boolean isMember) { 4 if (isMember && total > 1000) { 5 return total * 0.20; // 20% for members over ₹1000 6 } else if (isMember) { 7 return total * 0.10; // 10% for members 8 } 9 return 0; 10 } 11 12 static double calculateTax(double amount, double taxRate) { 13 return amount * taxRate; 14 } 15 16 static void printInvoice(double subtotal, double discount, double tax, double total) { 17 System.out.println("========== INVOICE =========="); 18 System.out.printf("Subtotal: ₹%10.2f%n", subtotal); 19 System.out.printf("Discount: -₹%10.2f%n", discount); 20 System.out.printf("Tax: +₹%10.2f%n", tax); 21 System.out.println("-----------------------------"); 22 System.out.printf("Total: ₹%10.2f%n", total); 23 System.out.println("============================="); 24 } 25 26 public static void main(String[] args) { 27 double subtotal = 2500.0; 28 boolean isMember = true; 29 30 double discount = calculateDiscount(subtotal, isMember); 31 double taxableAmount = subtotal - discount; 32 double tax = calculateTax(taxableAmount, 0.18); 33 double total = taxableAmount + tax; 34 35 printInvoice(subtotal, discount, tax, total); 36 } 37}
Use Case 2: Authentication System
1public class AuthSystem { 2 3 static boolean isValidEmail(String email) { 4 return email != null && email.contains("@") && email.contains("."); 5 } 6 7 static boolean isStrongPassword(String password) { 8 if (password == null || password.length() < 8) return false; 9 boolean hasUpper = false, hasLower = false, hasDigit = false; 10 for (char c : password.toCharArray()) { 11 if (Character.isUpperCase(c)) hasUpper = true; 12 if (Character.isLowerCase(c)) hasLower = true; 13 if (Character.isDigit(c)) hasDigit = true; 14 } 15 return hasUpper && hasLower && hasDigit; 16 } 17 18 static String validateRegistration(String email, String password) { 19 if (!isValidEmail(email)) { 20 return "Invalid email format."; 21 } 22 if (!isStrongPassword(password)) { 23 return "Password must be 8+ chars with upper, lower, and digit."; 24 } 25 return "✅ Registration successful!"; 26 } 27 28 public static void main(String[] args) { 29 System.out.println(validateRegistration("user@email.com", "Pass1234")); 30 System.out.println(validateRegistration("bad-email", "weak")); 31 } 32}
Use Case 3: Recursive File Search (Conceptual)
1// Conceptual example — demonstrates recursion in real systems 2static void listFiles(File directory) { 3 File[] files = directory.listFiles(); 4 if (files == null) return; // Base case 5 6 for (File file : files) { 7 if (file.isDirectory()) { 8 listFiles(file); // Recursive call for subdirectories 9 } else { 10 System.out.println(file.getName()); 11 } 12 } 13}
Common Mistakes
Mistake 1: Forgetting the Return Statement
1// WRONG — Missing return in one path! 2static int max(int a, int b) { 3 if (a > b) { 4 return a; 5 } 6 // What if a <= b? Compiler error: missing return statement! 7} 8 9// CORRECT 10static int max(int a, int b) { 11 if (a > b) { 12 return a; 13 } else { 14 return b; 15 } 16} 17 18// EVEN BETTER — Single return 19static int max(int a, int b) { 20 return (a > b) ? a : b; 21}
Mistake 2: Returning from void Method
1// WRONG 2static void greet() { 3 return "Hello"; // ❌ Cannot return value from void 4} 5 6// CORRECT 7static void greet() { 8 System.out.println("Hello"); 9}
Mistake 3: Wrong Argument Types
1static double divide(int a, int b) { 2 return (double) a / b; 3} 4 5// WRONG — Passing a String 6divide("10", "2"); // ❌ Compilation error 7 8// CORRECT 9divide(10, 2); // ✅ Works
Mistake 4: Missing Base Case in Recursion
1// WRONG — Infinite recursion → StackOverflowError 2static int factorial(int n) { 3 return n * factorial(n - 1); // Never stops! 4} 5 6// CORRECT 7static int factorial(int n) { 8 if (n <= 1) return 1; // Base case stops recursion 9 return n * factorial(n - 1); 10}
Mistake 5: Ignoring the Returned Value
1static int calculateTax(int salary) { 2 return salary * 20 / 100; 3} 4 5// WRONG — Result is lost! 6calculateTax(50000); // Calculates but throws away the result 7 8// CORRECT 9int tax = calculateTax(50000); 10System.out.println("Tax: " + tax);
Mistake 6: Overloading by Return Type Only
1// WRONG — Compilation error! Java cannot distinguish these. 2static int process(int x) { return x; } 3static double process(int x) { return x; } // ❌ Not allowed!
Best Practices
-
Use descriptive method names — A method name should tell you exactly what it does.
1// Good 2calculateTotalPrice(), isValidEmail(), fetchUserById() 3 4// Bad 5calc(), check(), getData() -
Keep methods small and focused — One method should do one thing. If it is longer than 20-30 lines, consider splitting it.
-
Return values instead of printing — Methods should be pure when possible. Let the caller decide what to do with the result.
1// Good — reusable 2static double calculateCircleArea(double radius) { 3 return Math.PI * radius * radius; 4} 5 6// Bad — tightly coupled to output 7static void printCircleArea(double radius) { 8 System.out.println(Math.PI * radius * radius); 9} -
Use early returns to reduce nesting — Flatten your logic.
1// Good 2static boolean isAdult(int age) { 3 if (age < 0) return false; // Guard clause 4 return age >= 18; 5} -
Document complex methods — Use JavaDoc comments.
1/** 2 * Calculates the compound interest. 3 * @param principal The initial amount 4 * @param rate Annual interest rate (decimal) 5 * @param years Number of years 6 * @return The final amount after interest 7 */ 8static double compoundInterest(double principal, double rate, int years) { 9 return principal * Math.pow(1 + rate, years); 10} -
Avoid deep recursion for large inputs — Use iteration when
ncould be large. -
Use varargs for truly variable input — Do not overload 10 versions of the same method.
Architecture & Performance Considerations
Method Inlining (JVM Optimization)
The Java JIT (Just-In-Time) compiler automatically inlines small, frequently called methods. This means it replaces the method call with the actual method body at runtime, eliminating the overhead of pushing/popping stack frames.
1// Original code 2int result = add(5, 3); 3 4// JVM may inline to: 5int result = 5 + 3; // No method call overhead!
What helps inlining:
- Small method bodies (under 35 bytes by default)
privateorstaticmethods- Methods called frequently ("hot" methods)
Tail Call Optimization (Not in Java)
Some languages (like Scala or Kotlin) optimize tail-recursive methods to use constant stack space. Java does NOT do this. Even tail-recursive methods in Java will eventually cause a StackOverflowError for large inputs.
1// This WILL stack overflow for large n in Java 2static int tailRecursiveSum(int n, int accumulator) { 3 if (n == 0) return accumulator; 4 return tailRecursiveSum(n - 1, accumulator + n); // Tail position 5}
Method Overloading vs Overriding
| Feature | Overloading | Overriding |
|---|---|---|
| When | Compile time | Runtime |
| Where | Same class | Parent-child classes |
| Signature | Must differ | Must match exactly |
| Return type | Can differ (co-variant) | Must be same or subtype |
| Purpose | Convenience | Polymorphism |
Static vs Instance Methods
| Feature | static Method | Instance Method |
|---|---|---|
| Belongs to | Class | Object |
| Called via | ClassName.method() or method() (same class) | object.method() |
| Access to fields | Only static fields | Static and instance fields |
| Use case | Utility functions, helpers | Object-specific behavior |
For beginners: Use
staticmethods until you learn about classes and objects. Then you will understand when to use instance methods.
Practice Programs
Exercise 1: Maximum of Three Numbers
1public class MaxOfThree { 2 3 static int max(int a, int b, int c) { 4 if (a >= b && a >= c) return a; 5 if (b >= a && b >= c) return b; 6 return c; 7 } 8 9 public static void main(String[] args) { 10 System.out.println("Max of (45, 78, 33): " + max(45, 78, 33)); // 78 11 } 12}
Exercise 2: Even or Odd Checker
1public class EvenOdd { 2 3 static boolean isEven(int number) { 4 return number % 2 == 0; 5 } 6 7 public static void main(String[] args) { 8 System.out.println("Is 24 even? " + isEven(24)); // true 9 System.out.println("Is 17 even? " + isEven(17)); // false 10 } 11}
Exercise 3: Power Calculator (Without Math.pow)
1public class PowerCalculator { 2 3 static double power(double base, int exponent) { 4 double result = 1; 5 int absExp = Math.abs(exponent); 6 7 for (int i = 1; i <= absExp; i++) { 8 result *= base; 9 } 10 11 return exponent < 0 ? 1 / result : result; 12 } 13 14 public static void main(String[] args) { 15 System.out.println("2^5 = " + power(2, 5)); // 32.0 16 System.out.println("2^-3 = " + power(2, -3)); // 0.125 17 } 18}
Exercise 4: Average Calculator with Varargs
1public class AverageCalculator { 2 3 static double average(int... numbers) { 4 if (numbers.length == 0) return 0; 5 6 int sum = 0; 7 for (int num : numbers) { 8 sum += num; 9 } 10 return (double) sum / numbers.length; 11 } 12 13 public static void main(String[] args) { 14 System.out.println("Avg of (10, 20): " + average(10, 20)); // 15.0 15 System.out.println("Avg of (10, 20, 30, 40): " + average(10, 20, 30, 40)); // 25.0 16 } 17}
Exercise 5: Reverse String Using Recursion
1public class RecursiveReverse { 2 3 static String reverse(String text) { 4 // Base case 5 if (text == null || text.length() <= 1) { 6 return text; 7 } 8 9 // Recursive case: last char + reverse of rest 10 return text.charAt(text.length() - 1) 11 + reverse(text.substring(0, text.length() - 1)); 12 } 13 14 public static void main(String[] args) { 15 System.out.println(reverse("Java")); // avaJ 16 System.out.println(reverse("Hello")); // olleH 17 } 18}
Mini Project: Modular Calculator Suite
Build a comprehensive calculator that demonstrates methods, overloading, varargs, and recursion in a single interactive program.
1import java.util.Scanner; 2 3public class ModularCalculator { 4 5 // ===== BASIC OPERATIONS ===== 6 static double add(double a, double b) { return a + b; } 7 static double subtract(double a, double b) { return a - b; } 8 static double multiply(double a, double b) { return a * b; } 9 static double divide(double a, double b) { 10 if (b == 0) { 11 System.out.println("❌ Cannot divide by zero!"); 12 return 0; 13 } 14 return a / b; 15 } 16 17 // ===== OVERLOADED: MULTIPLE NUMBERS ===== 18 static double add(double... numbers) { 19 double sum = 0; 20 for (double n : numbers) sum += n; 21 return sum; 22 } 23 24 static double multiply(double... numbers) { 25 double product = 1; 26 for (double n : numbers) product *= n; 27 return product; 28 } 29 30 // ===== ADVANCED OPERATIONS ===== 31 static double power(double base, int exp) { 32 double result = 1; 33 int absExp = Math.abs(exp); 34 for (int i = 0; i < absExp; i++) result *= base; 35 return exp < 0 ? 1 / result : result; 36 } 37 38 static long factorial(int n) { 39 if (n < 0) return -1; // Error indicator 40 if (n == 0 || n == 1) return 1; 41 return n * factorial(n - 1); 42 } 43 44 static boolean isPrime(int n) { 45 if (n <= 1) return false; 46 for (int i = 2; i <= Math.sqrt(n); i++) { 47 if (n % i == 0) return false; 48 } 49 return true; 50 } 51 52 // ===== UTILITY METHODS ===== 53 static void printHeader(String title) { 54 System.out.println("\n" + "=".repeat(40)); 55 System.out.println(" " + title); 56 System.out.println("=".repeat(40)); 57 } 58 59 static void printResult(String operation, double result) { 60 System.out.printf("✅ %s = %.4f%n", operation, result); 61 } 62 63 public static void main(String[] args) { 64 try (Scanner input = new Scanner(System.in)) { 65 boolean running = true; 66 67 while (running) { 68 System.out.println("\n========== MODULAR CALCULATOR =========="); 69 System.out.println("1. Basic Operations (+, -, *, /)"); 70 System.out.println("2. Sum of Multiple Numbers (Varargs)"); 71 System.out.println("3. Product of Multiple Numbers (Varargs)"); 72 System.out.println("4. Power Calculator"); 73 System.out.println("5. Factorial (Recursive)"); 74 System.out.println("6. Prime Checker"); 75 System.out.println("7. Exit"); 76 System.out.print("Select option (1-7): "); 77 78 int choice = Integer.parseInt(input.nextLine()); 79 80 switch (choice) { 81 case 1 -> { 82 printHeader("BASIC OPERATIONS"); 83 System.out.print("Enter first number: "); 84 double a = Double.parseDouble(input.nextLine()); 85 System.out.print("Enter operator (+, -, *, /): "); 86 char op = input.nextLine().charAt(0); 87 System.out.print("Enter second number: "); 88 double b = Double.parseDouble(input.nextLine()); 89 90 double result = switch (op) { 91 case '+' -> add(a, b); 92 case '-' -> subtract(a, b); 93 case '*' -> multiply(a, b); 94 case '/' -> divide(a, b); 95 default -> 0; 96 }; 97 98 if ("+-*/".indexOf(op) >= 0) { 99 printResult(a + " " + op + " " + b, result); 100 } 101 } 102 case 2 -> { 103 printHeader("VARARGS SUM"); 104 System.out.print("How many numbers? "); 105 int count = Integer.parseInt(input.nextLine()); 106 double[] nums = new double[count]; 107 for (int i = 0; i < count; i++) { 108 System.out.print("Number " + (i + 1) + ": "); 109 nums[i] = Double.parseDouble(input.nextLine()); 110 } 111 printResult("Sum", add(nums)); 112 } 113 case 3 -> { 114 printHeader("VARARGS PRODUCT"); 115 System.out.print("How many numbers? "); 116 int count = Integer.parseInt(input.nextLine()); 117 double[] nums = new double[count]; 118 for (int i = 0; i < count; i++) { 119 System.out.print("Number " + (i + 1) + ": "); 120 nums[i] = Double.parseDouble(input.nextLine()); 121 } 122 printResult("Product", multiply(nums)); 123 } 124 case 4 -> { 125 printHeader("POWER CALCULATOR"); 126 System.out.print("Base: "); 127 double base = Double.parseDouble(input.nextLine()); 128 System.out.print("Exponent: "); 129 int exp = Integer.parseInt(input.nextLine()); 130 printResult(base + "^" + exp, power(base, exp)); 131 } 132 case 5 -> { 133 printHeader("FACTORIAL"); 134 System.out.print("Enter number: "); 135 int n = Integer.parseInt(input.nextLine()); 136 long fact = factorial(n); 137 if (fact == -1) { 138 System.out.println("❌ Factorial not defined for negative numbers."); 139 } else { 140 printResult(n + "!", fact); 141 } 142 } 143 case 6 -> { 144 printHeader("PRIME CHECKER"); 145 System.out.print("Enter number: "); 146 int n = Integer.parseInt(input.nextLine()); 147 System.out.println(n + (isPrime(n) ? " is PRIME ✅" : " is NOT PRIME ❌")); 148 } 149 case 7 -> { 150 System.out.println("\n👋 Thank you for using Modular Calculator!"); 151 running = false; 152 } 153 default -> System.out.println("❌ Invalid choice."); 154 } 155 } 156 } 157 } 158}
What This Project Covers:
- Method declaration with various return types
- Method overloading (
add(double, double)vsadd(double...)) - Varargs for flexible input
- Recursion for factorial
- Utility methods (
printHeader,printResult) - Input validation and error handling
- Interactive menu with
switchexpressions
Summary & Cheat Sheet
Quick Reference
| Concept | Syntax | Example |
|---|---|---|
| Method declaration | modifier returnType name(params) { } | public static int add(int a, int b) |
| Method call | name(arguments); | add(5, 3); |
| Return value | return value; | return a + b; |
| void method | void name() { } | void greet() { ... } |
| Parameter | Variable in declaration | int a in add(int a, int b) |
| Argument | Value passed in call | 5 in add(5, 3) |
| Overloading | Same name, different params | add(int, int) + add(double, double) |
| Recursion | Method calls itself | factorial(n) = n * factorial(n-1) |
| Varargs |
Key Takeaways
- Methods are reusable code blocks — Write once, call many times.
- Parameters are placeholders; arguments are actual values — Do not confuse them.
- Return types must be honored — If you promise an
int, return anint. voidmeans "no return value" — Use it for actions, not calculations.- Overloading improves API design — Same intuitive name, different inputs.
- Recursion needs a base case — Without it, your program crashes with
StackOverflowError. - Varargs eliminate overload bloat — One method handles any number of arguments.
- The call stack is real — Every method call uses memory. Deep recursion is dangerous.
- Name methods after what they do —
calculateTotal()is better thancalc(). - Keep methods focused — One method, one responsibility.
What's Next?
Now that you can organize code into reusable methods, you are ready for:
- Arrays — Pass collections of data to methods
- Object-Oriented Programming — Classes, objects, inheritance, polymorphism
- Exception Handling — Make your methods robust against errors
- Unit Testing — Test each method independently
- Design Patterns — Learn how methods work together in larger architectures
Methods are the building blocks of every Java application. Master them, and you have mastered the art of writing clean, maintainable, professional code.
SEO Keywords
java methods tutorial, java method overloading, java recursion example, java varargs tutorial, java functions guide, java method declaration, java return types explained, java method parameters, java method best practices, learn java methods, java programming methods, java method call stack, java method overloading examples, java recursive methods, java beginner methods
Found this guide helpful? Bookmark it and share it with fellow learners. For more Java tutorials, explore the Tech3Space Java Course.
Tags: #Java #Methods #Functions #Overloading #Recursion #Varargs #Programming #Tech3Space #CodingForBeginners