Variables in Java

Get an introduction to variables, their naming conventions, where they are stored in memory, and how much space they take.

Introduction

Variables are just like containers which hold the values while the program is executed.

A variable is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value.

Variables in Java are strongly typed; thus they all must have a data type declared with their identifier. In this lesson, we will discuss identifiers.

Naming a variable

Just as every person has a name that helps identify them, every variable has a name associated with it. There are certain naming conventions that one must follow in order to decide a name for the variable. This name is called the variable’s identifier. Variable names should be descriptive based on what data item they are declared to store.

There are three rules to create an identifier:

  1. Characters from A to Z, as well as their lowercase counterparts, can be used.
  2. Numbers from 0-9 can be used.
  3. Special characters that can be used are $ (the dollar sign) and _ (underscore).

Note:

  1. A variable must never start with a number
  2. The identifier can not have spaces in it

While you can give a variable any name, the identifier must describe or be related to the data being stored inside it. The same way when you name a book, it is indicative of the story or characters inside it, the identifier must also be related to the data it represents.

Think of it this way, a book about wizards and magic being called “Facts and Figures of the Modern World”. Doesn’t make sense, does it? Rather, if we called it, “A Magical Journey”, it would make much more sense. Below are a few examples of the identifiers we can use.

Let’s say we have a book, a book has multiple details- the name of the book, the number of copies published, the author and the publishing company. Imagine if we gave the identifiers as ‘a’, ‘b’, ‘c’, and ‘d’. Wouldn’t that be confusing? Now we will give them identifiers in line with the naming conventions that we have described above:

Get hands-on with 1200+ tech skills courses.