Page 102 - Introduction to Programming with Java: A Problem Solving Approach
P. 102

                68 Chapter 3 Java Basics
For your first Java trace, we’ll make things easy. Rather than asking you to do a trace on your own, we
just ask you to study the completed trace in Figure 3.4. But please do study it. Make sure you understand
8
how all the column values get filled in.
 1 int salary;
2
String bonusMessage;
salary = 50000;
bonusMessage = "Bonus = $" + (.02 * salary);
System.out.println(bonusMessage);
3
4
5
6
 line#
 salary
 bonusMessage
 output
  1
 ?
   2
  ?
  4
 50000
   5
  Bonus = $1000
  6
   Bonus = $1000
  Figure 3.4 Calculating a bonus—code fragment and its associated trace Apago PDF Enhancer
3.12 Initialization Statements
A declaration statement specifies a data type for a particular variable. An assignment statement puts a value into a variable. An initialization statement is a combination of the declaration and assignment statements— it specifies a data type for a variable, and it puts a value into that variable.
The Java language is strongly typed, meaning that all variable types are fixed. Once a variable is de- clared, it cannot be redeclared. Therefore, you can have only one declaration statement for a particular vari- able. Likewise, since an initialization statement is a specialized form of a declaration statement, you can have only one initialization statement for a particular variable.
Here’s the syntax for an initialization statement:
<type> <variable> = <value>;
And here are some initialization examples:
String name = "John Doe"; // student's name
 int creditHours = 0;
// student's total credit hours
The name variable is declared to be a String type, and it’s given the initial value of “John Doe.” 9 The creditHours variable is declared to be an int and it’s given the initial value of 0.
8 If you run the code fragment on a computer, you’ll see a .0 at the end of the output (Bonus
when you learn about mixed expressions and promotion later in this chapter.
9John Doe is commonly used as a filler in the United States and Great Britain when a person’s real name is unknown. We use it here as a default value for a student’s name. It serves as an indication that the student’s real name has not yet been filled in.
 =
1000.0). The .0 should make sense






















































   100   101   102   103   104