Java Reference
In-Depth Information
LISTING 2.6
//********************************************************************
// Geometry.java Author: Lewis/Loftus
//
// Demonstrates the use of an assignment statement to change the
// value stored in a variable.
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println ("A heptagon has " + sides + " sides.");
sides = 10; // assignment statement
System.out.println ("A decagon has " + sides + " sides.");
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
OUTPUT
A heptagon has 7 sides.
A decagon has 10 sides.
A dodecagon has 12 sides.
A variable can store only one value of its declared type. A new
value overwrites the old one. In this case, when the value 10 is
assigned to sides , the original value 7 is overwritten and lost for-
ever, as follows:
KEY CONCEPT
Accessing data leaves it intact in
memory, but an assignment state-
ment overwrites the old data.
After initialization:
sides
7
After irst assignment:
sides
10
Search WWH ::




Custom Search