7.1 Variables, Data Types, and Type Conversion
Key Takeaways
- The ETS pseudocode data types are boolean, char, double, float, int, int[ ], int[ ][ ], short, and String.
- Integer types store whole numbers exactly within a fixed range; floating-point types (float, double) store fractional values approximately.
- Integer division discards the fractional part (17 / 5 is 3), while floating-point division keeps it (17.0 / 5 is 3.4); the remainder operator % gives 17 % 5 = 2.
- Type conversion is needed when data arrive in the wrong type, such as text input "42" that must become the number 42, or integers that must be averaged as floating-point values.
- Converting a floating-point value to an integer typically truncates toward zero, so 87.85 becomes 87 and −4.8 becomes −4.
What this competency asks
ETS asks you to understand how to use variables and a variety of data types, including integers, floating point, strings, Booleans, and arrays or lists. Beyond tracing code, the listed skills include:
- Identify variables and data types, and the need for type conversion.
- Describe the difference between integer and floating-point numeric types, and between integer and floating-point division.
- Describe the benefits of each data type and identify the most appropriate type in a context.
- Distinguish global and local scope (Section 9.1) and sequence string operations (Section 7.2).
Variables
A variable is a named storage location whose value can change. In ETS pseudocode, a variable is declared with its type and usually given an initial value in the same line:
int count ← 0
double price ← 19.99
boolean done ← false
char grade ← 'A'
String name ← "Ada"
int[ ] scores ← {90, 85, 77}
Declaration tells the program the name and type. Initialization gives the first value. Assignment (←) replaces the stored value: in count ← count + 1, the right side is evaluated using the old value, and the result then overwrites count.
A constant is a named value that should not change, such as a tax rate or a maximum class size. Using named constants instead of repeated literal numbers makes code easier to read and change (Section 10.4).
The data types in ETS pseudocode
| Type | Holds | Typical size* | Good for |
|---|---|---|---|
boolean | true or false | — | Flags and conditions: isEnrolled, found |
char | One character | 16 bits (Java) | A letter grade, a single key press |
short | Small whole numbers | 16 bits (−32,768 to 32,767) | Memory-conscious small counts |
int | Whole numbers | 32 bits (about ±2.1 billion) | Counts, indexes, ages, quantities |
float | Approximate real numbers | 32 bits (about 7 significant digits) | Measurements where modest precision is enough |
double | Approximate real numbers | 64 bits (about 15–16 significant digits) | Averages, measurements, scientific values |
String | A sequence of characters | Varies | Names, messages, text input |
int[ ] | A list of int values | Varies | A set of scores |
int[ ][ ] | A grid of int values | Varies | Seating charts, game boards, images |
*Sizes shown are the Java conventions most textbooks use. The ETS notation table lists the types without sizes.
Choosing the most appropriate type
| Situation | Best type | Why |
|---|---|---|
| Number of students in a class | int | Whole number; exact |
| Average of several test scores | double | May have a fractional part |
| Whether homework was submitted | boolean | Only two states |
| A student's middle initial | char | One character |
| A student's full name | String | Many characters |
| Daily high temperatures for a month | double[ ] or int[ ] | Many values of the same type |
| Tic-tac-toe board | char[ ][ ] or int[ ][ ] | Rows and columns |
| Phone number or ZIP code | String | Not used in arithmetic; may begin with 0 |
A classic trap: a ZIP code such as 02134 looks numeric, but storing it as an int drops the leading zero, and you never add ZIP codes together. Identifiers such as these belong in a String.
Integer vs. floating-point types
Integer types (short, int) | Floating-point types (float, double) | |
|---|---|---|
| Values | Whole numbers only | Numbers with fractional parts, and very large or small magnitudes |
| Exactness | Exact within the range | Approximate: many decimals, such as 0.1, cannot be stored exactly |
| Main risk | Overflow past the maximum value | Round-off error; comparing with == is unreliable |
| Typical uses | Counting, indexing, looping | Measurements, averages, scientific calculations |
Because floating-point values are stored in binary, 0.1 + 0.2 is not exactly 0.3 in most languages. Compare floating-point results with a tolerance, such as abs ( a - b ) < 0.0001, instead of with ==. For money, many programs store whole cents in an integer type to avoid round-off.
Integer vs. floating-point division
| Expression | Result | Reason |
|---|---|---|
17 / 5 (both integers) | 3 | Integer division discards the fraction |
17 % 5 | 2 | Remainder: 17 = 5 × 3 + 2 |
17.0 / 5 | 3.4 | A floating-point operand gives floating-point division |
-7 / 2 (integers, Java) | −3 | Java truncates toward zero |
In ETS pseudocode, remember the rule from Section 1.2. The notation table says / is floating-point division unless stated otherwise, but ETS's sample explanations treat / between two int values as integer division. Read the declared types and the answer choices.
The average trap. In Java, if sum and count are both int, then double avg = sum / count; performs integer division before the result is stored. With sum = 17 and count = 4, avg is 4.0, not 4.25. Converting one operand first, as in (double) sum / count, gives 4.25.
When type conversion is needed
Type conversion changes a value from one type to another.
| Need | Example |
|---|---|
| Text input used as a number | The user types "42"; convert the String to an int before adding |
| A number shown as text | "Total: " + 42 produces the String "Total: 42" through concatenation |
| An accurate average of integers | Convert sum or count to double before dividing |
| Storing a real number as an integer | Convert 3.99 to an int (truncation gives 3) |
| Comparing a character with a code | 'A' has the numeric code 65 in ASCII and Unicode |
Widening conversions (such as int → double) happen automatically in most languages because the target can represent the value's range. Even so, very large integers can lose precision when converted to float. Narrowing conversions (such as double → int) usually require an explicit cast because information can be lost. When a floating-point value is cast to an integer, the fractional part is truncated toward zero: (int) 3.9 is 3 and (int) -4.8 is −4. It is not rounded.
How the types are stored
All types are ultimately bit patterns. Integers use two's complement binary, and floating-point numbers use the IEEE 754 format (sign, exponent, fraction). Characters are stored as numeric codes (ASCII or Unicode), and Booleans as a bit or a byte. Arrays store their elements in consecutive memory locations. Chapter 13 explains these representations in detail.
In Java, what is printed by the following code?
int sum = 17;
int count = 4;
double avg = sum / count;
System.out.println(avg);
A program must record, for each student, whether a permission slip has been returned. Which data type is most appropriate?
In Java, what value is stored in finalGrade?
double rawScore = 87.85;
int finalGrade = (int) rawScore + 5;