1

This is a method from the book "Absolute Java." I don't understand why the last else statement needs a return value of 0. The author's comment is "Needed to keep the compiler happy". And is there a reason the return value is 0, or could it be any integer?

public int getMonth( )
{
    if (month.equals("January"))
        return 1;
    else if (month.equals("February"))
        return 2;
    else if (month.equalsIgnoreCase("March"))
        return 3;
    else if (month.equalsIgnoreCase("April"))
        return 4;
    else if (month.equalsIgnoreCase("May"))
        return 5;
    else if (month.equals("June"))
        return 6;
    else if (month.equalsIgnoreCase("July"))
        return 7;
    else if (month.equalsIgnoreCase("August"))
        return 8;
    else if (month.equalsIgnoreCase("September"))
        return 9;
    else if (month.equalsIgnoreCase("October"))
        return 10;
    else if (month.equals("November"))
        return 11;
    else if (month.equals("December"))
        return 12;
    else
    {
        System.out.println("Fatal Error");
        System.exit(0);
        return 0; //Needed to keep the compiler happy
    }
}
Sing Sandibar
  • 714
  • 4
  • 15
  • 26

3 Answers3

8

I'd argue that this is bad design on the programmer's part, but it's simple enough and gets the job done I suppose. Perhaps the book provides more context around this example? Maybe they use this to make a point about the language and not to actually solve a problem? Because this is a poor way to control the flow of logic in the application.

At runtime the application will end here:

System.exit(0);

But the compiler doesn't know that. The compiler sees this function returns an int and demands that all code paths return a value. Even if one of the code paths will, at runtime, exit the function in another way. So that last code path needs to return a value:

return 0;

It can be any integer, of course. The developer picked 0 because it's easy, but it's essentially arbitrary. At runtime that line won't be reached.

David
  • 208,112
  • 36
  • 198
  • 279
  • @bmorris591: Thanks :) I've heard of people using exceptions for control flow, but I've never heard of using application events for control flow. – David Mar 29 '13 at 23:01
3

If a method returns a value, the compiler tests every possible execution path to see whether a value is returned. If this is not the case, a compile-time error is raised.

It will not look into the methods that are called to see if it exits the application or something. From the compiler's point of view System.exit() is just a method call like any other. Without the return 0; statement the method would not return a value for that execution path, and that is illegal. Even if it would never get executed in practice.

Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157
0

better yet

    System.exit(0);
    throw new AssertionError("won't reach here");
ZhongYu
  • 19,446
  • 5
  • 33
  • 61