Unit 1: Introduction to Java
1.3 Variables
Computer programs only manipulate numbers. Everything (pictures, sounds, instructions, text) is encoded as numbers. Programs store and retrieve data in memory. There are two things that you and the computer need to know:
- where the storage is located in memory
- what type of data is going to be stored there.
Java has about 50 reserved words and 8 primitive data types.
You cannot use these words as class names, function names, or variable names.
We call this named storage space a variable. A variable is a place in the computer's memory where one piece of data can be stored. You refer to the variable by a variable name given by the programmer. Each variable can hold only one type of information. When you make a variable, you have to do a number of different things:
step | terminology for variables | terminology for objects |
---|---|---|
name the variable | declaration | declaration |
state what type of variable it is | ||
allocate memory for it | automatic | instantiation |
initialize it to some value. | initialization | |
change to another value | assignment | assignment |
Example: using primitive data type
int x;
This says that x is a variable of type "int". It also allocates memory for it.
x = 7;
This initializes x. Without this, there may be just a random number in x
These lines can be combined into one as: int x = 7;
Example: using an object (we'll learn about this when we do objects)
Dog rover;
This says that rover is (the name of) an object of type "Dog".rover = new Dog()
This creates the object and allocates memory for it.rover.age = 3
This initializes some aspect of the rover object. Initialization may also be done when the object is created.
These lines can be combined: Dog rover = new Dog();
You still need rover.age = 3
Once a variable has been created, you can just change the contents.
You don't need to create it again, in fact, you get an
error if you try to do this.
String name = "Bob"; String name = "Bob Jones";
ERROR!!! (name already exists)
Correct way:
String name = "Bob"; name = "Bob Jones";
A variable can be declared only once.
It is used by the compiler to help programmers avoid mistakes such as assigning string values to integer variables.
Before reading or assigning a variable, that variable must have been declared.