1. Overview
In this lesson, we’ll explore the concept of creating variables and using them in a practice example. Variables are one of the fundamental building blocks of any programming language, as they act as containers that hold data that can be used and modified throughout a program.
We’ll begin with a brief introduction to what variables are in Java, including primitive variables and reference variables, as well as the recommended naming conventions for variables.
To follow along with the examples, let’s create a new project in our IDE and add a Main class. We can place the code snippets from this lesson inside the main method of that class.
If we want to reference the complete code we’ll have at the end of this lesson, we can look at: variables-types-end.
2. What Is a Variable in Java?
A variable in Java is a named storage location in memory that holds a value. We can think of it as a container where our program keeps information while it runs. Variables make it possible to store data, reuse it later, and even change it as the program executes. Without variables, every calculation or operation would have to be hard-coded, which would make programs rigid and unmanageable.
Think of a variable as a labeled box where we can store a piece of information. This box has two important properties:
- A name: This is the label we use to find the box later (e.g., age).
- A type: This defines what kind of information the box can hold (e.g., a whole number value).
In Java, when we create a variable, we are telling the computer to set aside a small amount of memory to store a value. We use the variable’s name to access and modify this value throughout our program.
2.1. Assignment Operator
To use a variable in Java, we first declare it by specifying its type and a name. We can also give it an initial value at the same time.
Let’s open the Main class and add the following instructions/code to the main method:
int age;
age = 20;
In the snippet above, we declared a variable named ‘age’. On the second line, we initialized that variable with a value of 20.
We can also combine these two operations into a single one:
int age = 20;
In this example, we declare a variable, and in the same line, we initialize it to 20.
The = symbol in Java is called the assignment operator. It stores the value on the right-hand side into the variable on the left-hand side.
Once a variable has been declared and initialized, we can also re-assign another value to that:
int age = 20;
System.out.println(age);
age = 30;
System.out.println(age);
In the example above, we can see that initially the age variable was initialized with 20, and after we printed, we re-assigned that variable with the value 30.
Important: Local variables (declared inside a method, like age inside the main method) must be assigned a value before we read or use them; otherwise, the code won’t compile.
3. Types of Variables in Java
In Java, not all variables are the same. They can hold different kinds of values, and the way those values are stored in memory depends on the type of the variable. At a high level, variables fall into two categories:
- primitive variables, which store the actual value directly, and
- reference variables, which store a reference (like a memory address) to an object (a more complex data structure) in memory
In this lesson, we’ll focus mainly on primitives. We’ll cover objects and reference variables in more detail in a later lesson.
4. Primitive Variables
Java provides a special set of variable types called primitive types. These are the most basic kinds of data and are built directly into the language itself. Primitive variables store their values directly in memory.
Java has eight primitive data types, each designed to hold a specific kind of value:
| Type | Description / Usage | Range of Values | Size |
|---|---|---|---|
| int | Standard integer type. Most commonly used for whole numbers. | -2,147,483,648 to 2,147,483,647 | 32 bits (4 bytes) |
| short | Small integer values. Less common in practice. | -32,768 to 32,767 | 16 bits (2 bytes) |
| long | Large integer values. Used when int is not enough. |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 64 bits (8 bytes) |
| byte | Very small integers. Often used for raw byte data in I/O or encodings rather than for arithmetic. | -128 to 127 | 8 bits (1 byte) |
| double | Floating-point type with higher precision. Default for decimals. | Approx. 15–16 decimal digits precision | 64 bits (8 bytes) |
| float | Floating-point type with less precision, smaller memory footprint. | Approx. 6–7 decimal digits precision | 32 bits (4 bytes) |
| char | Stores a single character (letter, digit, or symbol). | Unicode characters (0 to 65,535) | 16 bits (2 bytes) |
| boolean | Logical values. Actual size is JVM-dependent for technical/performance reasons. | true or false | Not specified |
We’ll go into detail for the most common ones in the following subsections.
4.1. Integer Variable
Integers are whole numbers without any fractional part. The most commonly used integer type is int.
Below, we’ll create an int variable called playerScore:
int playerScore = 100;
System.out.println("The player’s score is:");
System.out.println(playerScore);
Running this example will produce the following output:
The player’s score is:
100
4.2. Floating-point Variable
When we need to store numbers with a fractional component, we use floating-point types. The default choice for this is double, which provides a high degree of precision:
double salary = 1000.5;
System.out.println("The worker's salary is:");
System.out.println(salary);
The output of this code will be:
The worker's salary is:
1000.5
4.3. boolean Variable
The boolean data type is used to store logical values. It can only hold one of two possible values: true or false. It is often used to track conditions in a program.
boolean closed = false;
System.out.println("Is the task closed?");
System.out.println(closed);
Executing this code will print the current state of our boolean variable:
Is the task closed?
false
4.4. char Variable
The char data type is used to store a single character, such as a letter, a digit, or a symbol. A char literal is always enclosed in single quotes (‘):
char playerGrade = 'A';
System.out.println("The player's grade is:");
System.out.println(playerGrade);
Here is the result of running the code above:
The player's grade is:
A
5. The String Type
Without going into details about classes and objects yet, let’s have a quick look at a very commonly used type in Java: the String type.
A String represents a sequence of characters, like “Hello” or “Java“.
Even though String is technically a class, Java gives it special support in the language, which is why we can work with it almost as easily as primitives. For example, we can directly assign text inside double quotes to a String variable:
String s = "Hello";
System.out.println(s);
The result of the above snippet code will be: “Hello”
6. Naming Conventions
For clean and readable code, we should follow Java’s standard rules and conventions for variable names.
Rules (must be followed):
- Names are case-sensitive. For example, name and Name are two different variables.
- Names can’t start with a digit.
- The first character must be a letter, underscore (_), or dollar sign ($) (although _ and $ are rarely used in practice).
- Subsequent characters can be letters, digits, underscores, or dollar signs.
- A variable name cannot be a reserved Java keyword (like int, public, class, abstract, or others).
Conventions (best practices to follow):
- Use camelCase for variable names: the first word is lowercase, and each subsequent word starts with an uppercase letter (e.g., creationDate, userName).
- Use meaningful, descriptive names (avoid single letters or unclear abbreviations).
- Constants are usually written in all uppercase letters, with words separated by underscores (e.g., MAX_VALUE).
- Avoid starting variable names with _ or $, even though it’s technically allowed.
Here are some examples of good variable names:
- userName
- playerScore
- emailAddress
- registry
Here are some examples of invalid or poorly styled names:
- 1stPlace (invalid, starts with a digit)
- user name (invalid, contains a space)
- class (invalid, is a reserved keyword)
- Username (poor style, should begin with a lowercase letter)
- player_score (poor style, should not contain underscores, use of camelCase instead)
7. Conclusion
In this lesson, we learned about variables in Java and explored the main types used in programming. We examined primitive variables such as int, double, char, and boolean, as well as the commonly used String type.
We also reviewed Java’s recommended naming conventions, which help us write code that is clean, consistent, and easy to read.
These concepts form the foundation for everything we’ll build going forward. As we continue, we’ll deepen our understanding of reference variables and more complex types, and see how variables interact with other core features of Java.