AP Computer Science A · Using objects and methods
Variables and data types
1Variables and primitive types
A variable is a named storage location that holds a value. In Java every variable has a type, declared before it is used:
int age = 16;
double price = 4.99;
boolean passed = true;
The three primitive types in AP Computer Science A:
int: whole numbers, e.g.-3,0,250. Stored in 32 bits, range about −2.1 billion to 2.1 billion (Integer.MIN_VALUEtoInteger.MAX_VALUE).double: numbers with a decimal part, e.g.3.14,-0.5,2.0.boolean: onlytrueorfalse.
A primitive variable stores its value directly in its memory location.
Check yourself
Which type is best for storing whether a door is locked?
Show the answer
boolean
Only two possible values.
2Declaring, initialising and naming
- Declaration:
int score;creates the variable. - Initialisation: giving it a first value,
score = 0;(or both at once:int score = 0;). - Using a local variable before it has a value is a compile-time error.
Naming rules: names start with a letter (or _ or $), contain no spaces, and are case-sensitive (total and Total differ). Java convention is camelCase: highScore, numStudents.
The keyword final makes a constant that cannot be changed after it is set:
final double TAX_RATE = 0.08;
Constants are written in capital letters with underscores by convention.
Check yourself
What happens if code tries to change a final variable after it is set?
Show the answer
A compile-time error
final values cannot be reassigned.
3Reference types and memory
Types other than primitives are reference types, such as String and any class you write. A reference variable stores the address of an object, not the object itself.
String name = "Ada";
int count = 3;
count holds 3 directly; name holds a reference (an arrow) to a String object somewhere in memory. A reference variable that points to no object holds null.
A primitive variable holds its value; a reference variable holds an arrow to an object
Check yourself
A variable of a reference type stores:
Show the answer
The address of an object
It refers to the object.
4Integer overflow and choosing types
If an int calculation goes past Integer.MAX_VALUE, it overflows and wraps around to a large negative number, with no error message.
Worked example:
int big = Integer.MAX_VALUE;stores 2147483647.big + 1evaluates to −2147483648.
Choose types by meaning: count of people → int; average mark → double; is the shop open → boolean.
Check yourself
What is the value of Integer.MAX_VALUE + 1?
Show the answer
Integer.MIN_VALUE
It wraps around.
5Going deeper: what a variable really holds, limits of each type, and tracing
Three primitive types to know
- int: whole numbers from −2,147,483,648 to 2,147,483,647 (
Integer.MIN_VALUEtoInteger.MAX_VALUE). Stored in 32 bits. - double: numbers with a fractional part, stored approximately in 64 bits.
- boolean:
trueorfalse.
Everything else (String, arrays, objects you create) is a reference type.
Primitive variables hold the value itself. Assigning one to another copies the value.
int a = 5;
int b = a;
b = 9;
System.out.println(a); // 5
Reference variables hold the location of an object. Assigning one to another copies the location, so both names refer to the same object. They are aliases.
int[] p = {1, 2, 3};
int[] q = p;
q[0] = 99;
System.out.println(p[0]); // 99
Integer overflow: when a calculation passes the largest int, the value wraps around to the negative end. No error is reported.
int big = Integer.MAX_VALUE;
big = big + 1;
System.out.println(big); // -2147483648
Doubles are approximate. Many decimals have no exact binary form, so 0.1 + 0.2 gives 0.30000000000000004. Never test doubles with ==; check that they are close:
boolean same = Math.abs(d1 - d2) < 0.000001;
Declaring and initializing
- A local variable must be given a value before it is used, or the code will not compile.
finalmakes a constant:final double TAX_RATE = 0.07;. Assigning to it again is a compile-time error. Constants are named in capitals.- Choose int for things you count, double for things you measure, boolean for yes or no.
Type rules in assignment
- An int can be stored in a double automatically (widening):
double d = 7;gives 7.0. - A double cannot be stored in an int without a cast:
int n = 7.9;does not compile;int n = (int) 7.9;gives 7 (the fraction is truncated, not rounded).
Wrapper classes: Integer and Double are objects that hold a primitive value, needed because an ArrayList can hold only objects. Java converts automatically: autoboxing (int to Integer) and unboxing (Integer to int).
Worked example (tracing a swap): what is printed?
int first = 3;
int second = 8;
int temp = first;
first = second;
second = temp;
System.out.println(first + " " + second);
- temp = 3.
- first = 8.
- second = 3.
- Output:
8 3. Withouttemp, both variables would end up as 8.
Worked example (spot the type): what is the value and type of 7 / 2 * 2.0?
- Left to right:
7 / 2is int division: 3. 3 * 2.0is 6.0.- A double, 6.0 (not 7.0).
Tracing technique: draw a table with a column for each variable and a new row every time a value changes. For references, draw an arrow from the variable to a box for the object; two arrows to one box shows an alias.
Common mistakes
- Expecting a cast to round.
- Thinking
b = alinks two primitives so that later changes to one affect the other. - Thinking
q = pcopies an array. - Comparing doubles with
==. - Forgetting that int arithmetic can overflow silently.
- Using a local variable before assigning it.
Check yourself
After int[] a = {4, 5}; int[] b = a; b[1] = 0; what is a[1]?
Show the answer
0
b and a refer to the same array object.
6For top marks
- Use the narrowest sensible type: an
intfor counts, not adouble. - Remember that primitive variables hold values but reference variables hold addresses: this matters when comparing and copying.
- Declare a variable once; after that use only its name.
- Know that
intoverflow happens silently.
a free-response method that counts items should declare int count = 0; before the loop, not inside it.
Check yourself
Which declaration is correct Java?
Show the answer
double average = 7.5;
Type, name, value.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera