Java Reference
In-Depth Information
Sample Run: (In this sample run, the user input is shaded.)
Enter first name, last name, age, and weight separated by spaces.
Sheila Mann 23 120.5
Name: Sheila Mann
Age: 23
Weight: 120.5
The preceding program works as follows: The statements in Lines 1 to 4 declare the variables
firstName and lastName of type String , age of type int ,and weight of type double .
The statement in Line 5 is an output statement and tells the user what to do. (Such output
statements are called prompt lines.) As shown in the sample run, the input to the program is:
Sheila Mann 23 120.5
The statement in Line 6 reads and assigns the string Sheila to the variable firstName ;
the statement in Line 7 skips the space after Sheila and reads and assigns the string Mann
to the variable lastName . Next, the statement in Line 8 skips the blank after Mann and
reads and stores 23 into the variable age . Similarly, the statement in Line 9 skips the blank
after 23 and reads and stores 120.5 into the variable weight .
The statements in Lines 10, 11, and 12 produce the third, fourth, and fifth lines of the
sample run.
VARIABLE INITIALIZATION
Remember, there are two ways to initialize a variable: by using the assignment statement
and by using a read statement. Consider the following declaration:
int feet;
int inches;
Consider the following two sets of code:
(a) feet = 35;
inches = 6;
System.out.println("Total inches = " + (12 * feet + inches));
(b) System.out.print("Enter feet: ");
feet = console.nextInt();
System.out.println();
System.out.print("Enter inches: ");
inches = console.nextInt();
System.out.println();
System.out.print("Total inches = " + (12 * feet + inches));
In (a), feet and inches are initialized using assignment statements, and in (b), these
variables are initialized using input statements. However, each time the code in (a)
executes, feet and inches are initialized to the same value, unless you edit the source
code, change the value, recompile, and run. On the other hand, in (b), each time the
 
Search WWH ::




Custom Search