Method Return Types in Java: void, the return Statement and Examples

Not 3.5. It prints 3.0. By the end of this lesson, you’ll know exactly why.

Quick Answer

The return type in Java is the data type a method promises to send back to its caller, written before the method name: int, double, boolean, String, an array, or void (nothing). The return statement ends the method and hands back a value of that type. The compiler checks that every path returns a compatible value.

Before you start: read Method Parameters in Java. Parameters bring data into a method; return values send results out.

What Does a Return Type Declare?

The return type is a contract. Callers know what they’ll get back, and the compiler enforces it on both sides:

  • Inside the method: every return must give a value compatible with the declared type.
  • At the call: the result can only be used where that type fits.

Think of a vending machine. The label says “Cold drink, ₹40”. You know what comes out before you press the button, and the machine can’t drop a packet of chips instead.

void vs Value-Returning Methods

void methodValue-returning method
Declaresstatic void printBill(...)static double total(...)
PurposeDoes something (print, save, update)Computes something and gives it back
returnOptional; only return; (no value)Required on every path: return value;
Can the call be stored?NoYes: double t = total(...);

Returning Primitive Values

Output:

Units: 36GST: 270.0
Free delivery: true
Grade: A

▶ Try it in the ExamAdda Compiler

Methods That Return boolean

A method that answers a yes/no question should return the condition directly:

Output:

17: cannot vote yet18: can vote
30: can vote

age >= 18 already is a boolean, so there’s no need for if … return true; else return false;. Name such methods as questions: canVote, isEmpty, hasStock.

Type Rules for Return Values: Widening and Narrowing

The returned value doesn’t need exactly the declared type. It must be assignable to it, using the same rules as assigning to a variable.

Widening Happens Automatically

Output:

 60.0

Narrowing Needs a Cast

Returning a double from an int method fails, because data could be lost:

NarrowingReturn.java:7: error: incompatible types: possible lossy conversion from double to int        return price;
^
1 error

Decide explicitly whether you want rounding or truncation:

Output:

5049

Why Does average(3, 4) Return 3.0? (The Puzzle Explained)

Output:

Java evaluates the expression (a + b) / 2 first, using int arithmetic, so 7 / 2 = 3. Only then is 3 widened to 3.0 to match the return type. A double return type doesn’t change how the expression is calculated. Fix it by making one operand a double (2.0).

Returning Reference Types: String, Arrays and Records

A method can return any reference type: a String, an array, or an object.

Output:

 Wireless Mouse - Rs 799[7, 14, 21, 28, 35]

The return type int[] means “an array of ints”. You’ll study arrays fully in Introduction to Arrays.

How Do You Return Multiple Values in Java?

A Java method returns exactly one value. To send back several, return one value that holds them. The modern, clean way is a record (Java 16+):

Output:

Min: 27, Max: 35MinMax[min=27, max=35]

▶ Try it in the ExamAdda Compiler

A record is a one-line data class with named parts (min(), max()), so callers can’t mix up which value is which. Older code returns an array (new int[]{min, max}), which works, but the caller has to remember that index 0 is the minimum. You’ll learn records properly in the OOP sections.

Can a Method Return null?

Yes: any method with a reference return type can return null, often meaning “not found”. But the caller must check for it:

Output:

Found: DIWALI20Found: null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "" is null
at ReturnNull.main(ReturnNull.java:8)

Primitive return types (int, double, …) can never return null. If a method can return null, say so clearly in its name or documentation, or check the result before using it. Later you’ll meet Optional (Java 8+), which makes “maybe no value” explicit.

How the return Statement Works

return does two things at once: it ends the method immediately and hands a value back to the caller.

Whiteboard
Loading diagram...

Execution never continues past a return inside the method. Control jumps straight back to the line that called it, carrying the value.

Multiple Return Paths and Early Return

A method may have several return statements; the first one reached wins. That’s ideal for searches:

Output:

return i leaves both the loop and the method, so there’s no need for break or a flag. The -1 “not found” value is a widely used convention.

Returning a switch Expression (Java 14+)

