What Is a Method in Java?
Think of a method like a recipe card in a restaurant kitchen. The card has a name (“Masala Tea”), lists what it needs (milk, tea leaves), describes the steps, and produces something (a cup of tea). Any cook can follow the same card again and again.
In Java:
- the name identifies the method,
- the parameters are its inputs,
- the body holds the steps,
- the return value is the result.
You’ve already used methods: System.out.println(...), Math.max(...) and main itself are all methods.
Why Do We Need Methods?
Here is a receipt printed without methods. The divider line is repeated four times:
Output:
==============================Pen x 2 = Rs 40
==============================
Notebook x 3 = Rs 180
==============================
Total = Rs 220
==============================
To change the divider style, you’d have to edit four lines and hope you didn’t miss one. Move it into a method:
Output:
------------------------------Pen x 2 = Rs 40
------------------------------
Notebook x 3 = Rs 180
------------------------------
Total = Rs 220
------------------------------
The divider style changed by editing one line. That’s the core benefit of methods:
| Benefit | What it means |
|---|---|
| Reuse | Write once, call many times |
| One place to change | Fix or update the logic in a single spot |
| Readability | printDivider() explains itself; a raw println doesn’t |
| Testing and debugging | Check one small method at a time |
| Abstraction | Callers use the method without knowing how it works inside |
Java Method Syntax: Anatomy of a Method
Every method declaration has these parts, in this order. Only the name, the parentheses and the body are always required. The return type is required too, but it may be void.
| Part | Example | Notes |
|---|---|---|
| Modifiers (optional) | public, private, static | Access and ownership. You’ll study access modifiers with OOP |
| Return type | int, String, boolean, void | void means “returns nothing” |
| Name | lineTotal, isEligible | camelCase, usually starting with a verb |
| Parameter list | (int price, int quantity) | Can be empty: () |
| Body | { ... } | The statements that run when the method is called |
What Is a Method Signature in Java?
The method signature is the method’s name plus the types and order of its parameters. For static int lineTotal(int price, int quantity), the signature is lineTotal(int, int).
The return type, modifiers and parameter names are not part of the signature. That’s why two methods that differ only in return type can’t exist in the same class (see Mistake 6). You’ll use signatures to tell methods apart in Method Overloading.
How to Call a Method in Java
You call a method by writing its name followed by parentheses, passing a value for each parameter:
Output:
Pen total: Rs 40Notebook total: Rs 180
Bill: Rs 220
Parameters vs Arguments in Java
| Term | Where it appears | In the example |
|---|---|---|
| Parameter | In the method declaration: a variable that receives a value | int price, int quantity |
| Argument | In the method call: the actual value you pass | 20, 2 |
Arguments are matched to parameters by position: the first argument goes to the first parameter. The values don’t need exactly the same type. Java allows safe widening (an int argument for a double parameter):
Output:
4.54.5The reverse (a double argument for an int parameter) could lose data, so it fails to compile:
NarrowingArgument.java:3: error: incompatible types: possible lossy conversion from double to int
System.out.println(twice(2.5));
^
^Java copies each argument’s value into the parameter. This is pass by value, which has its own lesson: Pass by Value in Java. Parameters in depth come next in Method Parameters.
void vs return: Does the Method Send Back a Value?
| Return type | Must it return a value? | Can you store the call’s result? |
|---|---|---|
void | No (a bare return; may end it early) | No |
Any other type (int, String, …) | Yes, on every path through the body | Yes |
Using return to Leave a Method Early
A bare return; in a void method stops it immediately. It’s handy for rejecting bad input first:
Output:
15: minor-3: invalid age
22: adult
return ends the method, unlike break, which ends only a loop or switch (from Break and Continue). Return types in depth: Method Return Types.
What Happens When a Method Is Called? (Inside the JVM)
Output:
1. main starts2. square starts with n = 7
3. square returns 49
4. main got 49
5. main ends
Step by step:
mainpauses at the callsquare(7).- The JVM creates a stack frame for
squareon the thread’s call stack. The frame holds the parametern = 7and the local variableanswer. square’s body runs.return answer;sends 49 back, the frame is removed, andnandanswerdisappear.mainresumes from exactly where it paused, now holding 49.
The Call Stack: Methods Calling Methods
Output:
enter mainenter placeOrder
enter calculateBill
enter addTax (top of the stack)
exit calculateBill
bill = 590.0
exit placeOrder
exit main
▶ Try it in the ExamAdda Compiler
Each call pushes a new frame on top of the stack, and each return pops it off. The last method called is always the first to finish (Last In, First Out), which is why the “exit” lines appear in reverse order.
What the Bytecode Shows
Running javap -c LineTotal (JDK 25) on the earlier example shows the call and the return as real JVM instructions:
public static void main(java.lang.String[]);
Code:
0: bipush 20
2: iconst_2
3: invokestatic #7 // Method lineTotal:(II)I
6: istore_1
...
static int lineTotal(int, int);
Code:
0: iload_0
1: iload_1
2: imul
3: istore_2
4: iload_25: ireturn
bipush 20andiconst_2push the two arguments.invokestaticcalls the static method;(II)Imeans “takes twoints, returns anint”.- Inside
lineTotal,iload_0andiload_1read the parameters from the new frame’s local variables. ireturnhands theintresult back to the caller.
The JVM’s internal descriptor (II)I includes the return type. The Java-language signature (lineTotal(int, int)) does not, and the Java signature is what the compiler uses to decide whether two methods clash.
Static vs Instance Methods in Java
So far, every method has been static: it belongs to the class, so main (also static) can call it directly. A method without static is an instance method: it belongs to an object, so you must create an object first.
Output:
Max of 12 and 7: 12Hello, Asha| Feature | Static method | Instance method |
|---|---|---|
| Keyword | static | none |
| Belongs to | The class | Each object |
| How to call | methodName() inside the class, ClassName.methodName() outside | object.methodName() |
| Can use object data (fields)? | No (no object) | Yes |
| Typical use | Utilities: Math.max, Integer.parseInt | Behaviour of an object: name.length() |
Objects, fields and this are covered in the OOP section, starting with Introduction to OOP.
Predefined vs User-Defined Methods
Output:
4212.0
9
BENGALURU
Predefined methods come with the Java library (Math.max, String.length). User-defined methods are the ones you write (lineTotal, printDivider). Both follow the same rules.
The main Method Is Also a Method
public static void main(String[] args) is the classic entry point: the JVM calls it to start your program.
| Part | Why it’s there (classic form) |
|---|---|
public | The JVM, outside your class, must be able to call it |
static | The JVM calls it before any object exists |
void | It returns nothing to the JVM |
String[] args | Receives command-line arguments: java App alpha beta gives args = {"alpha", "beta"} |
The order of declarations doesn’t matter. A method can be called before it appears in the file:
Output:
first() runs, even though it is declared after mainsecond() runsNew in Java 25: Instance main Methods and Compact Source Files
Since JDK 25 (JEP 512, final; previewed in JDK 21–24), main no longer has to be public, static, or take String[] args:
Output (JDK 25):
Instance main method: no static, no public, no String[] args You can even leave out the class. This is a compact source file, and the new java.lang.IO class prints without System.out:
Output (JDK 25, run with java HelloModern.java):
Hello from a compact source file (JDK 25)Square of 9 is 81On JDK 21 the same file fails unless preview features are turned on:
HelloModern.java:1: error: unnamed classes are a preview feature and are disabled by default.void main() {
^
(use --enable-preview to enable unnamed classes)
If a class has both forms, which main runs? The classic one with String[] args wins:
Output (JDK 25):
static main(String[] args) was chosenInterview tip: most companies still run Java 8, 11, 17 or 21, so always know the classic
public static void main(String[] args)and why each keyword is there. Mentionvoid main()as the Java 25 simplification for small programs.
Real-World Example: Student Report Card
Small, single-purpose methods, each doing one job:
Output:
Asha avg 85.00 grade A PASSRavi avg 45.00 grade C PASS
Meena avg 32.00 grade F FAIL
main reads like a to-do list, and each method can be checked on its own. The 3.0 in average forces decimal division; with 3, Java would do integer division. The pass mark lives in exactly one place (hasPassed), so changing it is a one-line edit.
Rules and Important Points
- Every method must be declared inside a class (in a compact source file, the class is created for you).
- A method cannot be declared inside another method.
- A non-
voidmethod mustreturna value on every path. - A
voidmethod can’t return a value, and its call can’t be stored in a variable. - Local variables and parameters exist only while the method runs; other methods can’t see them.
- Arguments must match the parameters in number, order and compatible type (widening is allowed).
- A static method can’t call an instance method directly; it needs an object.
- Two methods in one class can’t share a signature, even if their return types differ.
Common Mistakes With Methods in Java
Mistake 1: Calling an Instance Method From static main
StaticContext.java:3: error: non-static method greet(String) cannot be referenced from a static contextgreet("Asha");
^
1 error
Why: main is static and runs without an object, but greet needs one.
Mistake 2: Missing return Statement
MissingReturn.java:10: error: missing return statement}
^
1 error
Why: when marks < 40, the method reaches its end without returning a String.
Mistake 3: Storing the Result of a void Method
VoidAssign.java:3: error: incompatible types: void cannot be converted to StringString text = printWelcome();
^
1 error
Fix: call it on its own line (printWelcome();), or change it to return a String.
Mistake 4: Returning a Value From a void Method
VoidReturnValue.java:8: error: incompatible types: unexpected return valuereturn score;
^
1 error
Fix: use a bare return;, or change void to int.
Mistake 5: Using Another Method’s Local Variable
ScopeError.java:8: error: cannot find symbolSystem.out.println(price - discount);
^
symbol: variable discount
location: class ScopeError
1 error
Why: discount lives only inside main’s frame. Fix: pass it in as a parameter: applyDiscount(500, 10).
Mistake 6: Two Methods That Differ Only in Return Type
ReturnTypeOnly.java:6: error: method total(int,int) is already defined in class ReturnTypeOnlystatic double total(int a, int b) {
^
1 error
Why: both have the signature total(int, int). Change the parameter list instead (overloading).
Mistake 7: Declaring a Method Inside Another Method
NestedMethod.java:3: error: illegal start of expressionstatic void helper() {
^
NestedMethod.java:7: error: class, interface, annotation type, enum, record, method or field expected
}
^
2 errors
Fix: move helper out, next to main, inside the class.
Mistake 8: A Method That Calls Itself Forever
Exception in thread "main" java.lang.StackOverflowErrorat InfiniteSelfCall.countDown(InfiniteSelfCall.java:7)
at InfiniteSelfCall.countDown(InfiniteSelfCall.java:7)
at InfiniteSelfCall.countDown(InfiniteSelfCall.java:7)
Why: every call pushes a new frame, and none ever pops, until the call stack is full. A method that calls itself needs a stopping condition. You’ll learn how in Recursion in Java.
Methods vs Code in main: When to Create a Method
| Situation | Keep it inline | Make a method |
|---|---|---|
| Code is used once and is 1–3 lines | ✅ | |
| The same steps appear twice or more | ✅ | |
| A block needs a comment to explain what it does | ✅ (the method name becomes the comment) | |
main is longer than a screen | ✅ | |
| You want to test a calculation separately | ✅ |
Best Practices
- One method, one job. If the name needs “and” (
readAndPrintAndSave), split it. - Name methods with verbs:
calculateTotal,printReport. Name boolean methods as questions:isEligible,hasPassed. - Prefer returning a value over printing inside calculations.
average()returns a number;printReport()prints. This keeps calculations reusable. - Keep parameter lists short. More than 3–4 parameters is a sign to group the data, which you’ll do with objects and records later.
- Validate input early with a guard
returninstead of deep nesting. - Keep
mainas an orchestrator: it calls methods; the methods do the work. - Avoid magic numbers inside methods; use named constants (
final int PASS_MARK = 35;).
Interview Questions on Methods in Java
How to answer in an interview: “What is a method in Java?”
“A method is a named block of code inside a class that performs one task. It’s declared with a return type, a name and a parameter list, and called by name with arguments. Each call gets its own stack frame for parameters and local variables, which is removed when the method returns. Methods give us reuse, readability and easier testing.”
Output-Prediction Questions
Q1. What does this print?
Answer: 5 10. x is a copy of n, so changing x doesn’t affect n (pass by value).
Q2. What does this print?
Answer: 23. show(5) returns before printing.
Q3. Does this compile?
Answer: Yes. Both paths return a value, so the compiler is satisfied.
Conceptual Follow-Ups
- Why is
mainstatic? So the JVM can call it without creating an object first. (Java 25 adds instancevoid main()as an alternative; the JVM then creates the object for you.) - Is the return type part of the method signature? No. The signature is the name plus the parameter types, which is why overloading by return type alone fails.
- Where are a method’s local variables stored? In its stack frame on the thread’s call stack. They disappear when the method returns. Objects live on the heap.
- What is the difference between parameters and arguments? Parameters are declared in the method; arguments are the values passed in the call.
- What causes
StackOverflowError? Too many nested calls (usually recursion without a stopping condition) fill the call stack.
Comparison Questions
- Static vs instance method: class-level vs object-level; static can’t use object fields directly.
returnvsbreak:returnexits the method;breakexits only a loop or switch.- Method vs function: in Java, every “function” is a method because it must live inside a class.
More practice: Java Interview Questions for Freshers · Intermediate Questions
Practice Exercises
- Easy: Write
static boolean isEven(int n)and print the result for 7 and 12. - Easy: Write
static int max3(int a, int b, int c)that returns the largest of three numbers. - Easy–Medium: Write
static double celsiusToFahrenheit(double c)and print a table for 0, 25, 37 and 100 °C using a loop. - Medium: Write
static boolean isPrime(int n), then use it in a loop to print every prime from 1 to 50. - Medium: Split an electricity-bill calculator into
calculateUnits,calculateAmountandprintBillmethods.
Solve them on ExamAdda Practice and run them in the ExamAdda Compiler.
FAQs
1. What is a method in Java, in simple words?
A method is a named set of instructions inside a class. You write it once and run it by calling its name, optionally passing inputs and getting back a result.
2. Why is the main method static in Java?
The JVM calls main before any object of your class exists, so it must belong to the class itself. Since Java 25, an instance void main() is also allowed; the launcher creates the object for you.
3. Can we declare a method inside another method in Java?
No. Methods must be declared directly inside a class. A method declared inside main gives “illegal start of expression”.
4. What is the difference between a void method and a method with a return type?
A void method performs an action and returns nothing. A method with a return type must send back a value of that type on every path, and you can store or use that value.
5. Can a method return more than one value?
Not directly; a method returns one value. To send back several, return an array, an object, or a record (Java 16+).
6. Is a method the same as a function?
Conceptually yes, but in Java every function belongs to a class or object, so it’s called a method.
7. What is the difference between a static and a non-static method?
A static method belongs to the class and is called without an object. A non-static (instance) method belongs to an object and needs one, like name.length().
Article Summary
- A method is a named, reusable block of code inside a class, with a return type, a name, parameters and a body.
- You call a method with arguments, which are copied into its parameters by position; it returns one value or nothing (
void). - Each call gets a stack frame on the call stack; frames are pushed on call and popped on return.
- Static methods belong to the class; instance methods need an object.
mainis static so the JVM can call it without an object, and Java 25 also allowsvoid main(). - Most method errors are compile-time: missing return, void misuse, static context, scope, and duplicate signatures.
Conclusion
Methods turn a long, repetitive main into small named steps that are easy to read, reuse and test. Keep each method focused on one job, return values instead of printing inside calculations, and remember what happens on the call stack. Next, you’ll learn how to pass data into methods properly in Method Parameters in Java.
← Previous: Switch Statement in Java · Next → Method Parameters in Java
References: JEP 512: Compact Source Files and Instance Main Methods · Oracle Java Tutorials: Defining Methods · JLS §8.4: Method Declarations