CodeGym /Courses /JAVA 25 SELF /Return values, return

Return values, return

JAVA 25 SELF
Level 8 , Lesson 3
Available

1. Introduction

Let’s start with a question: why should a method return anything at all? Why not just do everything inside the method and print the result to the screen?

The point is that we often need not just to perform some action, but to get a result that will be useful elsewhere in the program. For example:

  • A method computes the sum of two numbers and returns it so we can use the result for further calculations.
  • A method determines whether a number is even and returns true or false so we can make a decision.
  • A method returns a greeting string for a user, and we decide where to send it—print it on the screen, write it to a file, or send it over the network.

If methods always just printed results, our program would be rigidly tied to a single scenario, and reusing logic would be hard. A return value makes methods flexible and reusable.

Analogy

Imagine a coffee machine. You insert money, press a button—and get coffee. If the machine just loudly said “Coffee is brewed!” (but didn’t give you coffee), you wouldn’t be happy. Same with methods: sometimes you don’t want to just hear “Done!”, you want to get the result.

2. Return type: what a method can return

In Java, when you declare a method, you specify a return type—it can be any type: int, double, String, boolean, an array, even an object of your own class. If a method returns nothing, you write void.

Syntax:

return_value_type methodName(parameters)
{
    // method body
}
Method signature

Examples:

int sum(int a, int b) 
{
    // returns int
}

String getGreeting(String name) 
{
    // returns String
}

boolean isEven(int number) 
{
    // returns boolean
}

void printHello() 
{
    // doesn't return anything - just performs an action
}

Important! The return type is the method’s “promise”: it must return a value of this type. If you promised to return an int but return a String, the compiler will complain and won’t let the program compile.

3. The return statement: how to return a value from a method

To actually hand the result of a method “outside,” use the return statement. This word says: “Here, take the result—and my job is done.”

int sum(int a, int b) 
{
    int result = a + b;
    return result; // return the result
}
Returning a value with return

It can be shorter:

int sum(int a, int b) 
{
    return a + b;
}

When a method reaches the return line, it finishes execution, returns the specified value, and passes it back to the call site.

Important: the type of the value after return must match the method’s declared return type.

4. Using the return value: what to do with it?

When a method returns a value, you can:

  • Store it in a variable.
  • Use it directly in an expression.
  • Pass it to another method.
int result = sum(5, 7); // store in a variable
System.out.println(result); // print the result

System.out.println(sum(10, 20)); // print the result immediately

if (isEven(42)) 
{
    System.out.println("The number is even!");
}

Example: a method that returns a string

String getGreeting(String name) 
{
    return "Hello, " + name + "!";
}

// Usage:
String greeting = getGreeting("Alice");
System.out.println(greeting); // Hello, Alice!

5. Practice: examples of methods with a return value

Method that returns the maximum of two numbers

int max(int a, int b) 
{
    if (a > b) 
    {
        return a;
    } 
    else 
    {
        return b;
    }
}

Even shorter if you already know the ternary operator:

int max(int a, int b) 
{
    return (a > b) ? a : b;
}

Usage:

int maximum = max(10, 25);
System.out.println("Maximum: " + maximum); // Maximum: 25

Method that returns true if a number is even

boolean isEven(int number) 
{
    return number % 2 == 0;
}

Usage:

if (isEven(18)) 
{
    System.out.println("The number is even!");
} 
else 
{
    System.out.println("The number is odd!");
}

Method that returns the sum of array elements

int sumArray(int[] arr) 
{
    int sum = 0;
    for (int i = 0; i < arr.length; i++) 
    {
        sum += arr[i];
    }
    return sum;
}

Usage:

int[] grades = {5, 4, 3, 5, 4};
int total = sumArray(grades);
System.out.println("Sum of grades: " + total);

6. What happens when calling a method with return

When you call a method that returns a value, program execution “enters” the method, runs its code, reaches return, returns the value, and substitutes it at the call site.

Schematically:

int a = 2;
int b = 3;
int c = sum(a, b); // sum(2, 3) is called here; 5 is returned; c becomes 5

Flowchart

        graph TD
        A["main"] --> B["sum(a, b)"]
        B --> C[calculations]
        C --> D[return result]
        D -->|result is returned| A
    

7. Useful details

return ends method execution

As soon as a return is encountered inside a method, the method’s execution stops immediately. Anything after it does not run.

int test()
{
    return 42;
    System.out.println("This will not be printed"); // unreachable
}

return in a void method

In a void method (which returns nothing) you can use return without a value—just to terminate the method early under some condition.

void printPositive(int number)
{
    if (number <= 0) 
    {
        System.out.println("The number is not positive!");
        return; // just exit the method
    }
    System.out.println("Number: " + number);
}

8. Common mistakes when working with return

Error No. 1: Not all code paths return a value

int getSign(int number)
{
    if (number > 0) 
    {
        return 1;
    }
    // And what if number <= 0? No return!
}
// Error: not all branches return a value

How to fix it: always ensure a return on every execution path.

int getSign(int number)
{
    if (number > 0) 
    {
        return 1;
    } 
    else if (number < 0) 
    {
        return -1;
    } 
    else 
    {
        return 0;
    }
}

Error No. 2: Return type mismatch

int getNumber()
{
    return "42"; // Error! Expected int, not String
}

Error No. 3: return after return

int test()
{
    return 5;
    System.out.println("This will not execute"); // unreachable statement
}

Error No. 4: return with an expression in a void method

void printSomething()
{
    return 42; // Error! A void method cannot return a value
}

Error No. 5: Ignoring the return value

sum(10, 20); // and that's it? The result is lost!

If you don’t use the return value, it simply gets lost. Don’t forget to save it or pass it further along in the code!

Error No. 6: Expecting return to print something

int result = sum(2, 3);
// return doesn’t print anything!
// You need to print explicitly:
System.out.println(result);
1
Task
JAVA 25 SELF, level 8, lesson 3
Locked
Smart assistant for personalized greetings 🤖
Smart assistant for personalized greetings 🤖
1
Task
JAVA 25 SELF, level 8, lesson 3
Locked
Parity Detector for a Game Quiz ❓
Parity Detector for a Game Quiz ❓
1
Task
JAVA 25 SELF, level 8, lesson 3
Locked
Determining the Winner by Score 🏆
Determining the Winner by Score 🏆
1
Task
JAVA 25 SELF, level 8, lesson 3
Locked
Calculating the student's total score across all tests 📚
Calculating the student's total score across all tests 📚
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Sid Level 21, United States of America, United States
11 March 2026
there should have been more challenging way of testing the methods parameter and return type knowledge which includes One / 2 or 3 Dimensional Arrays.