Learn Java

Java Variables

In all programming languages, a variable is a placeholder for storing a value of a particular type: a string, a number, or something else. In this topic, you will learn how to declare and use variables in Java programs.

Declaring and initializing

All variable types have a name (also known as an identifier) to distinguish them from each others. Before you start using a variable, you must declare it. The general form of variable declaration looks like this:

DataType variableName = initialization;

The leftmost part of this statement describes the variable, and the right part describes the value that is assigned to it.

  • The types of variables (or data type) determine what possible operations can be performed on the variable and which values can be stored in it. Here we use a non-existent data type (DataType) to demonstrate the general form of declaration.
  • Variable names (or identifiers) distinguish the variable from others. The name of a variable cannot start with a digit, so it usually starts with a letter. Always try to choose meaningful and readable names for variables to make your code easy to understand.
  • The assignment operator denoted by = is used to assign a single value or a result of an expression to a variable.
  • The initialization is a value or a result of an expression that is assigned to the variable.

According to this declaration, we can declare a variable of the type String and assign the word "java" to it:

String language = "java";

We can also declare a variable of the type int to store an integer number:

int numberOfApples = 5;

The case in the name of a variable makes a difference: language is not the same as Language.

Variables can store not only strings and numbers, but also characters and other data types.

Accessing the value of a variable

Once a variable has been declared, its value can be accessed and modified using the variable name or identifier. In the example below, we declare a variable and then print it:

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // prints Monday

It is also possible to assign a value of one variable to another variable:

int one = 1;
int num = one;
System.out.println(num); // prints 1

One important feature of variables is that they can be changed. You don't need to declare a variable again to change its value; just assign a new value to it using the = operator.

Let's declare a string variable called dayOfWeek and print its value before and after changing:

String dayOfWeek = "Monday";
System.out.println(dayOfWeek); // prints Monday

dayOfWeek = "Tuesday";
System.out.println(dayOfWeek); // prints Tuesday

There is an important restriction that you must keep in mind: you can only assign a value of the same type as the type of the initial variable. So, the following code is not correct:

int number = 10;
number = 11; // changed value of number from 10 to 11
number = "twelve"; // it does not work, gives an error

There are several alternative forms of declaration which are less commonly used in practice. Here are a couple of them shown with examples:

  • Declaring several variables of the same type as a single statement:
String language = "java", version = "8 or newer";
  • Separating declaration and initialization of a variable into two statements:
int age; // declaration
age = 35; // initialization 

However, as we have already noted, these forms are rarely used.

Type inference

Since Java 10, you can write var instead of a specific type to force automatic reference type based on the type of assigned value:

var variableName = initialization;

Here are two examples:

var language = "Java"; // String
var version = 10; // int

This feature can be a bit controversial as on the one hand, it allows your code to be more concise. On the other hand, since it doesn't indicate the type explicitly, it may affect the code readability in a negative way. For now, it's enough to understand the basic idea. We will not use type inference in our theory to avoid confusion with regards to older versions of Java.

Why is naming important?

Experienced programmers put a lot of care into naming to make their programs easy to understand. It is important because programmers spend a lot of their time getting through the code written by other programmers. If variables have bad names, even your own code will seem unclear to you in a few months.

Always try to give descriptive and concise names to all variables. As a result, any programmer will enjoy your code for a long time.

In addition, there are two sets of rules that restrict the possible names for variables.

Rules for naming variables

Java has some rules for naming variables:

  • names are case-sensitive;
  • a name can include Unicode letters, digits, and two special characters ($_);
  • a name cannot start with a digit;
  • a name must not be a keyword (classint, static keyword, etc. are illegal names).

Based on these rules, you may conclude that whitespaces are not allowed in the name of a variable.

It is important not to break these rules; otherwise, the program will not work.

Here are some valid variable names:

number, $ident, bigValue, _val, abc, k, var

Note that to keep backward compatibility, the keyword var can be used as a variable name even after Java 10 was released.

And here are some invalid ones:

@ab, 1c, !ab, class

Since Java 9 the single character _ is an invalid name for a variable, but _a and __ (double _ ) are legal names.

Naming conventions for variables

Also, there are the following conventions for naming variables:

  • if a variable name is a single word it should be in lowercase (for instance: number, price);
  • if a variable name includes multiple words it should be in lowerCamelCase, i.e. the first word should be in lowercase and each word after the first should have its first letter written in uppercase (for instance: numberOfCoins);
  • variable names should not start with _ and $ characters, although they are allowed;
  • choose a name that makes sense, e.g. score makes more sense than s, although they are both valid.

These conventions are optional, but it is strongly recommended to follow them. As we mentioned at the beginning of this lesson, they make code more readable for you and other Java programmers.

Conclusion

Variables in Java are used to store values of different data types. They need to be declared with a type and a name. Variables can be modified after declaration, but the new value must be of the same type as the old one. In Java 10, the var keyword was introduced for automatic type inference.

As a programmer, following naming rules and conventions is not just a matter of compliance, but also a practice that significantly enhances code readability and maintainability, both for yourselves and your fellow programmers. By putting in a little extra effort in choosing clear and descriptive variable names, you can make your code more accessible and user-friendly.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate