Skip to main content
Logo image

Section 2.1 Values and variables

Computers operate on data which is stored as bits, usually described as β€œzeros and ones”, in the computer’s memory. Though even that’s a bit of a fairy tale: in the computer each bit is actually represented by the state of a tiny electrical circuit.
However sequences of zeros and onesβ€”let alone microscopic circuitryβ€”aren’t convenient for humans to deal with, so programming languages like Java give us higher-level abstractions for dealing with data that let us treat those sequences of bits as values that have some meaning to us humans. The kinds of values, called data types, supported by a programming language and what we can do with them are the most basic building blocks of our programs
In a program the bit of code that produce values are called expressions. Every expression evaluates to a value. In this section we’ll deal with two of the most basic kinds of expressions. First, literal values are the way we write specific values in our program, that will be turned into the appropriate bits in memory when the program runs. These are things like 123 and 3.14. Second, we can create names in our program, called variables that represent a place in the computer’s memory where a value can be stored which we can then refer to by the variable’s name. In a later unit we’ll talk about expressions that use operators that cause the computer to perform computations using existing values to produce new values.

Subsection 2.1.1 Data types

In Java, every value has a data type that determines how it is represented in the computer’s memory (which mostly we don’t have to worry about) and what we can do with it. There are two categories of data types in Java. One, primitive types, hold the kinds of values that the computer can directly operate on such as numbers which we can do math with and logical values that we can do, well, logic with. The other, reference types hold a reference to a more complex value called an object. For now we’ll focus on three of the main primitive data types in Java. We’ll come back to reference types in ChapterΒ 8Β Classes.
The primitive types you need to know about for the AP exam are:
  • int which can represent integers, i.e. numbers with no fractional part such as 3, 0, -76, and 20393.
  • double which can represent non-integer numbers like 6.3 -0.9, and 60293.93032. Computer people call these β€œfloating point” numbers because the decimal point β€œfloats” relative to the magnitude of the number, similar to the way it does in scientific notation like \(6.5 βœ• 10^8\text{.}\) The name double comes from the fact that double values are represented using sixty-four bits, double the thirty-two bits used for the type float which used to be the normal size floating point number when most computers did math in units of 32-bits. (float is rarely used these days and is not part of the AP curriculum.)
  • boolean which can represent only two values: true and false. We’ll discuss the boolean type in ChapterΒ 4Β Booleans and conditionals
Another way to think of a data type is as a set of values and a set of operations on those values. For example, the int datatype represents the set of integers that can be represented in thirty-two bits (-2,147,483,648 to 2,147,483,647) and they support the normal arithmetic operations like addition, subtraction, multiplication, and division as well as a few that you probably didn’t learn about in elementary school.

Activity 2.1.1.

What type should you use to represent the average grade for a course?
  • While you could use an int, this would throw away any digits after the decimal point, so it isn’t the best choice. You might want to round up a grade based on the average (89.5 or above is an A).
  • double
  • An average is calculated by summing all the values and dividing by the number of values. To keep the most amount of information this should be done with decimal numbers so use a double.
  • boolean
  • Is an average true or false?

Activity 2.1.2.

What type should you use to represent the number of people in a household?
  • The number of people is a whole number so using an integer make sense.
  • double
  • Can you have 2.5 people in a household?
  • boolean
  • Is the number of people something that is either true or false?

Activity 2.1.3.

What type should you use to record if it is raining or not?
  • While you could use an int and use 0 for false and 1 for true this would waste 31 of the 32 bits an int uses. Java has a special type for things that are either true or false.
  • double
  • Java has a special type for variables that are either true or false.
  • boolean
  • Java uses boolean for values that are only true or false.

Activity 2.1.4.

What type should you use to represent the time of the gold medal winner in the 100 meter dash in the Olympics?
  • The integer type (int) can’t be used to represent numbers with fractional parts and the difference between gold and silver in the Olympics is often measured in just thousandths of a second.
  • double
  • The double type is excellently suited to representing measured quantities that might not be whole numbers.
  • boolean
  • Java uses boolean for values that are only true or false.

Subsection 2.1.2 What is a variable?

There are two aspects to a variable. To the computer a variable is a location in its memory that can store a value. The value stored at that location can change, or vary, while the program is running which is why we call them variables. To us human programmers, on the other hand, the important aspect of a variable as its name that we can use to refer to the data without having to know about the variable’s exact location in memory.
For example, in a computer game we might need to keep track of the player’s score, which will start at 0 and increase as the player earns points. The score can be stored somewhere in memory but in our program we’ll refer to it with the name score since that’s much more convenient than something like β€œaddress 66a3ffec”.
Figure 2.1.1. A pong game in Scratch with a score shown in the upper left.
The following video gives a quick summary of the relationship between variables, their names, and their data types.

Subsection 2.1.3 Declaring variables in Java