A switch expression produces a value, so you can return it directly:

Output:

2930
31

More on switch expressions: Switch Statement in Java.

What Can the Caller Do With a Return Value?

Output:

Price with GST: 1180.0Two items: 2360.0
Rounded: 1179
Delivery charge applies

You can also store a returned value with var (Java 10+). var total = subtotal(3, 249.5); infers double from the return type and prints 748.5.

The Fifth Option: Ignoring It (Usually a Bug)

Java lets you call a value-returning method and throw the result away. It compiles, but it often hides a bug:

Output:

punePUNE

toUpperCase() doesn’t change the string; it returns a new one. If you don’t store that result, the work is lost. You’ll see why in the Strings section (strings are immutable).

How Return Values Work Internally

Each method’s last instruction is a typed return in bytecode. Running javap -c (JDK 25) on the earlier examples shows:

  static int countUnits(int, int);
3: ireturn
static double gstOn(double);
5: dreturn
static boolean qualifiesForFreeDelivery(double);
13: ireturn
static char gradeFor(int);
13: ireturn
static java.lang.String productTag(java.lang.String, int);
7: areturn
static int[] firstMultiples(int, int);
26: areturn
public static void main(java.lang.String[]);
        33: return


Return typeBytecodeNote
int, boolean, char, byte, shortireturnThe JVM stores small types as int internally
long / float / doublelreturn / freturn / dreturn
Any reference (String, arrays, objects)areturnReturns the reference; the object stays on the heap
voidreturnHands back nothing

The returned value is pushed onto the caller’s operand stack as the callee’s frame is removed. For references, only the address travels back; the array or object itself never moves.

Rules of Return Types

  1. Every method declares exactly one return type; use void if it returns nothing.
  2. A non-void method must return a compatible value on every possible path.
  3. A void method may use return; but never return value;.
  4. Returned values follow assignment rules: widening is automatic, narrowing needs a cast.
  5. Statements directly after a return in the same block are unreachable (a compile error).
  6. Reference return types can return null; primitive return types can’t.
  7. The return type is not part of the method signature, so you can’t overload by return type alone (next lesson: Method Overloading).

Common Mistakes With Return Types

Mistake 1: A Path Without a return

 MissingPath.java:14: error: missing return statement    }
^
1 error

Why: the three conditions cover every age, but the compiler doesn’t analyse the logic. It only sees an else if with no final else, so in principle the method could reach its end without returning.

Fixed output for 9, 16 and 25: child, teen, adult.

Mistake 2: Code After return


 Unreachable.java:8: error: unreachable statement        System.out.println("done");
^
1 error

Fix: move the statement before the return, or delete it.

Mistake 3: Storing the Result of a void Method

 VoidValue.java:3: error: incompatible types: void cannot be converted to int        int total = printTotal(250);
^
1 error

Fix: either call it on its own (printTotal(250);), or change it to return an int.

Mistake 4: Returning a Wider Type Than Declared

return price; from an int method, where price is a double, gives possible lossy conversion. Cast deliberately, as shown above.

Mistake 5: Assuming the Return Type Fixes the Calculation

return (a + b) / 2; in a double method still does integer division. Use 2.0.

Mistake 6: Ignoring a Returned Value

city.toUpperCase(); on its own line does nothing useful. Store or use the result.

Mistake 7: Using a Possibly-null Result Without Checking

Return Value vs Printing Inside the Method

return the resultPrint inside the method
Reusable in calculations✅ Yes❌ No; the value is gone after printing
Testable✅ Compare the returned value❌ Have to capture console output
Flexible output✅ Caller decides how to show it❌ Fixed format
Best forCalculations and checksFinal display steps only

A good rule: calculate in one method, display in another. That’s exactly how the invoice example below is built.

Real-World Example: GST Invoice

Output:

Asha: subtotal Rs 698.00, with GST Rs 823.64, payable Rs 872.64Rahul: subtotal Rs 1299.00, with GST Rs 1532.82, payable Rs 1532.82 (free delivery)

