I'm having trouble understanding what exactly the return statement does. What would be the difference in using:
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
int result = num*num*num;
System.out.println(result);
}
vs
public void run()
{
System.out.println(cube(5));
}
public int cube(int num)
{
return num*num*num;
}
Isn't it basically doing the same?
CodePudding user response:
In your first example, the square
function will print the cube of the provided number. However, if you wanted to do something more with it, like System.out.println(square(5) 3)
, printing would not give you back 125 (did you mean to call it cube?) to add to the 3, it would only say "125" in the console. The return
statement actually makes the function give back 125, so you can continue to work with it as a value.
Additionally, since you declared the square
function as returning an int
, if you do not have a return
statement, then the program will fail to compile.
CodePudding user response:
The return statement allows for more modular code with clear separation of concerns.
In your first example, your first System.out.println
in the run()
method calls another method that both calculates and then prints; therefore, the first System.out.println
doesn't print anything itself, and could be simplified to just
public void run() {
square(5);
}
public void square(int num) {
System.out.println(num * num);
}
Which is nice and concise, but let's say you don't want to System.out.println
every time you calculate a square, but only print if the result is divisible by 3. If you add the logic for that scenario to your square()
method, it starts to exceed its responsibility. Additionally, your square()
method is now only useful to that specific scenario. So the better practice would be something like this:
public void run() {
int result = square(5);
if (result % 3 == 0) {
System.out.println(result);
}
}
public int square(int num) {
return num * num;
}
Which now allows you to re-use the square()
method for other scenarios, rather than just printing squares divisible by 3.
Unrelated to the code itself, but your square()
method is actually calculating a cube (num*num*num) rather than a square (num*num)
CodePudding user response:
The difference would be whether or not you want to do something with the product of the function. If you just want to print the result, you're good to go. If you want to store that value into a variable to use later, you'd want to return it, and you could then call a System.out.println on that variable too. I would say fin nailed it in his response. Hope this helped!