In every programming language, variables are fundamental building blocks that allow programs to store and manipulate data. These are necessary for data representation which in return helps users of the data efficiently work with that data. In Java, variables have constraints on how they are defined and are also categorised differently concerning type, scope, and requirements for storage.
In this article, we will learn in detail about variables in Java, their definition, how to declare and assign them, the different classes of variables based on scope and lifetime, and the differences between static and local variables. We’ll also learn about working with different variables through code examples.
What are Variables in Java?
Variables are named memory locations that hold values. Variables are data containers containing the data values during Java program execution. Each variable in Java has a type that defines what data it can hold. For example, integers, floating point numbers, characters, etc. The type also plays a role in determining the type of operation that can be carried out on the variable.
Variables work to enhance and improve the program because data can be stored, accessed, and used when required. For example, it is similar to a box with a label at a warehouse where boxes are kept: the box (the variable) is designed with its label stating the box content types (the data type). Some contents can be placed in the box (initialization), and later on, the contents can be removed and substituted with others of a similar nature.
Each variable in Java has a data type that specifies the type of data it can store.
Java is a statically typed language, meaning that each variable must be declared with a data type before it can be used.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
How to Declare and Initialise Variables in Java?
A variable must be declared for the program to use it, along with its data type and name. Assigning a variable value is known as initialization. In Java, before utilisation of the variable, it must be declared, and such declaration is followed by initialization which must be done at the time of declaration or sometime later.
Declare Variables in Java
In Java, a variable has to be declared before it can be utilised. Variable declaration is required before using any variable in Java. Variable creation in Java involves assigning a certain part of computer memory which is labelled using the name of the variable to avoid confusion. A declaration gives a variable a unique identifier (name) and informs the compiler about the kind of data it will hold.
Syntax:
dataType variableName;
Here,
dataType: The type of the variable (e.g., int, double, String, etc.).
variableName: The name of the variable.
Initialize Variables in Java
Initialization refers to assigning a value to the variable when it’s declared or afterward. The variable must first be initialised before it may be used in procedures or operations. Errors may arise from a variable that lacks an initial value, particularly in the case of local variables. There are two types of variable initialization: Implicit and Explicit.
Explicit Initialization: When a variable is assigned a value at the moment of declaration, it is known as explicit initialization.
Implicit Initialization: When a value is subsequently assigned to the variable during processing, it is known as implicit initialization.
Syntax:
variableName = value;
Here,
value: The value assigned to the variable.
Rules for Declaring and Initialising Variables in Java
Java has several rules for declaring and initialising variables that need to be followed while working with them. These are:
Variables Must Be Declared Before Use: All occurrences of new or initialization of this type must be followed by a definition of the variable. There will be an error if this undeclared variable is used while compiling.
Scope of Variable Names Must Be Unique: One of the fundamental properties of a variable is that it has a name and that this name is unique within the confines of this particular scope. Though it is permissible to define variables with the same name in different methods or blocks, two variables with the same name cannot be defined in the same block or method.
Variable Names Must Follow Naming Conventions: Java provides rules for naming variables, known as naming conventions. Such as :
Start with a letter, underscore (_), or dollar sign ($).
No numbers at the start.
No spaces in the naming convention.
No reserved keywords.
Initialization of Local Variables Is Required:
Before being utilised, local variables need to be explicitly initialised. When you try to utilise a local variable that has been declared but not initialised, the compiler will generate an error.
Multiple Variables Declaration
Java allows you to declare multiple variables of the same type in a single line. Here is an example of the same:
int a = 10, b = 20, c = 30;
This is useful when you need to declare several variables of the same type and want to keep your code concise.
Java offers a variety of variable types, each with a distinct function in a given situation. Let’s see the different types of Java variables.
Variables in Java are divided into three types according to their lifetime, scope, and behaviour inside a class or function. These are:
Local variables
Instance variables
Static/Class variables
In Java programs, each of these variables has a distinct purpose. Understanding the differences among these variable types is essential for memory management, access control, and the creation of effective programs.
Local Variables
Local variables are those variables that are defined within methods, constructors, or code blocks. The local variables are created when a method/constructor/block is called and is destroyed as soon as that method is done executing or when the call returns from the function. Local variables are accessible only within the method or block in which they are defined.
Key Characteristics:
Scope: Scope refers to the extent that a certain variable is obtained and is particularly defined in this context with a local variable. A variable is said to be destroyed immediately after the procedure or block containing the variable execution has been completed and which no individual will have access anymore.
Lifetime: Local variables come into existence during the execution of the method or a code block and are destroyed after the execution of that method or code block is over.
Default Value: Local variables are also not set as default values. For you to use a variable locally, you have to set a value to it since you cannot use it otherwise you will get a compilation error.
Syntax:
public void methodName() {
int localVar = 10; // local variable
}
Here, the localVar is declared inside the methodName() method, which is only accessible within the method it is declared.
Example:
public class MyClass {
public void computeSum() {
// Declaring two local variables of data type int
int n1 = 300; // Initializing n1
int n2 = 200; // Initializing n2
// Declaring another local variable to store the sum
int sum; // sum is declared but not yet initialised
// Calculating the sum of n1 and n2
sum = n1 + n2; // sum is now initialised with the result
// Display output
System.out.println("The sum is: " + sum);
}
public void printName() {
// Declaring a local variable of data type String
String name = "Hello World"; // Initializing the variable with a value
// Display output
System.out.println("My name is: " + name);
}
public static void main(String[] args) {
// Creating an instance of MyClass class
MyClass obj = new MyClass();
// Calling the computeSum() method to execute the code
obj.computeSum();
// Calling the printName() method to execute the code
obj.printName();
}
}
Output:
The sum is: 500
My name is: Hello World
Explanation:
In this example, we have a class MyClass that contains a method called computeSum(). Within this method, three local variables are declared: n1, n2, and sum, where n1 and n2 are initialised with some values.
The sum variable is defined after n1 and n2 to store the value of their addition.
Finally, the sum is printed to the console.
Local variables exist only within the method’s scope and are created when the method is called. They are destroyed once the method execution is completed.
Instance Variables
Instance variables are the variables defined in a class but outside the scope of the methods/constructors/code blocks. They are inside universally themselves. Instance variables are defined without the STATIC keyword. Instance variables can only be accessed by creating objects. A variable of this type is designed specifically to hold the unique characters of an object.
Key Characteristics:
Scope: All methods in the class have access to instance variables. Their values are particular to the class’s object, for instance.
Lifetime: Instance variables are created when an object is instantiated and destroyed when the object is garbage-collected.
Visibility: All instance variables are accessible to all the methods, constructors, and blocks within the class in which they are declared. These variables are also advisable to be changed to private since they control the state of the object to prevent outside interference.
Default Value: If an instance variable is not initialised, Java assigns a default value. For example, object references default to null, numerical variables default to 0, etc.
Access Control: In case subclassing is required and instance variables visibility is required, access modifiers such as protected and public can be used. In such a way you will be able to regulate access as per the requirement.
Syntax:
class ClassName {
int instanceVariable; // instance variable
}
Here, the instanceVariable is declared inside the ClassName() class.
Example:
public class MyClass {
// Declaring instance variables
private String userName; // Instance variable to store the name, private for encapsulation
private int userAge; // Instance variable to store the age, private for encapsulation
// Constructor to initialise instance variables
public MyClass(String name, int age) {
this.userName = name; // 'this' keyword refers to the current object's instance variable
this.userAge = age; // Initializing the instance variable age
}
// Method to display the details of the person
public void showDetails() {
// Printing instance variables to the console
System.out.println("Name: " + userName); // Output: Name: [name]
System.out.println("Age: " + userAge); // Output: Age: [age]
}
public static void main(String[] args) {
// Creating an instance i.e., the object of the class MyClass
MyClass p1 = new MyClass("John Roy", 25);
MyClass p2 = new MyClass("Aryan Singh", 30);
MyClass p3 = new MyClass("Rishi", 22);
MyClass p4 = new MyClass("Raj", 28);
MyClass p5 = new MyClass("Rohan", 29);
// Calling the method to display the person's details
p1.showDetails();
p2.showDetails();
p3.showDetails();
p4.showDetails();
p5.showDetails();
}
}
In this example, the MyClass class has two instance variables, userName and userAge and these are private since they are not made directly accessible to users of the class.
These variables are set through a constructor as soon as an object of the class is created.
The constructor employs the `this` keyword to distinguish between the parameters of the constructor and the instance variables.
The showDetails() method is used to display the object instance data members in the console.
Instance variables are data members that belong to an object, and garbage collection determines the lifespan of these variables.
Static/Class Variables
Static variables, also known as class variables, are shared among all instances of a class. Static variables are those that have been declared as static in type. They are not declared as local variables. The static variable can be made in one copy and shared by every instance of the class. Static variables are created at the beginning and automatically destroyed after program execution. Static variables are linked to the class instead of an instance of the class and are declared using the static keyword.
Key Characteristics:
Scope: Static variables can be accessible from anywhere within the class, and they can also be accessed by external code using the class name, without creating an object.
Lifetime: Static variables exist as long as the class is loaded in memory, and they are initialised only once when the class is first loaded.
Standard Format: When static variables are made public, static, and final (that the variables are constants), it is the convention that their names are written all in capital letters. This is for the purpose if I have to mention the constants in the code they appear different.
Default Value: If static variables are not explicitly initialised, they are initialised with default values, just like instance variables.
Memory Storage: Static variables are kept in a distinct section of the memory known as static memory, separate from storage, for instance, variables or storage for local variables.
Syntax:
class ClassName {
static int staticVariable; // static variable
}
Here, the staticVariable is declared inside the ClassName() class.
Example:
public class MyClass {
// Declaring a static variable
private static int cnt = 0; // Static variable to count the number of objects created
// Constructor to increment the object count whenever an object is created
public MyClass() {
cnt++; // Increment the static variable for each object created
}
// Static method to display the current object count
public static void showCount() {
// Display the object count
System.out.println("The total number of objects created is: " + cnt);
}
public static void main(String[] args) {
// Creating multiple instances of MyClass
MyClass obj1 = new MyClass(); // First object created
MyClass obj2 = new MyClass(); // Second object created
MyClass obj3 = new MyClass(); // Third object created
MyClass obj4 = new MyClass(); // Fourth object created
// Calling the static method to display the object count
MyClass.showCount();
}
}
Output:
The total number of objects created is: 4
Explanation:
In the MyClass class, we declare a static variable named `cnt` to keep track of how many objects of the class have been created. This static variable is shared among all instances of the class.
The very first time a new object is created using the constructor, the `cnt` is increased.
The static method showCount() displays how many objects have been created up until the present moment.
The main() method creates three instances of the class, clearly showing that a static variable is common to all and retains its value across all instances.
Static variables are program-scoped and exist as long as the program is running and are attached to the class instead of the particular object.
Difference Between Static and Local Variables
The key differences between static and local variables in Java are as follows:
Criteria
Static Variables
Local Variables
Declaration
The static variables in Java are declared using the `static` keyword inside the class.
The local variables in Java are declared inside a method or a block.
Scope
Static variable is available to all instances of a class.
The scope of the local variable is limited to the block in which it’s declared.
Lifetime
The static variables exist for the lifetime of the class.
They exist only during the method/block execution.
Memory Allocation
Memory is allocated once when the class is loaded.
Memory is allocated each time the method/block is invoked.
Access
Can be accessed using the class name.
Can only be accessed within the method or block.
Conclusion
Within the Java programming language, variables facilitate data retention and control of the sequence of program execution as well as other operations. In Java, variables are important objects that hold data for programmatic manipulation and utilisation. Local, instance, and class (static) variables are the three primary types of variables in Java. Java variables also have restrictions in terms of scope, lifetime, and initialization, which are meant to help in the management of memory as well as improve performance.
Having proper knowledge about the working of variables in Java should enable any programmer to use instance and static variables wisely and restrict local variables to certain areas only to reduce errors and make the code cleaner and more efficient. Are you eager to learn more about Java? Then, consider pursuing HeroVired’s Full Stack Development course.
FAQs
What are variables in Java?
In Java, a variable is an object that is used to hold values. Every variable has a declaration with a specific data type such as int, float, String, etc. so the value to be stored is restricted within these bounds. Variables are called the containers for data and help in processing data in the operations performed by the program.
How to declare and initialise variables in Java?
Variables in Java are declared by specifying a data type followed by the variable name. Initialization means assigning a value to the variable. For example:
Syntax:
int num; // Declaration
num = 10; // Initialization
What are the types of variables in Java?
Variables in Java can be divided into three types:
Local Variables: These are declared within methods, constructors, or blocks and have scope exclusively to that part of the code.
Instance Variables: They are declared in a class but out of the logic methods within a class instance.
Static Variables: They are declared with the static keyword and shared among all instances of a class.
Can final variables be modified in Java?
No, a final variable must also have been assigned a value and no changes can be made on that variable. These variables are placed similarly within the code and cannot be altered throughout the whole process.
What are the naming conventions for Java variables?
The name of a variable should begin with a letter or underscore (_) and can contain any other letter or a number following that. All normal variable names should be camel-cased, for example myVariable. In writing down constants (Static final variables) all letters need to be in uppercase with the use of space being replaced with an underscore.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.