One last rule is that String literals must start and end on the same line. If you have a long message, you can break it into two String literals. Then, concatenate the two literals. Defining Constants Some data values are known and do not change: number of inches in a foot, number of days in a week, ounces in a quart, and so on. Known values like these are called constants. A constant is a value that cannot and should not change during the execution of the program. To define a constant, use the keyword final in front of the definition. Here are some examples: final int DAYS_IN_WEEK = 7 final double CENTIMETERS_PER_INCH = 2.54 Notice that the Java naming convention for constants is different from other variables. All letters are capitalized, and words are separated by underscores. An advantage to defining constants is to avoid what are called “magic num- bers.” These are numbers that “magically” appear in a program and lead another programmer to ask, “Where did that number come from?” For example, 32 is a magic number in this statement: double totalOunces = quarts * 32 // 32 is a magic number Instead, it would be much clearer to define 32 as a constant: final int OUNCES_IN_QUART = 32 double totalOunces = quarts * OUNCES_IN_QUART Another advantage to defining a value as a constant is that Java will monitor the use of that variable. It will stop any attempt by the program to change the constant’s value after it has been assigned a value. HANDS-ON EXAMPLE 4.2.1 Defining Variables In this exercise, you will define variables and output their values. Before beginning this exercise, download the chapter files from the student companion website. The starter file VariableSnippet.java is used in this exercise. 1. Launch jGRASP, and open the VariableSnippet.java file. 2. Add your name to the header comment. 3. Examine the code. You will see five places where comments direct your activity. The work for comment 1 is completed for you. The variable doubleBurgerCalories has been defined and its value outputted in a sentence. /* VariableSnippet -- define variables of primitive types your name here */ public class VariableSnippet { public static void main( String [ ] args ) { /***** 1. Define a variable named doubleBurgerCalories that has the value 563 and output its value. */ int doubleBurgerCalories = 563 System.out.println( "The calories in a double hamburger are " + doubleBurgerCalories + "." ) (Continued) FYI Following the Java naming convention will help make your code look professional to other programmers. Copyright Goodheart-Willcox Co., Inc. Chapter 4 Variables 85
Previous Page Next Page