▶ Try it in the ExamAdda Compiler

This one program uses four return types: double (amounts), boolean (freeDelivery), String (rupees), and void (printInvoice). Only the void method prints; every other method returns a value that can be reused. freeDelivery is called by both deliveryCharge and printInvoice, so the threshold lives in one place.

Best Practices

  1. Return values from calculations; print only in display methods.
  2. Return booleans directly (return age >= 18;).
  3. Use guard clauses: return early for invalid input instead of nesting ifs.
  4. Make the last branch a plain else, or add a final return, to satisfy the compiler cleanly.
  5. Return a record (Java 16+) rather than an array when you need several named values.
  6. Avoid returning null where a clear alternative exists (an empty array, -1 for an index, or Optional later). When you do return null, make it obvious.
  7. Don’t ignore return values, especially from String methods.

Interview Questions on Return Types

How to answer in an interview: “What is a return type in Java?”
“The return type is the data type a method promises to give back, declared before the method name. void means nothing is returned. The return statement ends the method and hands back a value compatible with that type, and the compiler checks every path. A method can return only one value, so for several values we return an array, an object or a record.”

Output-Prediction Questions

Q1.

Answer: 2.0. Integer division gives 2, which is then widened to 2.0.

Q2.

Answer: 0. That’s -1 + 1.

Q3.

Answer: hi. The uppercase result was ignored.

Conceptual Follow-Ups

  1. Can a method return more than one value? No. Return one container: an array, an object or a record.
  2. Is the return type part of the signature? No, which is why overloading by return type alone fails.
  3. Can a constructor have a return type? No. If you add one, it becomes an ordinary method (covered in OOP).
  4. Can a void method contain return? Yes, return; with no value, to exit early.
  5. What’s a covariant return type? An overriding method may return a subtype of the original return type. You’ll see this in the Inheritance section.

More practice: Java Interview Questions for Freshers · Intermediate Questions

Practice Exercises

  1. Easy: Write static boolean isEven(int n) using a single return.
  2. Easy: Write static double percentage(int obtained, int total) that returns a double (watch the division).
  3. Easy–Medium: Write static String grade(int marks) with an else-if ladder that compiles without a “missing return” error.
  4. Medium: Write static int countVowels(String text) and use its result in an if condition.
  5. Medium: Write record Stats(int min, int max, double average) and a method that returns it for an int[].

Practise on ExamAdda Practice and run your code in the ExamAdda Compiler.

FAQs

1. What is a return type in Java?
It’s the data type of the value a method sends back to its caller, written before the method name. If the method returns nothing, the return type is void.

2. Is a return statement required in a void method?
No. A void method ends automatically at its closing brace. You can still write return; to exit early.

3. How can a Java method return multiple values?
A method returns only one value, so return one object that holds several: a record (Java 16+), a class, or an array.

4. Why do I get “missing return statement” when all my conditions are covered?
The compiler checks structure, not logic. If the last branch is an else if, it assumes a path may fall through. Use a final else or add a return at the end.

5. Can a method return null in Java?
Yes, if its return type is a reference type such as String or an array. Primitive return types can’t be null. Callers must check before using the result.

6. What happens to code written after a return statement?
If it’s in the same block and the return always runs, the code is unreachable and the compiler reports “unreachable statement”.

7. Can I ignore the value returned by a method?
Yes, it compiles, but the value is lost. That’s a common bug with methods like toUpperCase() that return a new result instead of changing the original.

Article Summary

  • The return type declares what a method gives back; void means nothing.
  • return ends the method immediately and passes the value to the caller; a non-void method must return on every path.
  • Returned values follow assignment rules: widening is automatic, narrowing needs a cast, and the expression is evaluated before conversion.
  • A method returns one value; use arrays or records (Java 16+) for several, and check results that may be null.
  • Calculate in value-returning methods and print in void display methods.

Next → Method Overloading in Java · ← Previous: Method Parameters in Java

References: Oracle Java Tutorials: Returning a Value from a Method · JLS §14.17: The return Statement · JLS §8.4.7: Method Body