-3

I am implementing stack in java. While doing this I saw a code where a function returns -1. Like this one:

public int peek()
    {
        if (!isEmpty())
            return arr[top];
        else
            System.exit(1);

        return -1;
    } 

What does it actually mean returning a -1 value?

  • 3
    that -1 will never be returned – Alberto Sinigaglia Aug 16 '20 at 11:41
  • What does it mean actually? – develop_code Aug 16 '20 at 11:42
  • 3
    It means that if this line were reached, a `-1` would be returned. To make a statement about the semantics, we would have to see more code. If I were to guess, I would say that it is either some value to satisfy the compiler or was meant as a flag-/error-code value to signal that the operation could not be executed. An in my opinion cleaner solution would be to throw an `Exception` (e.g. `IllegalStateException`), hence referring the handling of this situation to the calling side. – Turing85 Aug 16 '20 at 11:45
  • 2
    _Why_ is there a `System.exit` call inside a `peek` method??? – Slaw Aug 16 '20 at 11:46
  • 2
    It's a terrible example. The whole JVM is stopped if the collection is empty. In this case -1 has no meaning, as it will never be returned. It's only there because the compiler will complain that the method must return a value in all cases. – RealSkeptic Aug 16 '20 at 11:46
  • So the return value could be anything @RealSkeptic – develop_code Aug 16 '20 at 11:50

1 Answers1

3
System.exit(1);

Ends the JVM and returns the exit status 1 to the OS.

You know, return -1; will never be executed, but the compiler has to enforce, that EVERY method, that says in the signature, that it returns something, has either a return-statement or a throw at every end of the control flow.

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29