The `else if` Keyword Doesn’t Exist in Java

The `Else If` Keyword Doesn’t Exist in Java Featured Image

Last Updated on

Listen, I know this is going to seem crazy to some of you, but the else if keyword doesn’t exist in Java. Yeah, I was today years old when I learned that too.

Table of Contents

The Beauty of Social Media

If you know me at all, you know I hate social media. After all, I don’t have a Facebook or an Instagram, and I try to stay away from all the chat apps. Don’t ask me to join your Slack, GroupMe, WeChat, Messenger, or WhatsApp groups. I don’t need any other ways for people to contact me when I’m trying to binge anime.

That said, I do use Twitter quite heavily. Most of the time I use it to read up on hockey or stay up to date on politics. However, due to the sheer volume of content I consume through Twitter on a daily basis, I do occasionally stumble upon a gold nugget or two.

Well, recently, I saw a tweet by Mathias Bynens which read:

In JS, there’s `if` and `else`, but there’s no special `else if` construct. It might look like there is, since `else if` works…
…but it’s just an `if` nested within an `else` block without braces.
else if (x) {} → else { if (x) {} }
The more you know

Mathias Bynens, 31 Jan 2019

This tweet blew my mind because the if/else if/else syntax was something so ingrained in me that I never questioned it. Oddly enough, I had just taught branching to my own Java class, and I happily explained else if as if it were its own keyword. Well, I suppose this article goes out to them.

Proper Branching in Java

As an instructor, I often teach branching in two stages: basic branching then nested branching. Who would have thought that they were both the same thing? Not convinced? Let’s take a look at a grading example:

Scanner in = new Scanner(System.in);
int grade = Integer.parseInt(in.nextLine());

if (grade >= 90) {
  System.out.println("You got an A!");
} else if (grade >= 80) {
  System.out.println("You got a B!");
} else if (grade >= 70) {
  System.out.println("You got a C!");
} else if (grade >= 60) {
  System.out.println("You got a D!");
} else {
  System.out.println("You got an F!");
}

In this simple example, we ask the user for a number which we assume is valid. Then, we test that number against five cases, so we can print the appropriate message.

Of course, we should probably look at an example, so let’s say a user enters a value of 75. At first, we’ll fail because 75 is not greater than or equal to 90. As a result, we drop down to the next case which checks to see if 75 is greater than or equal to 80. Once again, the test fails, so we drop down to the next case where we finally pass. At that point, we print a message and exit to the top level.

If you’re like me, nothing really surprises you about this implementation. When we want conditions that depend on each other, we create an if case, an else case, and as many else if cases as we need.

There Can Be Only Two Keywords

But, what if I told you that the else if keyword doesn’t actually exist in Java? I know this directly contradicts what I’ve said before, but it’s true. All we’re missing in the code above is braces:

Scanner in = new Scanner(System.in);
int grade = Integer.parseInt(in.nextLine());

if (grade >= 90) {
  System.out.println("You got an A!");
} else {
  if (grade >= 80) {
    System.out.println("You got a B!");
  } else {
    if (grade >= 70) {
      System.out.println("You got a C!");
    } else {
      if (grade >= 60) {
        System.out.println("You got a D!");
      } else {
        System.out.println("You got an F!");
      }
    }
  }
}

Instead of a flat series of if statements, we now have a cascading set of if and else statements. Now, we can see the dependent relationship that each if statement has on the next one.

That said, it may be helpful to look at an example, so let’s say for the sake of argument that a user enters 75. As expected, the first test case will fail because 75 is not greater than or equal to 90. As a result, we fall into the else case we’re we test to see if 75 is greater than or equal to 80. It’s not, so we once again fall into the else statement. At this point, we satisfy the if statement, print our message, and exit to the top level.

As we can see, both solutions operate identically, and that shouldn’t be too surprising. After all, they’re equivalent solutions.

For the People in the Back

When I first published this piece, I got a lot of weird pushback from folks who seemed to misunderstand the point of this article, so I’ll say it again for the people in the back: this article is a commentary on the Java grammar, and it’s target audience is beginners.

Please try to avoid the temptation to lecture me on the following topics:

  • Keywords can or cannot have spaces
  • Branching is or is not bad (i.e. your preferred control flow structure)
  • The else if keyword does or does not exist in other languages
  • The relevance of other C-like languages (i.e. JavaScript, C, C#, C++, etc.)

Also, please try to avoid personal attacks. I know it’s hard, but you have to control yourself. Don’t bother reading my content if it bothers you so much.

Mind Blown

At any rate, if you’re like me, the idea of else if not being a separate keyword probably bothers you a lot. After all, this is one of those things that would make its way onto the Today I Learned subreddit. It just amazes me that I’ve gone through almost five years of education and two years of industry without realizing this fact.

To be honest though, the idea is so ubiquitous that some languages do have extra control flow keywords. For instance, Python has the elif keyword. Meanwhile, Ruby has the elsif keyword. And, I wouldn’t be surprised if other languages followed the same convention.

That said, what are you going to do with your new knowledge? Are you mindblown like me? Let me know in the comments below! And, thanks for stopping by.

Series Navigation← Be Careful with String’s Substring Method in JavaRock Paper Scissors Using Modular Arithmetic →
Advertisements

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.