Page 100 - Introduction to Programming with Java: A Problem Solving Approach
P. 100
66 Chapter 3 Java Basics
We do make exceptions to these recommendations. Note how these row and col variables are declared
together with one declaration statement:
int row, col;
That’s acceptable because they are intimately related. Note that the row and col variables are declared without a comment. That’s acceptable because row and col are standard names that all programmers should understand. It would be overkill to include a comment like this:
int row, col;
// row and col hold row and column index numbers
Note how this studentId variable is declared without a comment: int studentId;
That’s acceptable because the studentId name is so completely descriptive that everyone should be able to understand it. It would be overkill to include a comment like this:
String studentId; // a student's ID value
Variable names are identifiers. Thus, when you name your variables, you should follow the identifier rules covered earlier. The studentId variable is well named—it uses all lowercase letters except for the first letter in its second word, Id.
One final recommendation for your variable declarations: Try to align your comments such that they all begin in the same column. For example, note how the //’s are in the same column:
String lastName;
String firstName;
Apago PDF Enhancer
// student's first name
// student's last name
3.11 Assignment Statements
You now know how to declare a variable in Java. After declaring a variable, you’ll want to use it, and the first step in using a variable is to put a value inside of it. We’ll now consider the assignment statement, which allows you to assign/put a value into a variable.
Java Assignment Statements
Java uses the single equal sign (=) for assignment statements. See Figure 3.3’s BonusCalculator program. In
particular, note the salary
the value 50000 into the variable salary.
=
50000; line. That’s an example of a Java assignment statement. It assigns
In the BonusCalculator program, note the blank line below the declaration statements. In accordance with the principles of good style, you should insert blank lines between logical chunks of code. A group of declaration statements is usually considered to be a logical chunk of code, so you should normally insert a blank line below your bottom declaration statement.
Let’s analyze the code fragment’s bonusMessage assignment statement. Note the * operator. The * operator performs multiplication. Note the + operator. If a + operator appears between a string and some- thing else (e.g., a number or another string), then the + operator performs string concatenation. That means that the JVM appends the item at the right of the + to the item at the left of the +, forming a new string. In
our example, the mathematical expression, .02
The JVM then appends the result, 100000, to “Bonus $”, forming the new string “Bonus $100000”.
*
salary, is evaluated first since it’s inside parentheses.