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.
// 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.
Character Types¶
Single characters.
Boolean Types¶
True or false values.
Composite Data Types¶
Data types that can hold multiple values.
Strings¶
Sequences of characters.
Arrays¶
Fixed-size collections of same-type elements.
// 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.
// 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¶
- Naming Conventions
- Use descriptive, meaningful names
- Follow language-specific conventions (camelCase, snake_case)
-
Avoid single-letter variables except for loop counters
-
Type Selection
- Choose the most appropriate data type for the data
- Consider memory usage and performance
-
Use appropriate size for numeric types
-
Initialization
- Always initialize variables before use
- Use meaningful default values
-
Consider using constants for fixed values
-
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.
Explicit Conversion (Narrowing)¶
Manual conversion from larger to smaller types.
// Java (narrowing conversion)
double doubleValue = 10.7;
int intValue = (int) doubleValue; // 10 (truncated)
🔍 Related Concepts¶
- 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.