Time estimate: 90 min.

1.3. Variables and Data Types

In this lesson, you will learn about variables and primitive data types.

1.3.1. What is a Variable?

A variable is a name associated with a memory location in the computer, where you can store a value that can change or vary. The following video explains what a variable is and gives a couple of real word examples of variables.

When you play a game, it will often have a score. Scores often start at 0 and increase, so they can change. A score can be stored in a variable.

../_images/pongScore.png

Figure 1: A pong game in Scratch with a score shown in the upper left.

1.3.2. Data Types

There are two types of variables in Java: primitive variables that hold primitive types and object or reference variables that hold a reference to an object of a class. A reference is a way to find the object (like a UPS tracking number helps you find your package). The primitive types on the Advanced Placement Computer Science A 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\). The name double comes from the fact that doubles are represented using 64 bits, double the 32 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. (The data type is named for George Boole, a 19th century English mathematician who invented Boolean algebra, a system for dealing with statements made up of only true and false values.)

String is one of the object types on the exam and is the name of a class in Java. A String is written in a Java program as a sequence of characters enclosed in a pair of double quotes - like "Hello". You will learn more about String objects in Unit 2.

Note

Some languages use 0 to represent false and 1 to represent true, but Java uses the keywords true and false in boolean variables.

A type is a set of values (a domain) and a set of operations on them. For example, you can do addition operations with ints and doubles but not with booleans and Strings.

exercise Check your understanding

1.3.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 primitive variable Java will set aside enough bits in memory for that primitive type and associate that memory location with the name that you used.

The fact that you need to declare the type of a variable is one of the ways Java differs from languages like Python, Javascript, and Snap! In those languages a variable is just a name for a value and the value can be of any type. In Java you have to say what type of value a variable will be used to name and the Java compiler will make sure you never try to use a variable to hold a different kind of variable. While it creates some extra work when declaring variables it also helps avoid bugs caused by different parts of your program not agreeing on the types of values they are working with.

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.

../_images/typesAndSpace.png

Figure 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;

You can print the value of variables by passing them to System.out.print and System.out.println like this:

System.out.println(score);

You can also concatenate values with a String using the + operator. Concatenation just means “smoosh together” so "Score: " + score is an expression that smooshes together the string "Score: " with the value of the variable score converted to a String, giving us "Score: 4". We can then print that new value like this:

System.out.println("Score: " + score);

Remember when you are trying to print the value of a variable you do not put the name of the variable in quotes. score is the name of a variable; "score" is a string containing the word “score”.

If you want spaces between words and variables, you must put the spaces inside the quotes of some String. If you forget to add spaces, you will get smushed output like Score:4 instead of Score: 4.

coding exercise Coding Exercise:

Run the following code to see what is printed. Then, change the values and run it again. Try adding quotes around some variables and removing spaces from some of the strings to see what happens.

The equal sign here = doesn’t mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here it means set the value in the memory location associated with the variable name on the left to a copy of the value on the right. The first line above sets the value in the box called score to 4. A variable always has to be on the left side of the = and a value or expression on the right.

exercise Check Your Understanding

coding exercise Coding Exercise:

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

exercise Check Your Understanding

Mixed up Code Problems

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.

The keyword final can be used in front of a variable declaration to make it a constant that cannot be changed. Constants are traditionally written in all upper case.

final double PI = 3.14

coding exercise Coding Exercise:

Try the following code and notice the syntax error when we try to change the constant PI. Put the comment symbols // in front of that line to remove the error and run it again.

1.3.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/se14/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 in most contexts, because it gives no clues as to what kind of data it holds. On the other hand, don’t name your variables crazy things like thisIsAReallyLongName, especially on the AP exam. You want to make your code easy to understand, not harder.

Note

  • Use meaningful variable names!

  • Start variable names with a lower case letter and use camelCase.

  • Variable names are case-sensitive and spelling matters. Each use of the variable in the code must match the variable name in the declaration exactly.

  • A variable name inside quotes is just a String not a reference to the variable.

The convention in Java and many programming languages is to always start a variable name with a lower case letter and then capitalize the first letter of each additional word, for example gameScore. Since variable names can not include spaces, capitalizing the first letter of each word after the first makes it easier to read the name. This style is called camel case because it looks like the humps of a camel. Another option is to use underscore to separate words, known as snake case, so game_score rather than gameScore. But snake case it is almost never used in Java. (Programmers working in the language Python—appropriately enough—almost always use snake case.)

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

exercise Check Your Understanding

1.3.5. groupwork Debugging Challenge : Weather Report

Working in pairs, debug the following code. Can you find the all the bugs and get the code to run?

1.3.6. Summary

  • A variable is a name for a memory location where you can store a value that can change or vary.

  • A variable can be declared or declared and initialized as shown in the the following code:

    int score;
    double gpa = 3.5;
    
  • Data types can be primitive types (like int) or reference types (like String).

  • The three primitive data types used in this course are int (whole numbers), double (decimal numbers), and boolean (true or false).

  • Each variable has associated memory that is used to hold its value.

  • The memory associated with a variable of a primitive type holds an actual primitive value.

  • When a variable is declared final, its value cannot be changed once it is initialized.

1.3.7. AP Practice

You have attempted of activities on this page