AP Computer Science Java: Lesson 1.3b
Variables and Constants - Working with Variables


Lesson 1.3b - Working with Variables
Purpose: To learn how to declare and assign values to Java variables

Declaring variables
Before a variable can be used in a program it must be declared. That means it must be given a name and a type (and optionally an initial value). By doing so, we allow Java to set aside storage space for this named variable.

The format of a Java variable declaration is

type name;

Here are some examples:

int ernational;
double trouble;
char mander;
String cheese;
boolean gameOver;

It also permitted to declare several variables of one type in the same statement.

int eresting, errupted;
double play, or_nothing, stuff_oreos;

Lastly, it is also possible to give a variable an initial value when it is declared.

int age = 17, year = 2006;
double cost = 12.89;
char letterGrade = 'A';
String name = "Boba Fett";
boolean gameOver = false;

Note the use of single quotes when assigning a character value and double quotes when assigning a string value. They are requirements of these data types.


Assigning values to variables Once a variable is declared we can give it a value via input or assignment statement.

Input example:    age = keybd.nextInt();

Assignment example:    age = currentYear - yearBorn;

Note that the form of the assignment statement requires that the variable to be assigned is on the left of the equal sign and that the assigning expression is always on the right. See below.


Correct:
      age = currentYear - yearBorn;

Incorrect:     currentYear - yearBorn = age;


Using variables in equations
We can also use declared variables in equations and output, but only after first giving the variable a value.

Correct
double price = 18.95, tax;
tax = .0725 * price;

Incorrect
double price, tax;
tax = .0725 * price;

The problem in the second version is that we are trying to use the variable price in an equation, but price does not have a value yet. This will produce a compile-time error. The same error will occur if we try to output price before it has a value.

© DanShuster.com