To create a variable, you must tell Java its data type and its name. Creating a variable is also called declaring a variable. The type is a keyword like int, double, or boolean, but you get to make up the name for the variable. When you create a variable that will hold a primitive type, Java will set aside enough memory to hold a value of that type and will associate that memory location with the name you used.
Computers store all values using bits (binary digits). A bit can represent two values and we usually say that the value of a bit is either 0 or 1. When you declare a variable, you have to tell Java the type of the variable because Java needs to know how many bits to use and how to represent the value. The 3 different primitive types all require different number of bits. An integer gets 32 bits of memory, a double gets 64 bits of memory and a boolean could be represented by just one bit.
Figure 2.1.2. Examples of variables with names and values. Notice that the different types get a different amount of memory space.
To declare (create) a variable, you specify the type, leave at least one space, then the name for the variable and end the line with a semicolon (;). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).
Here is an example declaration of a variable called score.
int score;
After declaring a variable, you can give it a value like below using an equals sign = followed by the value.
int score;
score = 4;
Or you can set an initial value for the variable in the variable declaration. Here is an example that shows declaring a variable and initializing it all in a single statement.
int score = 4;
The equal sign here = doesn’t mean the same thing as it does in a mathematical equation where it is an assertion that the two sides are equal. In programming it means make them equal by setting the variable named on the left to the value of the expression on the right. The line above sets the value of the variable score to the literal value 4. The variable always has to be on the left side of the = and the value expression on the right.

Activity 2.1.5. Variable declarations.

While we can declare a variable without giving it an initial value, a variable must be initialized before it can be used in an expression. A variable is initialized the first time it is assigned a value.

Activity 2.1.6. Variable initializations.

Activity 2.1.7.

This assignment statement below is in the wrong order. Try to fix it to compile and run.

Activity 2.1.8.

Activity 2.1.9.

Activity 2.1.10.

Mixed up Code Problems

Activity 2.1.11.

The following code declares and initializes variables for storing a number of visits, a person’s temperature, and if the person has insurance or not. It also includes extra blocks that are not needed in a correct solution. Drag the needed blocks from the left area into the correct order (declaring numVisits, temp, and hasInsurance in that order) in the right area. Click on the β€œCheck Me” button to check your solution.

Subsection 2.1.4 Naming Variables

While you can name your variable almost anything, there are some rules. A variable name should start with an alphabetic character (like a, b, c, etc.) and can include letters, numbers, and underscores _. It must be all one word with no spaces.
You can’t use any of the keywords or reserved words as variable names in Java (for, if, class, static, int, double, etc). For a complete list of keywords and reserved words, see https://docs.oracle.com/javase/specs/jls/se22/html/jls-3.html#jls-3.9.
The name of the variable should describe the data it holds. A name like score helps make your code easier to read. A name like x is not a good name for a variable holding a score, because it gives no clues what the variable is used for. On the other hand, don’t use names that are too long like theNumberThatHoldsTheScore as those are also hard to read. Choose names that make your code easier to understand, not harder.
The convention in Java and many programming languages is to always start a variable name with a lower case letter and then uppercase the first letter of each additional word, for example gameScore. Variable names can not include spaces so uppercasing the first letter of each additional word makes it easier to read the name. Uppercasing the first letter of each additional word is called camel case because it looks like the humps of a camel. Another option is to use underscore _ to separate words, but you cannot have spaces in a variable name.

Activity 2.1.12.

Java is case sensitive so gameScore and gamescore are not the same. Run and fix the code below to use the right variable name.

Activity 2.1.13.

Activity 2.1.14.

Subsection 2.1.5 Debugging Challenge: Weather Report

Debug the following code that reads out a weather report. Make sure the data types match the values put into the variables. Can you find all the bugs and get the code to run? Work with a programming buddy if you get stuck.

Project 2.1.15.

Debug the following code. Can you find the all the bugs and get the code to run?

Subsection 2.1.6 Summary

  • (AP 1.2.B.2) A variable is a memory storage location that holds a value, which can change while the program is running.
  • (AP 1.2.B.2) Every variable has a name and an associated data type that determines the kind of data it can hold. A variable of a primitive type holds a primitive value from that type.
  • A variable can be declared and initialized with the following code:
    int score;
    double gpa = 3.5;
    
  • (AP 1.2.A.1) A data type is a set of values and a corresponding set of operations on those values. Data types can be primitive types (like int) or reference types (like String).
  • (AP 1.2.A.2) The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
  • (AP 1.2.A.3) A reference type, like String, is used to define objects that are not primitive types.
  • (AP 1.2.B.1) The three primitive data types used in this course are int (integer numbers), double (decimal numbers), and boolean (true or false).

Subsection 2.1.7 AP Practice

Activity 2.1.16.

Which of the following pairs of declarations are the most appropriate to store a student’s average course grade in the variable GPA and the number of students in the variable numStudents?
  • int GPA; int numStudents;
  • The average grade in GPA could be a decimal number like 3.5.
  • double GPA; int numStudents;
  • Yes, the average grade could be a decimal number, and the number of students is an integer.
  • double GPA; double numStudents;
  • The number of students is an integer number. Although it could be saved in a double, an int would be more appropriate.
  • int GPA; boolean numStudents;
  • The average grade in GPA could be a decimal number like 3.5. Booleans hold a true or false value, not numbers.
  • double GPA; boolean numStudents;
  • Booleans hold a true or false value, not numbers.
You have attempted of activities on this page.