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β
-
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.
# 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)
π 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.