Why use variables

Variables are used to represent a piece of data in a Java program. The variable represents a memory location that stores the data. The data itself is called the variable’s value.

We use an identifier to name a variable. By convention, variable names should:

  • Begin with a lowercase letter
  • Be meaningful

For example, if our variable represents the sales tax for a purchase, name it salesTax instead of st or stax.

Multiple-word variable names are common. By convention, the first word begins with a lowercase letter, but subsequent words in the name each begin with an uppercase letter.

✏️ Programming Tip

Java variable names can be long. Favor clarity over brevity. Avoid one-letter names unless the context suggests that they are appropriate. Follow convention by beginning variable names with a lowercase letter.


When we first create a variable, we must choose its data type. That is, we must specify what type of data the variable will represent. For example, if our program involves apples, we might track the number of apples in the variable numberOfApples. This count is an integer, so the data type of this variable would be int.

We declare the data type of a variable in a declaration statement. For example, the following statements declare one int variable, two double variables, a character variable, and a Boolean variable:

int numberOfApples;
double pricePerApple, totalCost;
char letter;
boolean done;

Each declaration begins with a data type and contains one or more variables of that type. Commas separate variables of the same type, and a semicolon ends each declaration.

📝 Note: Variable declarations

You must declare a variable before you can use it. You declare each variable only once, regardless of how often you use it.

Get hands-on with 1200+ tech skills courses.