Variables and the 8 Primitive Data Types

The Purpose of a Variable (and some vocabulary)

You can think of a simple program as a list of instructions to be read and acted upon sequentially

Example:

  1. Read a value representing the radius of a circle from the standard input source/stream
  2. Compute the area of a circle with this radius
  3. Print the area to the standard output stream (i.e., the console window)

Remember: a computer will read and act upon these instructions one at a time - it is not aware of what is coming up until it gets there!

Looking at step 1 in the program above, we will need to tell the computer that it needs to remember the value it is reading in - it needs to store this value in its memory somewhere so we can use it in a computation later.

To this end, we will need to do a couple of things. First, we need to tell the computer how much memory to use to store the value in question. Different kinds of numbers require different amounts of memory (more on this in a minute).

Of course, sometimes we need to store information that isn't explicitly numerical. These things too, come in different sizes. For example, it will certainly take more memory to store the Declaration of Independence than it will to store a single letter (i.e., a "character").

In addition to telling the computer how much memory we want to use to store the value in question, we also need to tell the computer how the value should be stored in memory (i.e., what method of "encoding" should be employed to turn the value into a string of 1's and 0's). Examples of types of encodings used include Two's Complement, IEEE 754 Form, ASCII, Unicode, etc...

The computer also needs to have some reference to where it stored the value in memory, so it can find it again.

The concept of a (typed) variable solves all of our problems here. A variable in Java gives us a way to store numerical or other kinds of information for later use, addressing all of the aforementioned considerations. The information being stored is called the value of the variable, regardless of whether the information is numerical or not.

The amount of memory allocated for a given variable and how the value associated with that variable should be encoded into 1's and 0's in memory are specified by its type. There are 8 primitive types of data built into the Java language. These include: int, byte, short, long, float, double, boolean, and char. The first 6 allow for storage of different kinds of numerical values, the last stores a single character (think "keyboard" character). We'll talk more about the differences between these in a little bit...

Also, every variable has a name that both serves as a "human-friendly" reference for the information, and is associated with the location in memory where the variable's value will be stored.

Whenever we use a variable in a Java program, we must first declare the variable - that is, we specify what the type and name of the variable will be.

Then we can assign a value to the variable - that is, tell it what to remember.

When we assign a variable a value for the first time, we are said to be initializing the variable.

Of course, computers are picky about how you tell them to do something. Truth be told, they are kind of dumb. They can't "read between the lines" or "figure out what you really meant". Programming languages have a particular format you have to stick to when telling the computer what to do. This format is called syntax. When code is written in a way that the computer can understand, we say the code is syntactically correct. When the code is written in a way the computer cannot understand, we say there is a syntax error.

Let's take a look at the syntax for declaring a variable:

<variableType> <variableName>;

Two Examples:

int myLuckyNumber; //Declares myLuckyNumber to be an integer variable
char myLetter;     //Declares myLetter to be a character variable

The semicolon on the end functions much like a period does in the English language. It tells the computer that the statement of what to do is complete at this point. Here, what the computer must do is: "Declare this variable of this type (that is to say: tell the computer to allocate an appropriate amount of memory for the type of variable given and reference that portion of memory by the name given), and that's it. Now move on to the next statement".

