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
------------------------------

▶ Try it in the ExamAdda Compiler

The divider style changed by editing one line. That’s the core benefit of methods:

BenefitWhat it means
ReuseWrite once, call many times
One place to changeFix or update the logic in a single spot
ReadabilityprintDivider() explains itself; a raw println doesn’t
Testing and debuggingCheck one small method at a time
AbstractionCallers use the method without knowing how it works inside

Java Method Syntax: Anatomy of a Method

Whiteboard
Loading diagram...

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.

PartExampleNotes
Modifiers (optional)public, private, staticAccess and ownership. You’ll study access modifiers with OOP
Return typeint, String, boolean, voidvoid means “returns nothing”
NamelineTotal, isEligiblecamelCase, 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

▶ Try it in the ExamAdda Compiler

Parameters vs Arguments in Java

TermWhere it appearsIn the example
ParameterIn the method declaration: a variable that receives a valueint price, int quantity
ArgumentIn the method call: the actual value you pass20, 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.5

The 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 typeMust it return a value?Can you store the call’s result?
voidNo (a bare return; may end it early)No
Any other type (int, String, …)Yes, on every path through the bodyYes

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

▶ Try it in the ExamAdda Compiler

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:

  1. main pauses at the call square(7).
  2. The JVM creates a stack frame for square on the thread’s call stack. The frame holds the parameter n = 7 and the local variable answer.
  3. square’s body runs.
  4. return answer; sends 49 back, the frame is removed, and n and answer disappear.
  5. main resumes from exactly where it paused, now holding 49.

The Call Stack: Methods Calling Methods

Output:

enter main  enter placeOrder
enter calculateBill
enter addTax (top of the stack)
exit calculateBill
bill = 590.0
exit placeOrder
exit main

▶ Try it in the ExamAdda Compiler

Whiteboard
Loading diagram...

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_2
         5: ireturn
  • bipush 20 and iconst_2 push the two arguments.
  • invokestatic calls the static method; (II)I means “takes two ints, returns an int”.
  • Inside lineTotal, iload_0 and iload_1 read the parameters from the new frame’s local variables.
  • ireturn hands the int result 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

▶ Try it in the ExamAdda Compiler

FeatureStatic methodInstance method
Keywordstaticnone
Belongs toThe classEach object
How to callmethodName() inside the class, ClassName.methodName() outsideobject.methodName()
Can use object data (fields)?No (no object)Yes
Typical useUtilities: Math.max, Integer.parseIntBehaviour 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.

PartWhy it’s there (classic form)
publicThe JVM, outside your class, must be able to call it
staticThe JVM calls it before any object exists
voidIt returns nothing to the JVM
String[] argsReceives 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() runs

New 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 81

On 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 chosen

Interview 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. Mention void 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

▶ Try it in the ExamAdda Compiler

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

  1. Every method must be declared inside a class (in a compact source file, the class is created for you).
  2. A method cannot be declared inside another method.
  3. A non-void method must return a value on every path.
  4. A void method can’t return a value, and its call can’t be stored in a variable.
  5. Local variables and parameters exist only while the method runs; other methods can’t see them.
  6. Arguments must match the parameters in number, order and compatible type (widening is allowed).
  7. A static method can’t call an instance method directly; it needs an object.
  8. 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 context        greet("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 String        String 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 value        return 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 symbol        System.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 ReturnTypeOnly    static 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 expression        static 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.StackOverflowError	at 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

SituationKeep it inlineMake 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

  1. One method, one job. If the name needs “and” (readAndPrintAndSave), split it.
  2. Name methods with verbs: calculateTotal, printReport. Name boolean methods as questions: isEligible, hasPassed.
  3. Prefer returning a value over printing inside calculations. average() returns a number; printReport() prints. This keeps calculations reusable.
  4. 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.
  5. Validate input early with a guard return instead of deep nesting.
  6. Keep main as an orchestrator: it calls methods; the methods do the work.
  7. 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

  1. Why is main static? So the JVM can call it without creating an object first. (Java 25 adds instance void main() as an alternative; the JVM then creates the object for you.)
  2. 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.
  3. 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.
  4. What is the difference between parameters and arguments? Parameters are declared in the method; arguments are the values passed in the call.
  5. 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.
  • return vs break: return exits the method; break exits 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

  1. Easy: Write static boolean isEven(int n) and print the result for 7 and 12.
  2. Easy: Write static int max3(int a, int b, int c) that returns the largest of three numbers.
  3. Easy–Medium: Write static double celsiusToFahrenheit(double c) and print a table for 0, 25, 37 and 100 °C using a loop.
  4. Medium: Write static boolean isPrime(int n), then use it in a loop to print every prime from 1 to 50.
  5. Medium: Split an electricity-bill calculator into calculateUnits, calculateAmount and printBill methods.

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. main is static so the JVM can call it without an object, and Java 25 also allows void 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