Overview of This Lesson

In this lesson we'll learn about variables in Java: what are they, how to create them, and how and why we use them.

Variables are a very important part of every programming language. Variables allow you to store pieces of data that you can use throughout your application. Variables are used in many expressions and statements.

Pre-Requisites

Before doing this tutorial, make sure you've gone through the tutorial Data Types.

What are Variables?

A variable is a storage location in the computer's memory or RAM - you assign a name to your variable so that you can access that memory location whenever you want in your program code. RAM is temporary storage: it's only available to your application while the application is running. That's fine, though because we often need to store things temporarily while the program runs. When you want to store things more permanently, you would use a file, database, or other storage mechanism, which is beyond the scope of this tutorial.

One problem with working with storage locations in memory is that the memory addresses aren't easy to remember. They're not symbolic at all and consist of address such as "13A4:0170". In addition, because programs and files are always being loaded in and out of memory, different areas of memory become available each time you run a program. You might run a program now and store a value in address 13A4:0170, but if you run the same program an hour from now, that address may no longer be available.

To overcome these problems, we define variables in our program to refer to storage locations with symbolic names that are easier to remember. Imagine you live in residence this term and are given a mailbox where you can pick up your mail. You know which box is yours because it probably has your room number on it, or your name. When you come back after summer vacation, you most likely get a different room. Will you have trouble finding your mailbox? Probably not, as it will have your new room number or your name on it. Memory can work the same way. We can tell the program to go grab a location in memory, and we can give it a name to stick on that location so that it's easy to refer back to it later.

Declaring and Initializing Variables

When you want to use a variable in your code, you have to declare or define it using a variable declaration statement. The syntax varies from language to language, but here's how you do it in Java:

dataType variableIdentifier;

In Java, all variable identifiers must have the correct syntax:

Industry standards for Java also state that a variable identifier should have the following characteristics:

Examples

Here are some examples of variables that you might use in a program:

You can even declare multiple variables in a single statement as long as they all have the same data type:

int n1, n2, n3;

However, this makes it harder to read and document variables so we don't do it often.

Where Do We Declare Variables?

In Java, there are a few places where you can declare variables. To start with, we'll declare our variables inside the main() method. Any time you declare a variable inside any method, that creates a local variable. When you declare variables outside of a method, that increases the level of scope of the variable. Variable scope refers to the accessibility or visibility of a variable. For example, local variables are only available inside the code block in which they are declared. We will discuss more about variable scope and how you can declare variables with larger scope as we go through the course.

public class TestVariables {
    public static void main(String[] args) {
        double empSalary;
        int numRecords
        String songName;
    }
}

Exercises

Which of the following are syntactically valid variable identifiers? For the invalid ones, explain why they're invalid.

  1. headings
  2. headings12
  3. headings 12
  4. 12headings
  5. point.x
  6. pointX
  7. Xpoint
  8. point^x
  1. headings - valid
  2. headings12 - valid
  3. headings 12 - invalid: contains a space
  4. 12headings - invalid: starts with a digit
  5. point.x - invalid: contains a period/decimal (note that if you've done object oriented programming before, this might be valid if you had an object called "point" and it contained a property called "x" but for a regular variable as we've described in this lesson, point.x is invalid)
  6. pointX - valid
  7. Xpoint - valid (although note that industry standards state it should not start with an upper-case X, but syntactically the variable is fine)
  8. point^x - invalid: contains the ^ (caret) character

For each of the following statements below, declare a variable. Use the most appropriate data types and identifier names.

  1. to store a customer's last name
  2. to record the number of customers
  3. to record the cost of a product
  4. to store an employee's phone number
  5. to record a single keystroke made by the user

Note that these have several correct answers. If you aren't sure about your own answer, ask your professor.

  1. String custLastName;
  2. int numCustomers;
  3. double productCost; or float productCost;
  4. String empPhone; (or in some cases long empPhone;
    you'd have to use long if you store as digits because many phone numbers would be too large a value for the int type - but this issue is why most developers will use String)
  5. char keyInput;

Using Variables

Variables need to be assigned a value. This is often done at the same time a variable is declared, but not always. When you give the variable a value for the very first time, that's called variable initialization.

Here are some examples of declaring and initializing variables at the same time:

String custFirstName = "Fred";
int numCustomers = 10;
double productCost = 5.99;
        

You can even declare and initialize multiple variables in a single statement as long as they all have the same data type:

int n1 = 2, n2 = 4, n3 = 5;

This does make the code harder to read and document, so we don't do this often.

You can initialize a variable with its first value after you declare it:

String custFirstName; 
... other code here ...
custFirstName = "Fred";

However, note that you can't "use" a variable until it has first been initialized, either when you declare it or some time after:

public class UseVariables {
    public static void main(String[] args) {
        
        int num;

        // this won't work:
        System.out.println(num);
    }
}

This program will give you a compile error: "The local variable num may not have been initialized." This is why many programmers prefer to initialize a variable to a default value. If you don't have a default value that makes sense, you can usually use the type's null value. In this case, the null value for an integer is 0, but feel free to use any positive or negative whole number you like:

public class UseVariables {
  public static void main(String[] args) {
      
      int num = 0;

      // this won't work:
      System.out.println(num);
  }
}

Note also that you can't use a variable if it has never been declared or defined:

public class UseVariables {
  public static void main(String[] args) {

      // this won't work:
      System.out.println(num);
  }
}

This program won't work because the variable num was never declared. Most editors will give you a "cannot resolve symbol" or "variable not defined" type of error.

Note that we use the = (equals) sign to assign a value or result to a variable. This is typical in programming so you'll see this a lot. Specifically, this is called an assignment statement.

We'll learn more about assignment statements in the next lesson, but this should be enough to allow you to start creating and working with variables.

Example

Examine the following code segment and the diagram below:

double dblSales = 2050.27;
double dblCommRate = .07;
double dblCommission = dblSales * dblCommRate;
All three variables in memory.

This diagram illustrates the results of the three assignment statements above the diagram. Each variable is a location in memory, and each memory location or variable is given a value to store. The first two statements store literal values or hard-coded values into the variables dblSales and dblCommRate. The third statement calculates the value of dblSales multiplied by dblCommRate, and stores the result in the variable dblCommission.

Exercise

How many variables are used in the program below?
What is the name and type of each variable?

public class GradeCalculator {
    public static void main(String[] args) {
        int assignGrade = 40;
        double assignMax = 32.5;
  
        double assignWeight = assignGrade / assignMax * 100;
  
        System.out.println("Assignment grade: " + assignWeight + "%");
    }
}

There are three variables being used in this program:
assignGrade, which is an int (integer)
assignMax, which is a double
assignWeight, which is also a double

Why do you think I used double instead of float for the assignMax variable? Try it and see what happens. We will discuss this in an upcoming lesson.