bachshwa bachshwa - 1 year ago 62
Java Question

How does return key code differs from return from a "simple" function?

public class Factorial {
static public int factorial(int x) {
if (x == 0) return 1;
return factorial(x - 1) * x;

public static void main(String[] args) {
int result = factorial(4);

When i return 1 in case of 9, it simply returns a result of my factorial.
When i return -1, it returns a negative result.
If i return 2 or 3, it just multiplies my result by 2, 3 and so on, respectively.
I thought that when i return 1, it means that something went wrong, and it does not affect to my other returns.
I need to understand that, because i feel like it's an important moment in my learning path.

Answer Source

You are probably talking about returning key codes to your OS like EXIT_FAILURE or EXIT_SUCCESS which works differently from what you have described, and in java you would do this: System.exit(code);

In C/C++ you can return either EXIT_FAILURE or EXIT_SUCCESS from your main function to, for example, clarify your program's behavior:

if(true) return EXIT_SUCCESS;
else return EXIT_FAILURE;

Speaking of your recursive factorial:

You've got 1 as a base condition so when it gets to that point, your program returns 1, then it gets assigned to a variable result and gets displayed eventually.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download