Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 2 ■ JAVA SYNTAX


} catch(IllegalArgumentException iae) {
System.out.println("Oops! can't use an empty array");
}

// add a test for the convenience method
System.out.println("AverageImpl.averageTwoNumbers(1, 2) = "
+ AverageImpl.averageTwoNumbers(1, 2));
}

private static String buildTestString(int[] values, float average, long time) {
// set up a timestamp for our tests
Date now = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String timeStamp = formatter.format(now);

StringBuffer sb = new StringBuffer(timeStamp);
sb.append(">Averaged {");
for (int i = 0; i < values.length; i++) {
sb.append(values[i]);
if (i < values.length - 1) {
sb.append(", ");
}
}
sb.append("} and got ");
sb.append(average);
sb.append(" in ");
sb.append(time);
sb.append(" nanoseconds");
return sb.toString();
}
}

Finally, the AverageTest class creates a program (you can tell because it has a main method, as we
saw in Chapter 1) that lets us test our Average interface and AverageImpl class. It tests all the methods in
the AverageImpl class and even creates an exception (that is, an error) so that we can see how that works.
It also creates a String object that we use as the message to the user to display our results.

Lines


Java files (classes and interfaces) consist of lines of code. Although that might seem obvious, it's actually
important. We measure code in lines (remember in the movie Jurassic Park where the programmer
played by Samuel L. Jackson says that there are two million lines of code and we are supposed to think
the program is complex?) and use lines to separate bits of code from other bits of code. Java has several
kinds of lines, including statements (such as i = 2;), declarations, and just plain old empty lines (which
are often handy for making a program easier to read). Java marks the end of statements with a particular
character, the semicolon (;). That matters because a long statement can be broken across multiple lines
in the file but can still be a single statement from Java's perspective. Sometimes, when you debug a bit of
Java code, that can be important. The examples in Listings 2-2 and 2-3 both have statements that have to
be split because of the width of the page.
To make your programming simpler and easier (and not drive other programmers crazy), keep your
lines (both statements and declarations) as short as possible. For historical reasons, 80 characters is
Free download pdf