DEV Community

loading...
Cover image for The `else if` Keyword Doesn’t Exist in Java

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

renegadecoder94 profile image Jeremy Grifski Originally published at therenegadecoder.com on ・5 min read

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.

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

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.

Discussion (20)

pic
Editor guide
Collapse
donut87 profile image
Christian Baer

Maybe this counts as mind blowing as well. The elif if python does not work any differently than the else if in Java. The only valid reason for having this elif construct is the formatting. In Python you would have to use correct spacing when using else if

if grade >= 90:
  print("You got an A!")
else:
  if grade >= 80:
    print("You got a B!")
  else: 
    if grade >= 70:
      print("You got a C!")
    else:
      if grade >= 60:
        print("You got a D!");
      else:
        print("You got an F!");

There is no difference in program flow or even speed when you use an elif construct. The blocks are just arranged in a nicer way. Very much like, when in Java you are using

else if(x) {
  System.out.println("Stuff")
}

instead of

else {
  if(x) {
    System.out.println("Stuff")
  }
}

The solution in your case to get 'nicer looking' code without the usage of else so much is something like:

def get_letter_grade(grade):
  if grade < 60:
    return 'F'
  if grade < 70:
    return 'D'
  if grade < 80:
    return 'C'
  if grade < 90:
    return 'B'
  return 'A'

print("Your grade: {}".format(get_letter_grade(85)))

P.S. What is wrong with you Americans? Don't you care for the alphabet? What happened to 'E'?

Collapse
renegadecoder94 profile image
Jeremy Grifski Author • Edited

Maybe I was unclear, but the reason that this is so mind blowing to me is that else if isn’t a keyword. There is only elseand if. Python had to introduce a third keyword because else if isn’t valid syntax. In other words, else if comes for free in C-like languages due to the language grammar, and I had just assumed it was a special token.

Collapse
silwing profile image
Silwing

I was just wondering to myself why python would have a separate elif keyword. But of course it makes sense because of whitespace having meaning in python.
Thanks!

Collapse
donut87 profile image
Christian Baer

Quote from python documentation to back me up on this:

The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation.

Collapse
greenroommate profile image
Haris Secic

gave a heart just beacuse of P.S. :D

Collapse
moopet profile image
Ben Sinclair

I'd never before considered that anyone would have thought of "else if" as a single keyword. I've learnt stuff today though about Python (because it would need to be else: if and that ain't gonna work) and went away to look up something else that niggled.

PHP has "elseif" as an equivalent of "else if" and I'd never understood why they'd bother (except that PHP does a lot of crazy stuff). Turns out that it's for the "colon" syntax:

if ($foo):
  // Whee!
elseif ($bar):
  // This is valid
else if ($baz):
  // This isn't
else: if ($quokka):
  // Alright calm down
endif;
Collapse
renegadecoder94 profile image
Jeremy Grifski Author • Edited

Yeah, I suppose I just lumped the idea of else if as another keyword when writing branches. It never occurred to me that else and if were separate, and playing in languages like Python only reinforced that idea.

Granted, I'm sure it would have been more clear had Java not been my first language. I don't feel like you get to appreciate language syntax nowadays when languages are more tools than a form of art.

At any rate, interesting point about PHP! So, it has a mixed syntax (i.e. you can use else if with braces or elseif with a colon)?

Collapse
moopet profile image
Ben Sinclair • Edited

Yeah, it's mostly so you can use it in templates (since it was a templating language to begin with really):

<?php if ($foo): ?>
  <h1>Welcome to <?php echo $foo; ?></h1>
<?php else: ?>
  <h1>Welcome to something that isn't very foo</h1>
<?php endif; ?>

It's a big ugly, but it's better than this:

<?php if ($foo) { ?>
  <h1>Welcome to <?php echo $foo; ?></h1>
<?php } else { ?>
  <h1>Welcome to something that isn't very foo</h1>
<?php } ?>
Thread Thread
renegadecoder94 profile image
Jeremy Grifski Author

I can imagine that second syntax is a nightmare to debug. haha

Collapse
greenroommate profile image
Haris Secic

My first reaction: of course it doesn't exist there's a space between else and if. But then again second reaction was but hey Ruby does have elsif and what's the actual reason for it. Anyway not impressed by else if part that much (i didn't actually care about those) but something similar in C# I was disappointed is switch case which works a bit different than in Java because I used to propagate steps but it's kind of bad practice so... I'm not sure about what gets me happy or mindblown except for null handling operators like elvis ?: or null coalescing ?? or conditional member acces ?. It's good to have posts like these just to make you think about stuff you don't care/notice otherwise. Thanks

Collapse
renegadecoder94 profile image
Jeremy Grifski Author

I'm not sure that a space necessarily indicates separate keywords. It all depends on how the grammar is written. What's stopping a language grammar from containing else if as a terminal symbol?

Collapse
greenroommate profile image
Haris Secic

Nothing but my expectations are limited to that space. Even programming languages should think about UX. If you put else if as keyword with a space I wouldn't expect it to be 1 keyword but 2. But that's just my subjective view on that point.

Collapse
jillesvangurp profile image
Jilles van Gurp

How is this a problem? Code with lots of branches is a design smell; don't do that. Also, consider using the switch statement, which is getting more powerful with recent java releases. Or better, switch to Kotlin which has a nice when statement that is a bit more sane than switch or if else garbage.

Collapse
renegadecoder94 profile image
Jeremy Grifski Author

I don’t think I ever said it was a problem. I was acknowledging the fact that the Java grammar doesn’t contain an else if terminal symbol. Of course, the content was geared toward beginners (i.e. my students), so I chose not to dig into compilers. Instead, I shared an example they could easily understand.

Naturally, the example is purely for the sake of argument—not something you should put in production code. Of course, you’re welcome to lecture me on which tools I should be using.

Collapse
petarov profile image
Petar Petrov

Same as in good old C. To me it was strange back then when I first saw elif in Python. :-)

Collapse
lankydandev profile image
Dan Newton

😮😮 thanks for the post, I never thought about it like that either 👍👍

Collapse
renegadecoder94 profile image
Jeremy Grifski Author

Glad you liked it! It makes me wonder what other kinds of language-related things I’ve been missing.

Collapse
jorgecc profile image
Collapse
jackersjoeri profile image
Joeri_

The tweet mentions 'JS', not Java as far as I can tell?

Collapse
renegadecoder94 profile image
Jeremy Grifski Author

It does mention JS, but the syntax is the same in all c-like languages.