Principles of Programming – Data & Variables
2. Data, Objects, Variables, and Constants
2.1 Data
• Definition: Data is any raw fact or value that a program can process.
o Examples: numbers (25), text ("Hello"), logical values (True/False).
• Computers don’t “understand” data the way humans do — they see everything as
binary (0s and 1s). Data types and structures give meaning to this raw information.
Analogy: Imagine you have ingredients in a kitchen — sugar, flour, eggs. Those are your data.
The recipe (program) decides how to use them.
2.2 Objects
• In programming, an object is like a “thing” that stores data and knows how to act on it.
• Objects combine:
o Attributes (data) → e.g., a “Car” object has color = "red", speed = 60.
o Methods (functions/behavior) → e.g., drive(), brake().
Analogy: Think of a smartphone — it has data (apps, battery level) and behaviors (make call,
send SMS).
2.3 Variables
• Definition: A variable is a named storage location in memory that can hold data.
• Think of it as a container or a labelled box where you can put things in, take them out,
or change them.
Example (Python):
age = 20 # variable called age stores the number 20
name = "Lydia"
• Here, age and name are variables.
• Variables can change over time:
age = 21 # age now holds a new value
2.4 Constants
• Definition: A constant is like a variable, but once given a value, it cannot change during
program execution.
• Used for values that should stay fixed:
o Example: PI = 3.14159
Example (Python convention):
PI = 3.14159 # treated as constant by writing in CAPITALS
Example (Java):
final double PI = 3.14159;
Analogy: If a variable is like a whiteboard you can erase and rewrite, a constant is like a
permanent marker — once written, it stays forever.
3. Data Types
A data type tells the computer what kind of data is being stored and how much memory it
needs.
3.1 Elementary (Primitive) Data Types
These are the simplest, building-block data types.
1. Numeric
o Integer → whole numbers (5, -23, 1000)
o Float/Double → numbers with decimals (3.14, -0.01)
2. Character (char)
o Single letter, digit, or symbol ('A', '7', '#').
3. String
o Sequence of characters ("Hello World").
4. Boolean
o Logical values: True or False.
3.2 Declaration, Assignment, and Initialization
(a) Declaration
• Telling the computer what variable exists and what type of data it will store.
Example (Java):
int age; // declares an integer variable
String name; // declares a string variable
Example (Python):
age = None # declare with no value yet
name = "" # empty string
(b) Assignment
• Giving a variable a value.
• Symbol used: = (assignment operator).
Example:
age = 20 # assigns 20 to age
(c) Initialization
• Declaration and assignment done at the same time.
Example:
int age = 20; // initialized with 20
String name = "Ali"; // initialized with Ali
Example (Python):
age = 20
name = "Ali"