A variable is something that can hold a particular type of data and store it in the computer’s memory. This concept is best explained by an example, so let’s go ahead and get into one!

Creating a variable

Let’s say that you want to store your age in a variable. What type of data is your age? A number! So, you would want to declare this variable to be able to store numbers. In this example, let’s use an int. Below is how you would create a variable to store your age (assume you are 10 years old):

int age = 10;

In the above line of code, you can see the different components that are required to create a variable. The first thing we did was specify which data type our variable was going to store, which was an int in this case. Next, we gave our variable a name. The name of your variable can be anything! We named this variable “age” because that’s what the variable is going to store. We’ll get into naming variables more in a bit.

After the name, you can see an “=” sign, and this is what programmers call the assignment operator. We basically use it whenever we want to store or “assign” a value to a variable. Then, we went ahead and entered “10” to represent your age. Lastly, recall that we always use a semicolon ( ; ) to end our lines of code, to signal to the computer to move on to the next line. And those are the components of creating a variable!

Naming variables

Naming Variables

Let’s talk more about how to name your variables. Technically, you can name your variables anything as long as you continue to use the same name to refer to your variable throughout your entire program. That being said, you want to make sure that the name you give your variable is meaningful and actually has something to do with what you are storing in it.

Here are some general guidelines for naming variables:

  1. Your variable name should always start with a lowercase letter. If your variable name consists of two or more words, use camelCase, which basically means that you should capitalize the first letter in every word of your variable name EXCEPT the first letter of the first word. Examples:

    1. int age = 10;
    2. int dogAge = 5;

    NOT 3. int Age = 10; 4. int DogAge = 5;

  2. You may use numbers in your variable name, but make sure they are at the end of the name, not at the beginning. Examples:

    1. int age1 = 10;
    2. int age2 = 10;

    NOT 3. int 1age = 10; 4. int 2age = 10;

  3. Variables cannot have the same name as reserved terms (i.e. int)

    1. int age = 10;
    2. char apple[] = "apple";

    NOT

    c. int int = 10;

    d. char char = "apple";