A program or application variable is a data container that stores data values during program execution. In strictly typed languages such as Java, every variable is assigned a data type that designates the type and quantity of value(s) it can hold. This programming tutorial will provide an overview of variable rules, their types, how to declare, initialize, and assign values to variables, as well as variable naming conventions in Java.
Want to learn Java programming in an online course environment? We have list of the Best Online Courses to Learn Java to help get you started.
Java Variables Best Practices
Before using variables in your own programs, we should first cover the ground rules governing Java variables:
- A variable is the basic, atomic, unit of storage in a program. Although you have have a variable that contains other variables, such as an arrayeach element must consist of one variable.
- As the name suggests, the value stored in a variable can be changed during program execution.
- A variable is a name given to a memory location. Hence, all the operations done on the variable affect that memory location.
- In Java, all variables must be declared before use.
Variable Declaration, Initialization and Assignment
As mentioned above, a variable must be declared before you can use it. To do that, we need to provide two things:
- DataType: Type of data that can be stored in this variable.
- DataName: Name given to the variable.
Here are a few examples:
int count; String name; date today;
Once declared, a variable can be assigned a value in one of two ways:
- Variable initialization at declaration time.
- Assigning a value later on.
We can initialize a variable in the same statement as it is declared by adding the equals (=) assignment operator and a value. Here are the previous three variable declarations with initialization values:
int count = 0; String name = “rob”; Date today = new Date();
Note: It is generally a good practice to initialize your variables, so try to do so whenever possible.
Whether initialized or not, you can update a variable’s value at any time with either a literal value or another variable. Here are a couple of examples of how to change a variable’s data in Java:
// Declaring and initializing integer variables int topSpeed = 100, time = 10, speed; // later on in the code… time = 20; speed = topSpeed;
Reading: The Best Tools for Remote Developers
What are the Types of Variables in Java?
There are three types of variables in Java:
- local variables
- Instance variables
- Static variables
Local variables in Java
A variable declared inside the body of a method is referred to as a local variable. You can use this variable only within that method and the other methods in the class are oblivious that the variable even exists.
Instance Variables in Java
A variable declared inside a class but outside the body of any method is called an instance variable. It is named as such because its value is specific to that class instance and is not shared among instances.
Static Variables in Java
A variable that is declared with the “static” keyword is called a static variable. This allows a single copy of the variable to be shared among all the instances of the class. A ramification of making a variable static is that memory allocation happens only once when the class is first loaded into memory. Another side effect is that programmers do not need to instantiate the class before accessing it.
Here is some example code that shows the three types of variable and how to use them in Java:
public class VariableTypesExample { static int a = 100; //static variable void method() { int b = 90; //local variable } public static void main(String args[]) { int data = 50; //instance variable } } //use the static variable int a2 = VariableTypesExample.a;
Variable naming conventions in Java
Every programming language has its own set of rules and conventions regarding what characters variable names may contain, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:
- It should begin with a lowercase letter.
- There may (and should!) be more than one letter, but without any spaces between them; in other words, no whitespace.
- Digits may be used but only after at least one letter.
- No special symbol can be used except the underscore (_) and currency ($) icon. When multiple words are needed, camelCase should be utilized.
- No keywords or command can be used as a variable name. These include “class“, “internal“, “new“, and “void“.
- All statements in java language are case sensitive. Thus a variable A (in uppercase) is considered different from a variable declared a (in lowercase).
Here are some valid and invalid variable names. See if you can spot the bad ones!
- myvar
- myVar
- MYVAR
- _myVar
- 0u812
- food+nonfood
- $myVar
- age_
- myVar1
- myVar_1
In the above list, all the permutations of “myvar” are valid, while numbers 5, 6, and 8 are invalid. Here’s why:
- 0u812: Starts with a number.
- food+nonfood: The plus symbol (+) is not allowed.
- age_: The underscore cannot be the last character.
Beyond that, it is common practice to use camelCase for variable names. Moreover, some developers start their instance variable names with the underscore character to denote that it is private; while it is technically legal to begin your variable’s name with “_“, this practice is discouraged by Oracle.
Reserved keywords that should not be used as variable names are: abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, internal, interface, long, native, new, package, private, protected, public, return, short, static, stitchfp, great, switch, synchronized, this, throw, throws, transient, try, void, volatileand while.
Final Thoughts on Java Variables
In this programming tutorial, we learned how to work with variables in Java, from declaring, initializing, and assigning values to them, to variable naming conventions. In the next tutorial, we will be following up with a rundown on Java Data Types, so that you will be better equipped to match variables to their appropriate type.