Skip to main content

Variables & Data Types

🎯 Core Concept​

A Variable is a named storage location in computer memory that holds a value which can be changed during program execution. Data Types define the type of data that can be stored in a variable and determine what operations can be performed on that data.

🏷️ Data Types​

Primitive Data Types​

Basic data types built into the programming language.

Integer Types​

Whole numbers without decimal points.

# Python
age = 25 # int
count = 1000000 # int (unlimited size)
// Java
byte age = 25; // 8-bit (-128 to 127)
short count = 1000; // 16-bit (-32,768 to 32,767)
int population = 1000000; // 32-bit
long bigNumber = 1000000000L; // 64-bit

Floating-Point Types​

Numbers with decimal points.

# Python
price = 19.99 # float (64-bit double precision)
temperature = -5.5 # float
// Java
float price = 19.99f; // 32-bit
double temperature = -5.5; // 64-bit

Character Types​

Single characters.

# Python
grade = 'A' # str (Python uses strings)
// Java
char grade = 'A'; // 16-bit Unicode

Boolean Types​

True or false values.

# Python
is_student = True # bool
is_graduated = False # bool
// Java
boolean isStudent = true; // true or false
boolean isGraduated = false;

Composite Data Types​

Data types that can hold multiple values.

Strings​

Sequences of characters.

# Python
name = "John Doe" # str
message = 'Hello' # str
// Java
String name = "John Doe"; // Immutable
String message = "Hello";

Arrays​

Fixed-size collections of same-type elements.

# Python (Lists)
scores = [85, 90, 78, 92] # list
names = ["Alice", "Bob"] # list
// Java
int[] scores = {85, 90, 78, 92}; // Fixed size
String[] names = {"Alice", "Bob"}; // Fixed size

🏷️ Variable Declaration & Initialization​

Declaration​

Creating a variable with a specific data type.

# Python (Dynamic typing)
age = 25 # Type inferred automatically
name = "John" # Type inferred automatically
// Java (Static typing)
int age; // Declaration only
String name; // Declaration only

// Declaration with initialization
int age = 25; // Declaration + initialization
String name = "John"; // Declaration + initialization

Initialization​

Assigning an initial value to a variable.

# Python
# Multiple assignment
x, y, z = 10, 20, 30

# Chain assignment
a = b = c = 0
// Java
int x = 10, y = 20, z = 30; // Multiple declarations

// Constants (final variables)
final double PI = 3.14159;

πŸŽ“ Academic Context​

Exam Focus Points​

  • Definition: Named storage location with data type
  • Data Types: Primitive vs Composite
  • Declaration vs Initialization: Creating vs assigning values
  • Static vs Dynamic Typing: Type checking at compile vs runtime

Viva Questions​

  • What is the difference between declaration and initialization?
  • Why do we need different data types?
  • What is type safety?
  • When would you use a constant instead of a variable?

Mark Distribution​

  • Short Answers: 2-3 marks (definitions, data types)
  • Long Questions: 5 marks (examples, type safety)
  • Practical: Variable declaration and usage

Common Exam Topics​

  • Variable naming conventions
  • Data type selection
  • Type conversion (implicit/explicit)
  • Constant declarations
  • Scope of variables

πŸ’» Professional Context​

Best Practices​

  1. Naming Conventions

    • Use descriptive, meaningful names
    • Follow language-specific conventions (camelCase, snake_case)
    • Avoid single-letter variables except for loop counters
  2. Type Selection

    • Choose the most appropriate data type for the data
    • Consider memory usage and performance
    • Use appropriate size for numeric types
  3. Initialization

    • Always initialize variables before use
    • Use meaningful default values
    • Consider using constants for fixed values
  4. Scope Management

    • Declare variables in the smallest possible scope
    • Avoid global variables when possible
    • Use access modifiers appropriately (private, protected, public)

Professional Examples​

# Professional variable usage with type hints
from typing import List, Optional

class StudentManager:
def __init__(self):
self.students: List[dict] = []
self.max_students: int = 100
self.is_active: bool = True

def add_student(self, name: str, age: int, grade: float) -> bool:
"""Add a new student with validation"""
if len(self.students) >= self.max_students:
return False

if not (10 <= age <= 100): # Age validation
return False

if not (0 <= grade <= 100): # Grade validation
return False

student = {
'id': len(self.students) + 1,
'name': name.strip(),
'age': age,
'grade': grade,
'enrollment_date': datetime.now().isoformat()
}

self.students.append(student)
return True
// Professional variable usage with proper encapsulation
public class StudentManager {
// Instance variables with proper access modifiers
private List<Student> students;
private final int maxStudents;
private boolean isActive;

// Constants
private static final int MIN_AGE = 10;
private static final int MAX_AGE = 100;
private static final double MIN_GRADE = 0.0;
private static final double MAX_GRADE = 100.0;

public StudentManager(int maxStudents) {
this.students = new ArrayList<>();
this.maxStudents = maxStudents;
this.isActive = true;
}

public boolean addStudent(String name, int age, double grade) {
// Input validation
if (students.size() >= maxStudents) {
return false;
}

if (age < MIN_AGE || age > MAX_AGE) {
return false;
}

if (grade < MIN_GRADE || grade > MAX_GRADE) {
return false;
}

// Create student object
Student student = new Student(
students.size() + 1,
name.trim(),
age,
grade,
LocalDate.now()
);

students.add(student);
return true;
}
}

πŸ”„ Type Conversion​

Implicit Conversion (Widening)​

Automatic conversion from smaller to larger types.

# Python (automatic)
int_value = 10
float_value = int_value + 0.5 # 10.5 (int converted to float)
// Java (widening conversion)
int intValue = 10;
double doubleValue = intValue; // 10.0 (automatic)

Explicit Conversion (Narrowing)​

Manual conversion from larger to smaller types.

# Python (explicit)
float_value = 10.7
int_value = int(float_value) # 10 (truncated)
// Java (narrowing conversion)
double doubleValue = 10.7;
int intValue = (int) doubleValue; // 10 (truncated)
  • Constants: Variables whose values cannot change
  • Scope: Region where variable is accessible
  • Lifetime: Duration of variable existence
  • Type Safety: Preventing type-related errors
  • Memory Management: How variables use memory

This atomic content bridges academic variable theory with professional programming practices, emphasizing proper type selection and naming conventions.