8️⃣

11.8 Return Types

When a method executes, it can do tasks. In addition to doing tasks, it can also give you back a value. This is called returning a value. For example, we could have a method called printSum() which takes 2 arguments and prints the sum of those two arguments:

public static void printSum(int a, int b) {
		System.out.println(a + b);
}

'

Notice that the printSum() method signature contains the keyword void, which tells you that the method does not return a value.

Alternatively, we can have a method called sum() which returns the result of adding the 2 numbers, which allows us more flexibility (because we might not always want to print the sum):

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

Notice that we use the keyword return to return a value.

Let’s look at how these two methods might be called:

public static void main(String[] args) {
		printSum(5, 4);
		int myNumber = sum(5, 4) / 2;
		System.out.println(myNumber);
}

Output of the code above:

9
4

Let’s break down the code and output. First, we called printSum() and passed the arguments 5 and 4. The  printSum() method prints the result of taking the first argument plus the second argument, so it printed 9.

Now let’s look at when the sum() method was called. The arguments passed into sum() are also 5 and 4. However, the sum() method returns the result of adding the two arguments. 5 + 4 = 9, so the method returns the value 9. The return value then takes the place of the method call (the highlighted code), and now we can use this value however we want.

In this case, we are taking the result of sum(5, 4) and dividing it by 2. Then we store this in a variable called myNumber, which is of type int. Since sum(5, 4) equals 9, myNumber is 9 / 2, which is 4 (because it is integer division).

Finally, the value of myNumber is printed to the console.

💡

Note: When you return something in a method, the execution of the function stops (any code after the return statement is skipped).

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.