DEV Community

Discussion on: The `else if` Keyword Doesn’t Exist in Java

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 • 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

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