Page 99 - Introduction to Programming with Java: A Problem Solving Approach
P. 99
3.10 Variables 65 40 songs. Even though sngs might work, you should rename it to something like printTop40Songs to
improve your program’s readability.
3.10 Variables
To this point, our programs haven’t done a whole lot; they’ve just printed a message. If you want to do more than that, you’ll need to be able to store values in variables. A Java variable can hold only one type of value. For example, an integer variable can hold only integers and a string variable can hold only strings.
Variable Declarations
How does the computer know which type of data a particular variable can hold? Before a variable is used, its type must be declared in a declaration statement.
Declaration statement syntax:
<type> <list-of-variables-separated-by-commas>; Example declarations:
int row, col;
String firstName;
String lastName;
// student's first name
// student's last name
int studentId; Apago PDF Enhancer
In each declaration statement, the word at the left specifies the type for the variable or variables at the right. For example, in the first declaration statement, int is the type for the row and col variables. Having an int type means that the row and col variables can hold only integers (int stands for integer). In the sec- ond declaration statement, String is the type for the firstName variable. Having a String type means that the firstName variable can hold only strings.
Have you noticed that we sometimes spell string with an uppercase S and we sometimes spell it with a lowercase s? When we use “string” in the general sense, to refer to a sequence of characters, we use a lower- case s. In Java, String is a data type that happens to be a class name also. As you now know, coding conven- tions dictate that class names begin with an uppercase letter. Thus, the String class/data type begins with an uppercase S. So when we refer to String as a data type, in code and in conversational text, we use an uppercase S.
When you declare a variable(s), don’t forget to put a semicolon at the end of the declaration statement. When you declare more than one variable with one declaration statement, don’t forget to separate the vari- ables with commas.
Style Issues
The compiler will accept a variable declaration anywhere in a block of code, as long as it’s above where the variable is used. However, in the interest of readability, you should normally put your declarations at the top of the main method. That makes them easy to find.
Although it may waste some space, we recommend that you normally declare only one variable per declaration statement. That way, you’ll be able to provide a comment for each variable (and you should nor- mally provide a comment for each variable).