Next: None. Up: Introduction. Previous: Pieces of a program.


Variables

Textbook: Section 2.4

Definition

A variable is just a place in memory. From the programmer's point of view, a Java variable has three things associated with it.

Declaring a variable

Before you use a variable, you first have to tell Java that it exists so that the compiler knows about it. This is a declaration. To declare a variable in Java, type the type name followed by the variable name followed by a semicolon.

        int i;
If you want, you can declare several variables of the same type on the same line.
        int i, num_students, total_grade;
In general, I recommend against this practice; declare only one variable per line. This makes it easier to find the variable names and the code easier to edit.

The scope of a variable is the area of the program where you can use it. In Java, a variable's scope begins at the point of the variable's declaration and proceeds to the end of the innermost brace pair in which the declaration lies.

import csbsju.cs160.*;

public class Example {
    public static void run() {
        IO.println("hello world!");
        ... {
            // i isn't usable here
            int i;
            // now it is
            ... {
                // we can still use i within this brace pair
            }
            // and we're still within the brace pair
        }
        // but now we're out of the brace pair; i is unavailable
    }
}

Assigning a value

To assign a value to a variable, type the variable name, followed by an equal sign, followed by the value, followed by a semicolon.

        i = 2;
From here on, the variable's value is 2.

It's often convenient to combine the declaration and the first assignment.

        int i = 2;

What do you think the testI() method will print?

import csbsju.cs160.*;

public class Example {
    public static void testI() {
        int i;
        i = 2;
        IO.println("i");
        IO.println(i);
        i = 5;
        IO.println(i);
    }
}

Constants like 2 have an immediately recognizable type. In the case of integers, a constant is just a sequence of digits. For double values, the constant contains a decimal point (or an exponent, as in 3e8, which represents 3×108). For boolean constants, the only permissible values are true and false. And for characters, you type the character in a set of single quotes: 'A' (the capital A character) or ' ' (the space character). It's important that the character be in quotes; otherwise, the compiler will understand it as a variable name (or whitespace, or whatever else is appropriate).


Next: None. Up: Introduction. Previous: Pieces of a program.