The Basic Structure of Java Code

5.4 The Basic Structure of Java Code

Let's get a general feel for how to read Java code. A generic line of Java is a statement terminated by a semi-colon. The structure is free-flowing, unlike FORTRAN. This means that the line of code
            x= x - f(x)/df(x);
could be written in the file just as easily
            x =     x
                - f(x)
Of course, the first version is easier to read, but this illistrates the freedom you have to format your code in a way that is convenient for you. Unlike the siliness in FORTRAN, there are no restrictions to putting characters in the first 5 columns. With the freedom to format your code as you like comes the burden of making it readable to other people. You should look to see how other people format their code, find a style that you like, and be consistant in your style.

You can also group lines of Java code together using curly braces, { and } to delimit a section. You will see this, for example, in loops where the code executed during each loop is grouped together with curly braces. In our Newton's method code, the main loop calculates our new guess for x and then prints out some information for this iteration. The body of the loop looks like:

            x= x - f(x)/df(x);
	    System.out.println("Step: " + count + " x:" + x +
                               " Value:" + f(x));
Notice that there is no need for a semi-colon after the closing brace.

There are two ways to add comments to Java code - one for short comments and one for long. Early in our code, we have some descriptions of what some variables mean, for example:

double tolerance = .000000001; // Our approximation of zero
The marker // means that everything after it on the line is a comment. The Java code starts again on the next line. This is also a useful way to comment out single lines of code when you are changing a program.

The comment style for long comments is like the comment in our code that describes how we take our initial value:

/* If no command line guess is given, we take 0 as
   our starting point */
The comment starts with /* and ends with */. This sort of comment is also useful for commenting out large chunks of code.
Next 5.5 Introduction to Classes

David Maxwell, who is still writing this, would like to hear your comments and suggestions.