Java Journeys : Variables
What are Variables ?
Variables are like storage units in a java program and are used to store different kinds of data like numbers (integers, decimals), characters (letters), boolean values(true/false) and references to objects.
Declaring Variables
Declaring a variable in java means specifying its data type and name.
public class variables {
public static void main(String[] args) {
//Declaring variables
int count;
}
}
We’re simply informing the compiler that a variable with a certain name and type exists. However, declaring a variable doesn’t allocate any value.
Variable Initialization
Initialization is the process of assigning an initial value to a variable. Creating a variable involves both declaring it and allocating memory for it, possibly initializing it with a value.
public class variables {
public static void main(String[] args) {
//Intializing variables
int count = 100;
}
}
Naming Rules
Naming rules for variables contribute to the overall quality, readability, and maintainability of software code.
1. Must start with a letter(a-z,A-Z), underscore(_) or dollar sign($).
2. Case Sensitive : Uppercase & lowercase letters are considered different.
3. Java Keywords cannot be used : (int, double, if, else etc can’t be used).
4. Following the first character, variable names can include letters, digits (0–9), underscores, and ($).43
Variable Types
Primitive Variable Type
Primitive variables store simple values directly in memory. They represent basic data types in Java.
public class variables {
public static void main(String[] args) {
//Primitive Variable types
int num = 100;
double salary = 100.5;
char grade = 'A';
boolean isBool = true;
}
}
Reference Variable Type
Reference variables store memory addresses (references) of objects.
public class variables {
public static void main(String[] args) {
//declare reference variable to type String
String name;
//Assign a string object to reference variable
name = "Test";
}
}
In above example:
- We declare a reference variable named
name
of typeString
. - We assign the String object
"Test"
to the reference variablename
.
Conclusion
To sum up the above, Variables act as containers for storing and managing data within a program. They are categorized into two primary types: primitive types, responsible for directly holding basic values, and reference types, which store memory references to objects.
Thankyou and Happy Coding !! 😊