#what is a return statement

1 messages · Page 1 of 1 (latest)

devout hatchBOT
#

<@&987246399047479336> please have a look, thanks.

true patio
#

return is used for exiting a method.

when you call methods, you are entering a new area. when you leave the area, you are "returning" to the area you were at before

#

you are returning control of execution back to the caller

#

you may have to return with a value

nova narwhal
#

insteaf of articles this might also help to explain things

devout hatchBOT
#

MOOC is a completely free introductory Java course created by the University of Helsinki, it is a great way to learn Java from the ground up.

It consists of two parts, one at beginner, and another at intermediate level. The end of the course is marked by creating your own Asteroids game clone!

Even though the instructions show how to configure and use NetBeans for the course, you can use IntelliJ. To use IntelliJ, simply install the TMC plugin by opening IntelliJ -> File -> Settings -> Plugins and searching for TMC. You will then be able to use IntelliJ to complete MOOC.

Visit MOOC here: https://java-programming.mooc.fi/
(the course is available in both English and Finnish)

About the course - Java Programming

blazing pendant
#

but yeah return exit a method:

public void myMethod(final int value) {
  //manipulate the value
  if(value == 0)
    return
  //some other stuff
}

In this code for example, you can change the comment with wathever you want, and when it reaches the if block and the value is equal to 0 it calls return and exit the method, which goes back to the instruction that called myMethod. Otherwise it will continue it execution till the method block ends and then go back to the instruction that called it
Sometimes we need methods to return something, that something depends on the method type, so if you declare an int method, it has to return an int value, if you declare a String method it has to return a String and so goes on:

public String removePrefix(final String prefix, final String original)
  if (original.startsWith(prefix)) {
            return original.substring(prefix.length());
        }
        return original;

//somewhere else
String myString = "ABab";
String myStringWithoutPrefix = removePrefix("AB", myString);
devout hatchBOT
obsidian plume
#

You can write methods that return the result value so that you use it in your code
if you have a method that takes two ints a&b and sums them up and returns the sum it would look like this inside the method:
int sum = a +b;
return sum;

so now when you call this method, you have the value of sum and you can print it to the user or whatever you like!
they basically exit the block of code and sometimes exit while having some information with them that you can use!

true patio
#

similar to how classes extend Object without you having to specify it every type you create a class