Introduction
In this lesson, you will work with Java variables: how to declare and initialize them with appropriate data types, how to distinguish between local and global (instance/static) variables, how to apply naming conventions that improve readability, and how to use type casting to convert between data types. You will also see small programs that show these ideas in action.
What Is a Variable in Java?
A variable is a named storage location in memory that holds a value while your program runs. Each variable has:
- A data type (what kind of value it can store)
- A name (identifier)
- An optional initial value when declared
In Java, every variable must have a declared type.
Declaring and Initializing Variables
Basic Syntax
<data_type> variableName; // declaration
<data_type> variableName = value; // declaration + initialization
Examples of declarations and initializations:
int count = 10; // integer
double price = 19.99; // decimal number
char grade = 'A'; // character
boolean isActive = true; // boolean
String message = "Hello"; // reference type (class)
Example: Declaring and Initializing Different Types
public class VariableDemo {
public static void main(String[] args) {
int age = 25; // whole number
double temperature = 36.6; // decimal
boolean isJavaFun = true; // true/false
char initial = 'J'; // single character
String language = "Java"; // text
System.out.println("Age: " + age);
System.out.println("Temperature: " + temperature);
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Initial: " + initial);
System.out.println("Language: " + language);
}
}
// Output
Age: 25
Temperature: 36.6
Is Java fun? true
Initial: J
Language: Java
Explanation:
- Each variable is declared with a type and initialized with a value.
System.out.printlnshows how to use variables in expressions and output.
Local vs Global Variables
Java does not use the term "global" in the language specification, but in practice we talk about:
- Local variables – declared inside a method, constructor, or block
- Instance variables – declared inside a class, but outside any method (require an object)
- Static variables – declared with
staticinside a class; shared by all objects of that class
Local Variables
Characteristics:
- Exist only within the method or block where they are declared
- Cannot be accessed outside that scope
- Must be initialized before use
Instance and Static (Class) Variables
- Instance variables hold state per object.
- Static variables hold state shared across all objects of the class.
Example: Local vs Instance vs Static
public class Counter {
// Static (class) variable - shared
static int totalCounters = 0;
// Instance variable - per object
private int value;
public Counter(int start) {
value = start; // instance variable
totalCounters++; // modify static variable
}
public void increment() {
int step = 1; // local variable
value = value + step; // use local + instance
}
public int getValue() {
return value;
}
public static void main(String[] args) {
Counter c1 = new Counter(0);
Counter c2 = new Counter(10);
c1.increment();
c2.increment();
c2.increment();
System.out.println("c1 value: " + c1.getValue());
System.out.println("c2 value: " + c2.getValue());
System.out.println("Total counters created: " + Counter.totalCounters);
}
}
// Output
c1 value: 1
c2 value: 12
Total counters created: 2
Explanation:
totalCountersis a static variable; bothc1andc2affect the same shared value.valueis an instance variable; eachCounterobject has its ownvalue.stepinsideincrement()is a local variable; it exists only while the method runs.
Variable Naming Conventions
Readable variable names make your code easier to understand and maintain. Java follows standard conventions:
General Rules (Syntax)
- Names can contain letters, digits,
_, and$. - Cannot start with a digit.
- Cannot be a reserved keyword (
int,class,public, etc.).
Java Conventions (Style)
- Use camelCase for variables:
userName,totalAmount. - Name should be meaningful, not just
x,y(unless for short-lived local uses, like loop counters). - Constants (declared
static final) useUPPER_SNAKE_CASE, e.g.,MAX_USERS.
Example: Good vs Poor Naming
public class NamingExample {
public static void main(String[] args) {
// Poor names
int a = 5;
int b = 10;
// Better names
int minAge = 5;
int maxAge = 10;
System.out.println("Poor: a = " + a + ", b = " + b);
System.out.println("Better: minAge = " + minAge + ", maxAge = " + maxAge);
}
}
// Output
Poor: a = 5, b = 10
Better: minAge = 5, maxAge = 10
Explanation:
aandbtell you nothing about their purpose.minAgeandmaxAgeclearly communicate meaning.
Summary / Key Takeaways
In this lesson on Java Variables, you have learned:
- Variables must be declared with a specific data type, and can be initialized at the point of declaration to store values used in expressions and output.
- Local variables exist only within methods or blocks, while instance and static variables are defined at the class level, representing per-object state and shared state respectively.
- Static variables (class variables) are shared across all instances, whereas instance variables hold unique values for each object created from the class.
- Meaningful, camelCase names improve code readability, and constants are typically written in
UPPER_SNAKE_CASEto distinguish them from regular variables. - Variable naming must follow Java’s identifier rules, avoiding reserved keywords and starting names with letters, underscore, or dollar sign instead of digits.
- Implicit (widening) casting happens automatically when converting from a smaller to a larger numeric type, preserving the value without manual syntax.
- Explicit (narrowing) casting is required when converting from a larger to a smaller type, and may result in loss of precision, such as truncating decimal parts.
- Combining appropriate data types, naming, scope, and casting allows you to model program data clearly and safely while maintaining maintainable, readable Java code.