impera Open Impera

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_VALUE to Integer.MAX_VALUE).
  • double: numbers with a decimal part, e.g. 3.14, -0.5, 2.0.
  • boolean: only true or false.

A primitive variable stores its value directly in its memory location.

Check yourself

Which type is best for storing whether a door is locked?

  • boolean

  • int

  • String

  • double

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?

  • A compile-time error

  • A run-time error

  • The value changes normally

  • The program ignores the line

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:

  • The object's characters directly

  • Always the value 0

  • The address of an object

  • A copy of every field

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:

  1. int big = Integer.MAX_VALUE; stores 2147483647.
  2. big + 1 evaluates 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?

  • 0

  • An exception is thrown

  • Integer.MAX_VALUE

  • Integer.MIN_VALUE

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_VALUE to Integer.MAX_VALUE). Stored in 32 bits.
  • double: numbers with a fractional part, stored approximately in 64 bits.
  • boolean: true or false.

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.
  • final makes 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);
  1. temp = 3.
  2. first = 8.
  3. second = 3.
  4. Output: 8 3. Without temp, both variables would end up as 8.

Worked example (spot the type): what is the value and type of 7 / 2 * 2.0?

  1. Left to right: 7 / 2 is int division: 3.
  2. 3 * 2.0 is 6.0.
  3. 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 = a links two primitives so that later changes to one affect the other.
  • Thinking q = p copies 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]?

  • 5

  • 4

  • The code does not compile

  • 0

Show the answer

0

b and a refer to the same array object.

6For top marks

  • Use the narrowest sensible type: an int for counts, not a double.
  • 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 int overflow happens silently.
Example

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?

  • double average = 7.5;

  • average double = 7.5;

  • int average = "7.5";

  • Double average := 7.5;

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