To assign a variable a value (i.e., fill the memory associated with the variable with some information in an appropriately encoded way, per it's type), we use the following syntax:

<variableName> = <value or expression>;

Some Examples:

myLuckyNumber = 13;     //Assigns the variable myLuckyNumber 
                        //the value 13
myLuckyNumber = 5+8;    //Also assigns the variable myLuckyNumber 
                        //the value 13
                        //Note: expressions like the sum on the 
                        //right are evaluated before they are 
                        //assigned
myLetter = 'a';         //Assigns the variable myLetter the 
                        //character 'a'.

Note the equals sign here means something different than it does in mathematics. In fact, we don't even call this symbol "equals". We call it the "assignment operator" instead, or "gets" for short.

So we read the following:

myLuckyNumber = 13;

as "The variable myLuckyNumber gets the value 13."

A Useful Shortcut -- Variable Declaration and Assignment in One Statement

Java does allow us to shorten variable declaration and initialization up a bit, syntactically. We can declare a variable and assign it a value in one step as the following examples show:

int x = 1;
double d = 1.4;
char myLetter = 'a';
int myLuckyNumber = 5 + 8;
double myProduct = 3.14 * (2.78 + 1.0);

When source code contains a representation of a fixed value (like 1, 1.4, and 'a' above) that requires no computation, we call that representation a literal.

An expression, on the other hand, (like the 5+8 or the 3.14 * (2.78 + 1.0) above) is a combination of one or more operands and operators, whose value must be calculated. The operands might be literals, variables, or some other source of data (e.g., values returned from methods -- but more on that later).

Variable Reassignment

Variables don't have to have the same value throughout your entire program. Their contents can be changed over the course of the program's execution. For example, suppose you are writing a program to count the number of stars seen in an image of the night sky taken with your digital camera. You might declare a variable named "numStarsFound", initializing it to zero. Then upon examining the picture file, each time your program locates a new star, you might increase the value of your variable by one with the following statement:

numStarsFound = numStarsFound + 1;

Then when you are done, the variable numStarsFound will reflect the number of stars found in the entire picture.

Be aware, you must declare a variable before you can assign a value to it, but you should only declare a variable once within a given scope. (We'll talk more about scope later.)

Printing the Value of a Variable

As seen in the "Hello World" program, we can use System.out.println() to print things to the console. The "things" that can be printed include text strings, variable values, or the value of any valid expression. As an example, suppose one wants to print the value of a previously declared and initialized variable named myVar. The following would do the trick:

System.out.println(myVar);

Technically, the code above does a little bit more than just printing the value of myVar -- it also prints a line-feed character immediately afterwards. The effect of this is similar to hitting the "return" key on a keyboard, it moves the cursor down a line. As such, if anything is printed to the console after this statement, it will be printed on a different line.

If you wanted to avoid printing the extra line-feed character, you could opt for System.out.print() instead, as the example below suggests.

int a = 1;
int b = 2;
System.out.println(a);
System.out.println(b);
System.out.print(a);
System.out.print(b);

The above code snippet would print the following to the console:

1
2
12
Here's an example that mixes in some re-assignments and also prints variable values of different types. Note in particular how the double z gets printed as a decimal, despite it not having a fractional part...

int x = 1;             //an integer variable x is declared 
                       //and initialized to 1

int y = 2;             //an integer variable y is declared 
                       //and initialized to 2

double z = 3;          //a double variable z is declared
                       //and initialized to 3.0

x = y + 3;             //x is now 5
y = x * 4;             //y is now 20
x = x + 1;             //x is now 6

System.out.print(x);   //prints 6 to the console
System.out.println(y); //prints 20 to the console
System.out.println(z); //prints 3.0 to the console

Here's what we would see on the console when the above code is executed:

620
3.0

The Names of Variables...

The name of a variable is formally called an identifier.

abstract continue for new switch
assert*** default goto* package synchronized
boolean do if 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
(* not used; ** added in Java 1.2; *** added in Java 1.4; **** added in Java 5)

Conventions for Identifiers

The computer doesn't care about the following rules, but your instructor and any other programmer (including you) that has to read your code will!

The 8 Primitive Variable Types

Depending on the nature of the information one wishes to store in a variable, and -- in the case of numerical information -- depending the size and precision required, one can use any of the following eight primitive types in Java:

byte, short, int, long, float, double, char, boolean.

For the 6 numerical types, we have the following ranges, storage size, and encoding methods:

Name Range Storage Size (and Method)
byte -128 to 127
(i.e., -27 to 27 - 1)
8 bits (Two's Complement)
short -32768 to 32767
(i.e., -215 to 215 - 1)
16 bits (Two's Complement)
int -2147483648 to 2147483647
(i.e., -231 to 231 - 1)
32 bits (Two's Complement)
long -9223372036854775808 to 9223372036854775807
(i.e., -263 to 263 - 1)
64 bits (Two's Complement)
float Negative range: -3.4028235E+38 to -1.4E-45
Positive range: 1.4E-45 to 3.4028235E+38
32 bits (IEEE 754 Notation)
double Negative range: -1.7976931348623157E+308 to -4.9E-324
Positive range: 4.9E-324 to 1.7976931348623157E+308
64 bits (IEEE 754 Notation)


Note: float and double number types are stored in IEEE 754 format, and thus not stored with complete accuracy due to approximations. To convince yourself of this, try the following

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

and...

System.out.println(1.0 - 0.9);