Introduction to Java Variables
In the programming world, the most prized possession is data. But data alone cannot exist; it needs to have a place to sit while the program processes the information. This is where Java variables come in. This article explains everything about variables in Java. If you begin your learning journey with our Java training in Chennai, you can learn more.
Overview of Variables in Java
A variable can be defined as a labeled box in the computer’s brain where you can store your data. Consider a variable to be a box in a warehouse where you can store things. Each box has a label or a name, a size and shape, and something inside the box.
When you’re working with Java programming, which is a strongly typed language, you have to declare the type of variable you want to use before you can start using the variable.
1. Anatomy of a Java Variable
To use Java variables, you have to adhere to a specific syntax in declaring or initializing the variable.
Syntax:
type variableName = value;
Type: This refers to the type of data you can store in the variable.
variableName: This refers to the unique identifier you can use to access the variable.
Value: This refers to the actual data you’re storing in the variable.
Code Example:
int speedLimit = 60;
String driverName = “Alex”;
Real-time Example:
Imagine a Digital Bank Account.
- The Account Number is a variable (Constant/Long).
- The Balance is a variable (Double) that changes with every transaction.
- The Account Holder Name is a variable (String).
Find our Java course syllabus to get started.
2. Types of Java Variables
Java divides its variables into various types based on where they are defined. These are also differentiated on the basis of their lifecycle. This is where programming concepts like memory management come into play.
A. Local Variables
The local variables are defined within a method, a constructor, or a block. Their lifecycle begins when they enter the block and ends when they come out of the block.
- Scope: These can only be accessed within that specific method.
- Default Value: These do not have any default values. They must be initialized.
B. Instance Variables (Global Variables)
The instance variables are defined within a class outside any method. These are also known as global variables. This is because they have unique values for every object of that class.
- Scope: These can be accessed within any method of that class.
- Default Value: These have default values. For example, if they are numbers, they will have a default value of 0. If they are objects, they will have a default value of null.
C. Static Variables (Class Variables)
Variables declared using the static keyword inside a class. Unlike instance variables, static variables are stored in one copy regardless of how many objects are created.
- Scope: All instances of a class can access static variables.
- Use Case: A variable to keep a count of total users of an application.
Learn Java variables comprehensively with our Java tutorial for beginners.
3. Data Types: The “Shapes” of Variables
Because Java is Statically Typed, you must declare the data type. There are two categories of data types in Java. They are divided into Primitive and Non-Primitive data types.
Primitive Data Types
These data types are predefined by Java.
| Data Type | Size | Description | Example |
| byte | 1 byte | Stores whole numbers from -128 to 127 | byte age = 25; |
| int | 4 bytes | Stores whole numbers up to 2 billion | int salary = 50000; |
| long | 8 bytes | For very large whole numbers | long distance = 999999L; |
| float | 4 bytes | Stores fractional numbers (6-7 digits) | float price = 19.99f; |
| double | 8 bytes | Stores fractional numbers (15 digits) | double pi = 3.14159265; |
| boolean | 1 bit | Stores true or false | boolean isActive = true; |
| char | 2 bytes | Stores a single character/ASCII | char grade = ‘A’; |
Non-Primitive (Reference) Data Types
This consists of objects and is not predefined, except for String.
4. Rules for Naming Java Variables
To make the code clean, avoid compilation errors, and ensure the program runs smoothly, it is essential to adhere to the following rules:
- Case Sensitivity: myValue and myvalue are two different variables.
- Characters: Can contain letters, digits, underscores (_), and dollar signs ($).
- No Start with Digits: 1stValue is not valid, whereas value1 is valid.
- No Reserved Keywords: A variable cannot be declared as int, class, or static.
- Camel Case: studentFirstName is the standard way to write variable names.
Gain expertise with Java variables through our Java interview questions and answers.
5. Variable Shadowing and Scope
The scope of a variable determines the region in which the variable is available.
- Method Scope: Variables declared in the method.
- Block Scope: Variables declared in { } (like a for loop)
Variable shadowing occurs when the local variable has the same name as the instance variable. The local variable shadows the instance variable.
public class Test {
int x = 10; // Instance variable
void display() {
int x = 20; // Local variable shadows instance variable
System.out.println(x); // Prints 20
System.out.println(this.x); // Prints 10 using ‘this’
}
}
Obtain job-ready skills for industry-standard Java Developer Salary for Freshers and Experienced Professionals.
6. The final Keyword (Constants)
If you would like to define a variable whose value cannot be changed once it has been assigned, then the final keyword is utilized. In professional Java programming, they are always in ALL CAPS.
Real-time Example: $PI$, MAX_LOGIN_ATTEMPTS.
final double PI = 3.14159;
// PI = 3.15; // This would cause a compilation error
7. Memory Management: Stack vs. Heap
Where are Java variables actually stored?
- Stack Memory: This is where the primitives and references to objects are stored. This is where local variables are stored.
- Heap Memory: This is where the objects are actually stored.
8. Best Practice for Using Variables
- Initialize Variables: Always initialize your local variables with a value so that errors are not made.
- Use Meaningful Names: Avoid using “a,” “b,” “c.” Use “interestRate,” “userEmail,” etc.
- Minimize the Scope of Your Variables: Declare your variables as local as possible so that the memory usage is minimized.
- Use double over float: In modern applications, the standard is always double unless the memory is extremely constrained.
Conclusion
Java variables are the basis of all Java code. By mastering local variables, instance variables, and static variables, and knowing what data type to use for your variable, you can write Java code that is memory-friendly and easy to read. Whether working with a Boolean flag or a complex Object variable, Java variables are what allow your Java code to be dynamic and interactive. Explore more courses in our software training institute in Chennai.
