1.3 Variables and Data Types

What is a variable?

A variable is a named storage location that holds a value in a computer's memory. It acts as a symbolic name for a physical memory address where data can be stored and retrieved. The value stored in a variable can change or "vary" during the execution of a program.

Variables are fundamental in programming for several reasons:

  1. Data Storage: They allow programs to store different types of data, such as numbers (1010), text ("Hello"), boolean values (true/false), or more complex data structures.

  2. Manipulation: Once data is stored in a variable, it can be accessed, modified, and used in computations or logical operations.

  3. Flexibility: Using variables makes code more flexible and reusable, as the same code can operate on different data values simply by changing the values assigned to the variables.

Each variable typically has a specific data type, which determines the kind of values it can hold (e.g., an integer variable can hold whole numbers, while a string variable holds sequences of characters) and the operations that can be performed on it. When a variable is declared, memory is reserved for it, and the program uses the variable's name to refer to that memory location.

Data Types

In Java specifically, there are two types of variables:

  • Primitive Variables: These are the basic data types provided by the Java language. They directly store the actual value in the memory location allocated for them. Each primitive type has a predefined size and range of values, and they are not objects. When a primitive variable is declared, a specific amount of memory is reserved to hold its raw value.

  • Object/Reference Variables: These variables do not store the object itself but rather a reference (a memory address) to where the object is stored in memory. Objects, which are instances of classes, are typically stored in the heap memory. When an object/reference variable is assigned to another, it's the reference that is copied, not the object's data. This means both variables will point to the same object in memory.

Primitive Types that are going to be used in the AP Computer Science A exam are:

  • int: Represents integers.

  • double: Represents non-integer numbers (decimals)

  • boolean: Can represent 2 values, true and false.

A String is written in a Java programs as a sequence of characters enclosed in either ‘single-quotation’ or “double-quotation”.

Declaring a Variable

To declare a variable in Java, you must specify which data type and its name. Example:

int age = 17;
// integer 17 is age, or age in equal to integer 17.

At the end of your variable declaration, you must include a semicolon (;).

When printing out variables, you can use whats called string concatenation. String concatenation is  the process of linking two or more strings together to form a single string, which can be useful when displaying messages that include variable values. The string concatenation operator is +. 

You can also make a variable unchangable. This is done by declaring the variable with the final keyword in languages like Java, which ensures that once the variable is assigned a value, it cannot be reassigned. This can be useful in situations like  defining constants that represent configuration settings or mathematical constants, helping to prevent accidental modifications that could lead to errors in the program. Final variables are traditionally capitalized.

Naming Variables

There are some rules to follow when naming variables to ensure clarity and avoid errors:

  • A variable name should start with an alphabetic character (a, b, c, …).

  • It can include letters, numbers, and underscores.

  • Must be all one word, no spaces.

  • Can’t use any of the keywords or reserved words as variable names in Java

  • List of reserved words:

abstract   continue   for          new         switch
assert     default    if           package     synchronized
boolean    do         goto         private     this
break      double     implements   protected   throw
byte       else       import       public      throws
case       enum       instanceof   return      transient
catch      extends    int          short       try
char       final      interface    static      void
class      finally    long         strictfp    volatile
const      float      native       super       while
_ (underscore)

Although you can name your variable almost anything you want, you’ll want it to be named following the data it will be holding. A variable called score should be holding an integer value to represent points in a game, while a variable called temperature might hold a float to allow for decimal values. Having your variables be named really long names also isn’t suggested, you want to have your code to be easy to understand.

Note

  • Use meaningful variable names!

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

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

  • Never put variables inside quotes (” “).

If a variable needs to have many words, don’t use spaces. A variable that hold game score shouldn’t be called “game score”. Instead, use a name like "gameScore" to clearly indicate its purpose while following proper naming conventions. This technique where you make the first letter lowercase and the other words’ first letter capital is called camelCase, that because it looks like the bumps of a camel. Another option you have is using _(underscore), it’d look like “game_score.” Using underscores is particularly helpful in languages that do not support camelCase syntax, making the variable names more readable.

Java is case sensitive, meaning that “gameScore” isn’t the same as “gamescore.” Additionally, choosing meaningful variable names can significantly improve code maintainability and collaboration among developers.Â