Ryan Rampersad
Thoughts, opinions, ideas and now links
  • About
  • Podcast
  • Links

Archives

Java: syntax error on token “else”, delete this token

Before school ended, I donated some of my time to helping out the Intro to Java kids. In that class, I realized that when you tell beginning programmers “End each line with a semi-colon,” they think you really mean it. As in, every single line with actual code (e.g. not brackets) must end with a semi-colon. Well, it’s sad news but that is not true. Not every line needs a semi-colon.

Here’s an example. Look at this code. I dare you even to try running it. You’ll end up with an error.

public static void main(String[] args) {
	int magic = 10;
	if (magic < 20);
	{
		System.out.println("weak magic");
	} 
	else
	{
		System.out.println("strong magic");
	}
}	

The error is of course, uncommunicative of the true problem. Did you spot the error yet?

syntax error on token “else”, delete this token

The problem here isn’t the else or even the if. No, the problem is a semi-colon. Seriously. Take a look at the if-statement expression. The oddity comes about when you actually see the semi-colon attached to the end of it. And because the if-statement ended there, the else has no preceding pair so it has no choice but to error out.

This example is actually a clear cut case of putting a semi-colon after an if-statement expression. Imagine you didn’t have an error to remind you what you just did. You might just have a plain statement and proper following brackets.

public static void main(String[] args) {
	int magic = 10;
	if (magic < 20); {
		System.out.println("weak magic");
	}  
}

Without the else to throw an error message up, how easy would this be to spot? It’s tricky. What if your if-case was a rare edge case condition that you were hard pressed to demonstrate in testing but you theoretically knew it existed? You’d almost never know this wasn’t work until your nuclear reactor began to melt down.

The moral of story: kids will do what you tell them and mind you semi-colons at the end of constructs.

Upcoming PHP 5.4 Features – Arrays

The post tile was a little misleading. PHP.net has the full changeset for the PHP 5.4alpha.

Two remarkable language features coming in PHP 5.4.

Array dereferencing, or calling a function and acting upon it directly as if it were an array.

foo()[0]
$foo->bar()[0]

In addition, a new short syntax for creating arrays akin to the JavaScript array literal syntax.

$a = [1, 2, 3, 4];
$b = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
$c = ['one' => 1, 2, 'three' => 3, 4];

These two features will obviously make it impossible to be backwards compatible with older versions of PHP, but that’s really bad. Sadly, nobody on shared hosting will use this for a couple years.

© 2013 Ryan Rampersad.