Java Reference
In-Depth Information
don't care about the “change”; we only want to compute the 16 part. You might form
the following expression:
(int) 2.5 / 0.15
Unfortunately, this expression evaluates to the wrong answer because the cast is
applied to whatever comes right after it (here, the value 2.5 ). This casts 2.5 into the
integer 2 , divides by 0.15 , and evaluates to 13 and change, which isn't an integer and
isn't the right answer. Instead, you want to form this expression:
(int) (2.5 / 0.15)
This expression first performs the division to get 16 and change, and then casts
that value to an int by truncating it. It thus evaluates to the int value 16 , which is
the answer you're looking for.
2.2 Variables
Primitive data can be stored in the computer's memory in a variable.
Variable
A memory location with a name and a type that stores a value.
Think of the computer's memory as being like a giant spreadsheet that has many
cells where data can be stored. When you create a variable in Java, you are asking it
to set aside one of those cells for this new variable. Initially the cell will be empty,
but you will have the option to store a value in the cell. And as with a spreadsheet,
you will have the option to change the value in that cell later.
Java is a little more picky than a spreadsheet, though, in that it requires you to
tell it exactly what kind of data you are going to store in the cell. For example, if
you want to store an integer, you need to tell Java that you intend to use type int . If
you want to store a real value, you need to tell Java that you intend to use a double .
You also have to decide on a name to use when you want to refer to this memory
location. The normal rules of Java identifiers apply (the name must start with a letter,
which can be followed by any combination of letters and digits). The standard con-
vention in Java is to start variable names with a lowercase letter, as in number or
digits , and to capitalize any subsequent words, as in numberOfDigits.
To explore the basic use of variables, let's examine a program that computes an
individual's body mass index (BMI). Health professionals use this number to advise
people about whether or not they are overweight. Given an individual's height and
weight, we can compute that person's BMI. A simple BMI program, then, would
naturally have three variables for these three pieces of information. There are several
details that we need to discuss about variables, but it can be helpful to look at a complete
 
 
Search WWH ::




Custom Search