Here’s something interesting. In one of my courses we’re learning Java, and have had a few exercises in which we’re asked to write some small programs that do very basic things (generating arrays, ordering words, joining arrays, etc). One of the questions was to write a method that takes an array as input and prints it. It’s a fairly simple exercise but there are some small things that might be overlooked. Of course you’re going to use a for loop to do this, but you’ve got to be careful. If the array is empty, you don’t want to get an ArrayIndexOutOfBoundsException and you don’t want a comma printed after the last member of the array.
To answer the question, I wrote the following code:
public static void printArray(int[] args)
{
int len = args.length;
System.out.print("{");
if (len != 0)
{
for (int x = 0; x < (len-1); x++)
System.out.print(args[x] + ", ");
System.out.print(args[len-1]);
}
System.out.print("}");
}
The if statement accounts for empty strings, and the fact that I only use the for loop for all the elements except the last makes sure that it doesn’t print a comma after the last element.
The professor wrote a different piece of code, however:
public static void printArray(int[] array)
{
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i < array.length-1)
System.out.print(", ");
}
System.out.print("}");
}
His code also accounts for empty arrays, but instead of an if statement, it uses the for loop. Since variable i < array.length evaluates to false for an empty lists (whose array.length == 0), the for loop never executes. Also interesting is how he made sure that there is no trailing comma. He makes sure the index value is one less than the last element before printing a comma.
Of course, both answers are valid and have the same end result, but I really like his solution more. The for loop is clever and fairly obvious once you think about it, and the solution for the trailing comma problem is also pretty smart. One thing that I’m interested is to see if the if statement in the for loop affects execution time on very large arrays. My code only has one if statement which gets executed only once. The prof’s if statement gets executed at each iteration of the for loop.
Anyways, I just wanted to show two solutions to the same problem, and some interesting ways of thinking. I’ll look into benchmarking the two pieces of code on very large arrays just for fun. The results won’t mean anything on such a small problem, but it’d be interesting to see if an if statement inside a loop affects performance in any way.