(^124) | Arithmetic Expressions
Code Formatting
As far as the compiler is concerned, Java statements are free format:They can appear anywhere on a
line, more than one can appear on a single line, and one statement can span several lines. The
compiler needs only blanks (or comments or new lines) to separate important symbols, and it needs
semicolons to terminate statements. Of course, it is extremely important that your code be readable,
both for your sake and for the sake of anyone else who has to examine it.
When you write an outline for an English paper, you follow certain rules of indentation to make it
readable. The same kinds of rules can make your code easier to read. In addition, it is much easier to
spot a mistake in a neatly formatted class than in a messy one. For these reasons, you should keep
your code neatly formatted while you are working on it. If you’ve gotten lazy and let your code become
messy while making a series of changes, take the time to straighten it up. Often the source of an error
becomes obvious during the process of formatting the code.
Take a look at the following application for computing the cost per square foot of a house. Although
it compiles and runs correctly, it does not conform to any formatting standards.
// HouseCost application This application computes the cost per square foot of
// living space for a house, given the dimensions of the house, the number
// of stories, the size of the nonliving space, and the total cost less land
public classHouseCost { public static voidmain(String[] arg){
final doubleWIDTH = 30.0; final doubleLENGTH = 40.0; //Length of the house
final doubleSTORIES = 2.5; //Number of full stories
final doubleNON_LIVING_SPACE = 825.0; //Garage, closets, etc.
final doublePRICE = 150000.0; //Selling price less land
doublegrossFootage; //Total square footage
doublelivingFootage; //Living area
doublecostPerFoot; //Cost/foot of living area
grossFootage = LENGTH * WIDTH * STORIES; //Compute gross footage
livingFootage = grossFootage–NON_LIVING_SPACE;//Compute net footage
costPerFoot = PRICE / livingFootage; //Compute cost per usable foot
System.out.println(“Cost per square foot is “+ costPerFoot);}}
If we call this method in the following assignment statement, which is within the same
class as the method declaration, then answeris assigned the value 5.0:
answer = hypotenuse(3.0, 4.0);
Working anywhere outside of the class that contains the method declaration, we need
to precede the method name with the class name in a call. Within the same class, we can
refer directly to our method. If we wanted it to be a helper method, we could use the private
modifier in place of public. In Chapters 6 and 7 we explore all of the different rules regard-
ing accessibility and the other modifiers that Java supports.