Defining Variables To define a variable, provide a data type and a name followed by a semico- lon. It is a good programming practice to choose names that clearly indicate what data will be stored in the variable. For example: int numberOfPets // an integer double price // a real number char letterQ // a single letter boolean isRaining // true or false From the names, you can deduce what data these variables will store. A rule of thumb is to define identifiers for the next programmer. Self-documenting identi- fiers make it easy for the next programmer to understand your code. Often, the next programmer is you. If you return to edit a program even a few days later, clear, meaningful identifiers will immediately remind you of what you were try- ing to accomplish. It is also possible to define multiple variables of the same data type by sepa- rating each name with a comma. For example: int numberOfBedrooms, numberOfBathrooms // 2 ints double itemPrice, salesTax, finalPrice // 3 doubles char letterX, letterY, letterZ, nine // 4 chars boolean isCloudy, isSnowing, isWinter // 3 booleans Notice a form of CamelCase is used in the names: the initial letter is lowercase and internal words are capitalized. The Java naming convention for variables is to start the name with a lowercase letter and capitalize any internal words. It is strongly recommended to follow this standard to improve the readability of the code. An advantage of following this practice is that with case-sensitive names, if you know the name of the variable, you will know which letters are capitalized and which letters are lowercase. FYI Choose identifiers that clearly describe the data to be held in that variable. HANDS-ON EXAMPLE 4.1.1 Naming Data and Identifying Data Types Suppose you want to paint your bedroom. You decide to write a program to calculate the square footage of the bedroom walls, the amount of paint you will need, and the total cost of the paint. Assuming that your bedroom is rectangular, this is the data needed for the program: height of the room in feet width of the room in feet length of the room in feet number of square feet one gallon of paint will cover number of gallons of paint needed price of a gallon of paint in dollars and cents total cost to paint the bedroom Copyright Goodheart-Willcox Co., Inc. 80 Introduction to Computer Science: Java Programming
Previous Page Next Page