A variable holds a value that can change, a constant holds a value that stays fixed, and the data type tells the computer what kind of value it is. Choosing correctly prevents errors before the program even runs.
This lesson is part of programming foundations. The next lesson, writing loops with correct boundaries, puts these values to work.
How do you decide between a variable and a constant?
Ask one question: does the value change while the program runs? If yes, use a variable. If it is set once by a rule or by the shop, use a constant.
A constant also gives a number a name. PRICE_PER_PEN is easier to understand than a bare 1.50 scattered through the code.
Worked example: a stationery shop
The shop sells pens at RM1.50 each. The program records the customer’s name, the number of pens, the total and whether the customer is a member.
| Value | Kind | Data type | Reason |
|---|---|---|---|
| PRICE_PER_PEN = 1.50 | Constant | Real | Fixed and has sen |
| customerName | Variable | String | Text |
| quantity | Variable | Integer | Whole pens only |
| total | Variable | Real | Product of a real price |
| isMember | Variable | Boolean | Either true or false |
For 7 pens the total is 7 × 1.50 = RM10.50. Both values are numbers, so the multiplication works and the result is real.
What mistake do students make with types?
A common slip is to store a phone number as an integer because it contains only digits. The number 0123456789 is stored as 123456789, and the leading zero is lost.
| Choice | What is stored | Problem |
|---|---|---|
| Integer | 123456789 |
Leading zero disappears |
| String | "0123456789" |
None; every digit kept |
The test is simple: will you add, subtract or compare sizes with this value? If not, it is an identifier and belongs in a string, even though it looks like a number.
What happens if you mix types?
The same digits behave differently depending on type. If 12 and 3 are integers, 12 + 3 gives 15. If they are strings, joining them gives “123”.
This is why a program should convert text input to a number before doing arithmetic. The safest habit is to state the type of every value when you first declare it.
Check yourself
Choose a data type for each value, and say which would be a constant: (a) a student’s age in years, (b) a pass mark of 40 fixed by the school, (c) the class name “4B”, (d) whether the homework is done.
Answer
(a) Integer, because age in whole years is a count. (b) Integer, and a constant, because the school fixes it and the program never changes it. (c) String, since it mixes a digit and a letter. (d) Boolean, true or false.
What to study next
Next, use variables inside repeated steps in writing loops with correct boundaries. Log any type slip you make with the mistake log and paper-error review.
If you want a teacher to check your choices on new examples, see online one-to-one Computer Science tuition.