What a variable is
A variable is a named piece of memory. Recall from Level 0 that running programs live in RAM — a variable is you telling the language: "reserve a spot on the desk, put this value in it, and let me refer to it by this name."
# Python
age = 25
name = "Asha"
price = 99.50
is_member = True
// Java — the type comes first, and it's mandatory
int age = 25;
String name = "Asha";
double price = 99.50;
boolean isMember = true;
// C++
int age = 25;
std::string name = "Asha";
double price = 99.50;
bool isMember = true;
The label-on-a-box analogy: the name (age) is the label, the value
(25) is what's inside, and the type (int) is the shape of the box —
what kind of thing fits in it.
Variables vary: assigning again replaces the contents.
score = 10
score = score + 5 # read current value, add 5, store back → 15
score += 5 # shorthand for the same thing → 20
That x = x + 5 line bothers everyone at first: = is not math equality,
it's the assignment instruction — "compute the right side, store it in
the left side."
The core data types
A data type describes what a value is and what you can do with it (you can divide two numbers; you can't divide two names). Every language has the same basic set, under slightly different names:
| Concept | Python | Java | C++ | Example |
|---|---|---|---|---|
| Whole number | int | int / long | int / long long | 42, -7 |
| Decimal number | float | double | double | 3.14, -0.5 |
| Text | str | String | std::string | "hello" |
| True/false | bool | boolean | bool | True / true |
| Single character | (1-char str) | char | char | 'A' |
| Nothing/absent | None | null | nullptr | — |
Two beginner-critical details:
"42"is not42. Text that looks like a number is still text."42" + "1"is"421"in Python (text gluing — concatenation), while42 + 1is43. Most "weird bug" moments in week one are a string where a number was intended — often fresh from user input, which always arrives as text.- Decimals are approximate.
0.1 + 0.2gives0.30000000000000004in every language, because binary can't represent 0.1 exactly — same as ⅓ in decimal. Rule: never use floats for money; store paise/cents as integers. (Yes, this is an interview question.)
Contiguous Memory: Arrays (Java & C++)
Before looking at growable lists, we must understand the raw hardware container: the Array. An array is a fixed-size row of boxes in memory, all of the same type.
// Java: Declare and allocate an array of size 5
int[] arr = new int[5]; // initialized to [0, 0, 0, 0, 0] by default
arr[0] = 42; // store at index 0
// Array literal (size is inferred as 3)
int[] primes = {2, 3, 5};
// 2D Arrays (Matrix / Grid - very common in DSA)
int[][] grid = new int[3][4]; // 3 rows, 4 columns
grid[1][2] = 99;
// C++: Array on the stack (fixed size must be a compile-time constant)
int arr[5] = {0}; // initialize all to 0
arr[0] = 42;
// 2D Arrays
int grid[3][4] = {0};
grid[1][2] = 99;
Note: In C++, stack arrays are fixed. For dynamic sizing, we use std::vector (covered on the Collections page), which manages a raw heap array for us.
Converting between types
# Python
age = int("25") # text → number
label = str(25) # number → text
print(int(7.9)) # 7 — truncates, doesn't round
// Java
int age = Integer.parseInt("25");
String label = String.valueOf(25);
// C++
int age = std::stoi("25");
std::string label = std::to_string(25);
Static vs dynamic typing, now hands-on
The previous page introduced this split; here's what it feels like in practice:
# Python — dynamic: the TYPE LIVES WITH THE VALUE, names are free
x = 42 # x holds an int
x = "hello" # ...now a str. Legal. Sometimes a bug you wanted caught.
// Java — static: the TYPE LIVES WITH THE NAME, forever
int x = 42;
x = "hello"; // ❌ compile error — caught before the program ever runs
Dynamic typing is freedom (fast to write, easy to start); static typing is a seatbelt (a whole bug category — wrong type reaching distant code — cannot exist). Industry verdict, worth internalizing early: on large codebases the seatbelt wins, which is why typed Python and TypeScript took over.
Python Type Hints in DSA
Python is dynamically typed, but standard DSA templates use type hints to document function inputs and outputs. Since you will encounter them in every practice platform (like LeetCode), you must recognize this syntax:
from typing import List, Dict, Optional
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# 'nums' must be a list of integers
# 'target' must be an integer
# The function returns (->) a list of integers
return []
def get_node(self, val: int) -> Optional[ListNode]:
# Optional[T] means the return value is either a ListNode OR None
# This is extremely common in linked list and tree problems!
return None
Note: In modern Python (3.9+), you can write list[int] and dict[str, int] directly without importing from the typing module.
Naming: the first skill interviewers actually judge
Code is read far more often than written. Compare:
# bad
d = 86400
x = t / d
# good
SECONDS_PER_DAY = 86400
days_elapsed = elapsed_seconds / SECONDS_PER_DAY
Conventions to follow from day one:
- Names describe contents, not type:
customer_count, notnumorn2 - Python/C++:
snake_casevariables; Java:camelCase - Constants in
ALL_CAPS; booleans read as questions:is_member,has_paid - One-letter names only for tiny scopes (
iin a short loop — fine)
In machine-coding rounds (Level 5), reviewers consistently cite naming as a
top differentiator between candidates with identical logic. inventory vs
arr2 is the difference between "reads like a professional" and "reads like
homework."
What's actually in the box: a first look at references
One more idea, planted now because Levels 2 and 5 depend on it. For simple types (numbers, booleans), the box holds the value itself. For big things (lists, objects), the box usually holds a reference — the address of the data, not the data ("the warehouse shelf number, not the warehouse").
a = [1, 2, 3]
b = a # copies the ADDRESS, not the list
b.append(4)
print(a) # [1, 2, 3, 4] ← a changed too! Same list, two labels.
If that surprised you, good — hold the thought. Copying a reference copies access to the thing, not the thing. This single fact explains a huge family of bugs in every language, and we'll formalize it on the Functions page (pass-by-value vs pass-by-reference).
Pointers and References: Memory Addresses Under the Hood
For simple types like int, the variable contains the actual value. For complex objects, Python and Java variables contain references (pointers to memory addresses under the hood). C++ is unique because it forces you to deal with memory addresses explicitly.
You must master four concepts in C++ pointers and references to write linked lists, trees, and graphs:
1. Pointer Variables (*)
A pointer is a variable whose value is the memory address of another variable. We declare a pointer using the asterisk symbol *.
int x = 42;
int* ptr = &x; // ptr stores the memory address of x (ptr "points to" x)
2. Address-Of (&) and Dereferencing (*)
&(Address-Of): Returns the memory address of a variable.*(Dereference): Goes to the address stored in a pointer and reads/modifies the value there.
std::cout << ptr; // Prints something like 0x7ffd58bb12c (the address)
std::cout << *ptr; // Prints 42 (goes to that address and reads the value)
*ptr = 99; // Changes x to 99!
3. The Arrow Operator (->)
If a pointer points to an object/struct, we use the arrow operator -> to access its members. It is a shorthand for dereferencing followed by member access.
struct Node {
int val;
Node* next;
};
Node* head = new Node{10, nullptr};
std::cout << head->val; // Prints 10 (shorthand for (*head).val)
4. References (& in a type)
A reference is an alias (another name) for an existing variable. It does not store an address and cannot be repointed.
int x = 42;
int& ref = x; // ref is another name for x (any edit to ref edits x)
ref = 99; // x is now 99!
5. nullptr
nullptr represents a pointer that points to nothing (the equivalent of None in Python or null in Java). In DSA, the end of a linked list or an empty tree node is always signaled by nullptr.
Summary of Box-and-Address Models:
[Value Variable] [Pointer Variable]
┌───────────┐ ┌───────────┐
│ 42 │ │ 0x7ffd... │ ───┐ (Points to x)
└───────────┘ └───────────┘ │
x (at 0x7ffd...) ptr ▼
[x's box]
Common beginner mistakes
- Using a variable before assigning it —
NameError(Python) / compile error (Java, C++). Boxes must be filled before opening. - Comparing with
=instead of==.=stores;==asks "equal?". C++ will happily compileif (x = 5)and assign inside the condition — a classic trap. - String arithmetic surprises:
"5" * 3is"555"in Python (string repetition), an error in Java. Convert first. - Integer division:
7 / 2is3.5in Python 3 but3in Java/C++ (two ints → int, decimals dropped). Python's7 // 2gives the truncating version on purpose. - Float equality:
if (a == 0.3)after float math fails randomly. Compare with a tolerance:abs(a - 0.3) < 1e-9.
Think it through
Most week-one "weird bugs" are a type in disguise. Debug the classic one — text where a number was meant — before revealing each step.
PROBLEMA user enters two prices and a budget; this code always prints 'over'. Why? p1 = input(); p2 = input(); total = p1 + p2; budget = input(); if total > budget: print('over').
- 1
Find the type
“What type does input() return, and what does that do to p1 + p2?”
- 2
Fix at the boundary
“Where's the right place to turn text into numbers?”
unlocks after the stage above - 3
The money subtlety
“Is float the right type for prices and budgets?”
unlocks after the stage above - 4
Code it
“Convert each input; then the arithmetic and comparison just work.”
unlocks after the stage above - 5
The rules
“Summarize what prevents this whole bug family.”
unlocks after the stage above
Check yourself
1. In Python, input() always returns:
2. Why does 0.1 + 0.2 == 0.3 evaluate to False in essentially every language?
3. a = [1,2,3]; b = a; b.append(4). What is a afterward, and why?
4. In Java/C++, `7 / 2` with both operands ints gives:
Interview perspective
Practice
Beginner
- Create variables for your name, age, height in meters and whether you're a student; print a sentence using all four. (All three languages if you can.)
- Predict, then verify:
print("3" + "4"),print(3 + 4),print(int("3") + 4)— and the Java/C++ equivalents of each.
Intermediate
- Swap two variables without a third (Python:
a, b = b, a; how would you do it in Java?). Then explain to an imaginary junior whya = b; b = a;fails. - Write the list-aliasing example above, then fix it so
bis a true independent copy (b = list(a)/a.copy()).
Advanced
- In Python, run
x = 10**100and print it. Try the same value in Java withlong. What does this tell you about how each language stores integers, and what's the cost of Python's approach?
Next: Control Flow — making programs decide and repeat.