Java Reference
In-Depth Information
7 radius = 20 ; // radius is now 20
8
9 // Compute area
10 area = radius * radius * 3.14159 ;
11
12 // Display results
13 System.out.println( "The area for the circle of radius " +
14 radius + " is " + area);
15 }
16 }
Compile
Run
F IGURE 2.1
The program displays the area of a circle.
Variables such as radius and area correspond to memory locations. Every variable has
a name, a type, a size, and a value. Line 3 declares that radius can store a double value.
The value is not defined until you assign a value. Line 7 assigns 20 into variable radius .
Similarly, line 4 declares variable area , and line 10 assigns a value into area . The following
table shows the value in the memory for area and radius as the program is executed. Each
row in the table shows the values of variables after the statement in the corresponding line in
the program is executed. This method of reviewing how a program works is called tracing a
program. Tracing programs are helpful for understanding how programs work, and they are
useful tools for finding errors in programs.
declare variable
assign value
tracing program
line#
radius
area
no value
3
no value
4
7
20
10
1256.636
The plus sign ( + ) has two meanings: one for addition and the other for concatenating (com-
bining) strings. The plus sign ( + ) in lines 13-14 is called a string concatenation operator. It
combines two strings into one. If a string is combined with a number, the number is converted
into a string and concatenated with the other string. Therefore, the plus signs ( + ) in lines
13-14 concatenate strings into a longer string, which is then displayed in the output. Strings
and string concatenation will be discussed further in Chapter 4.
concatenate strings
concatenate strings with
numbers
Caution
A string cannot cross lines in the source code. Thus, the following statement would
result in a compile error:
System.out.println( "Introduction to Java Programming,
by Y. Daniel Liang" );
To fix the error, break the string into separate substrings, and use the concatenation
operator ( + ) to combine them:
System.out.println( "Introduction to Java Programming, " +
"by Y. Daniel Liang" );
break a long string
 
 
Search WWH ::




Custom Search