Skip to main content

Variables

Table of Contents​

  1. Introduction to Variables
  2. Variable Declaration & Initialization
  3. Data Types
  4. Variable Scopes
  5. Type Conversion & Casting
  6. Final Variables
  7. Variable Naming Conventions
  8. Practical Examples
  9. Best Practices

1. Introduction to Variables​

Variables are named containers that store data in Java programs. They:

  • Have a specific data type
  • Occupies memory space
  • Follow Java's naming conventions
  • Have defined scope and lifetime

Key characteristics:

  • Name: Identifier for the variable
  • Type: Determines size and operations
  • Value: Data stored in memory
  • Memory Address: Location in RAM

2. Variable Declaration & Initialization​

Declaration Syntax​

type identifier;

Initialization​

identifier = value;

Combined Declaration & Initialization​

type identifier = value;

Example​

int age; // Declaration
age = 30; // Initialization
double pi = 3.14; // Combined

3. Data Types​

Primitive Types​

TypeSizeRangeDefaultExample
byte8 bits-128 to 1270byte b = 100;
short16 bits-32,768 to 32,7670short s = 500;
int32 bits-2Β³ΒΉ to 2Β³ΒΉ-10int i = 100000;
long64 bits-2⁢³ to 2⁢³-10Llong l = 10000000000L;
float32 bits±3.4e⁻³⁸ to ±3.4e³⁸0.0ffloat f = 3.14f;
double64 bits±1.7e⁻³⁰⁸ to ±1.7e³⁰⁸0.0ddouble d = 3.141592;
char16 bitsUnicode characters'\u0000'char c = 'A';
boolean1 bittrue/falsefalseboolean flag = true;

Reference Types​

  • Store references to objects
  • Default value: null
  • Examples:
String name = "Java";
int[] numbers = {1, 2, 3};
Object obj = new Object();

4. Variable Scopes​

Class Variables (Static)​

class Counter {
static int count = 0; // Shared across all instances
}

Instance Variables​

class Person {
String name; // Unique to each instance
}

Local Variables​

void calculate() {
int result = 0; // Method-scoped
}

Block Variables​

for(int i=0; i<10; i++) { // Loop-scoped
System.out.println(i);
}

Scope Comparison​

ScopeDeclaration LocationLifetimeAccess ModifiersMemory Allocation
ClassInside class, with staticClass loading to unloadingYesMethod Area
InstanceInside class, no staticObject creation to GCYesHeap
LocalInside method/blockBlock executionNoStack
ParameterMethod parametersMethod executionNoStack

5. Type Conversion & Casting​

Widening (Automatic)​

int i = 100;
long l = i; // Automatic conversion

Narrowing (Explicit Casting)​

double d = 100.04;
long l = (long) d; // Explicit cast

Type Promotion Rules​

  1. byte β†’ short β†’ int β†’ long β†’ float β†’ double
  2. char β†’ int

Example​

byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double result = (f * b) + (i / c) - (s * 0.1);
// b promoted to float, c to int, s to double

6. Final Variables​

final creates immutable references (constants)

final double PI = 3.14159;
final int MAX_USERS = 1000;

Rules:

  • Must be initialized
  • Cannot be reassigned
  • Convention: UPPER_SNAKE_CASE

7. Variable Naming Conventions​

  1. Start with letter, $, or _ (not recommended)
  2. Subsequent characters: letters, digits, $, _
  3. Case-sensitive
  4. Avoid reserved keywords
  5. Follow camelCase convention

Examples:

int studentCount; // Good
String firstName; // Good
double accountBalance; // Good
int _temp; // Avoid
String $name; // Avoid

8. Practical Examples​

Example 1: Variable Usage​

public class Circle {
// Class variable
static final double PI = 3.14159;

// Instance variable
double radius;

public Circle(double r) {
// Parameter variable
radius = r;
}

public double area() {
// Local variable
double result = PI * radius * radius;
return result;
}

public static void main(String[] args) {
// Local variable
Circle myCircle = new Circle(5.0);
System.out.println("Area: " + myCircle.area());
}
}

Example 2: Type Casting​

public class TypeConversion {
public static void main(String[] args) {
int intValue = 100;

// Widening conversion
long longValue = intValue;

// Narrowing conversion
byte byteValue = (byte) intValue;

System.out.println("Original int: " + intValue);
System.out.println("Widened long: " + longValue);
System.out.println("Narrowed byte: " + byteValue);

// Special case: float to int
float floatValue = 123.456f;
int truncated = (int) floatValue;
System.out.println("Truncated float: " + truncated);
}
}

Example 3: Scope Demonstration​

public class ScopeDemo {
static int classVar = 10; // Class-level

int instanceVar = 20; // Instance-level

public void demoMethod(int paramVar) { // Parameter
int localVar = 30; // Method-level local

if(true) {
int blockVar = 40; // Block-level
System.out.println("Block variable: " + blockVar);
}

// blockVar not accessible here
System.out.println("Local variable: " + localVar);
System.out.println("Parameter: " + paramVar);
}

public static void main(String[] args) {
ScopeDemo demo = new ScopeDemo();
demo.demoMethod(50);

System.out.println("Class variable: " + classVar);
System.out.println("Instance variable: " + demo.instanceVar);
}
}

9. Best Practices​

  1. Initialize variables during declaration
  2. Use meaningful names (avoid single-letter names except in loops)
  3. Declare variables close to their usage
  4. Limit variable scope as much as possible
  5. Use final for constants
  6. Avoid public instance variables (use encapsulation)
  7. Prefer primitive types for performance-critical code
  8. Be cautious with implicit type conversions
  9. Use var for local variables when type is obvious (Java 10+)
var list = new ArrayList<String>(); // Type inferred
  1. Avoid global variables where possible

Common Pitfalls​

  • Using uninitialized local variables
  • Shadowing variables (local vs instance)
  • Memory leaks with reference types
  • Overflow/underflow in numeric operations
  • Precision loss in floating-point operations