المتغيرات كصناديق عليها ملصقات
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
Until now your programs have printed fixed text. Real programs need to remember things: a score, a name, a price, a count of items in a basket. A variable is how a Java program remembers one value while it runs.
In this lesson we use one picture throughout the whole module: a variable is a labeled box. The label is the variable's name, the kind of thing the box is built to hold is its type, and what is inside is its value. You will declare variables, put values into them, change them, and read them back with System.out.println.
Why this matters: every backend program, from a tiny script to a large service, is mostly variables being filled in, changed, and passed along. A request arrives with a user name and a quantity; the program stores them in variables, works on them, and builds a reply. If the box idea is solid now, the rest of the module (the different box sizes, conversions between them) will make sense.
This lesson builds on BEG-008: you can already write a main method, end statements with semicolons, and print with System.out.println. It introduces only two types, int and String, plus double; the full set comes in the next lesson.
Learning Objectives
By the end of this lesson you will be able to:
- Explain a variable as a named box with a type and a value.
- Declare a variable with a type and a name, and give it a first value in the same statement.
- Change a variable's value later with an assignment, and tell a declaration from an assignment.
- Read a variable's value inside
printlnand inside text built with+. - Explain why a variable must have a value before it is used, and read the compiler message when it does not.
- Recognise three compile errors beginners meet first: a missing value, a name declared twice, and a value of the wrong type.
Written Explanation
A variable is a labeled box
Imagine a shelf of boxes. Each box has:
| Part of the box | In Java | Example |
|---|---|---|
| The label on the outside | The variable's name | age |
| The kind of thing the box is built for | The type | int (a whole number) |
| What is inside right now | The value | 30 |
A box built for whole numbers will not accept the word "hello". That is the type doing its job, and the compiler enforces it before the program ever runs.
Declaring a variable
A declaration creates a box. It needs two things: a type and a name.
int age;This reads "make a box named age that holds an int". Most of the time you also give the box its first value in the same statement. That is called initializing the variable:
int age = 30;The single = here does not mean "equals" as in mathematics. It means "put the value on the right into the box on the left". Read it as "age gets 30". The right-hand side is worked out first; then the result goes into the box.
The general shape of a declaration with a first value is:
type name = value;Like every statement, it ends with a semicolon.
Changing and reading a variable
A variable is a box, not a sealed jar: you can swap what is inside. Putting a new value into an existing box is an assignment. Notice that it has no type in front, because the box already exists:
age = 31;The old value, 30, is gone; the box now holds 31. Using the name anywhere a value is expected reads what is in the box without emptying it:
System.out.println(age);You can also build the right-hand side from other variables, including the one being assigned. The right side is worked out first, using the old contents:
score = score + 10; // read the box, add 10, put the result backThe type is fixed for the life of the box
You choose the type when you declare the variable, and it never changes. A box built for int always holds an int. This is why Java is called a statically typed language: the type of every variable is known when the program is compiled. If you try to put text into an int box, the compiler stops you.
Three types are enough for this lesson:
intfor whole numbers such as30,-4, or0.doublefor numbers with a decimal part such as19.99.Stringfor text in double quotes such as"Cairo".
(String is a little different from the other two. That difference is the subject of Lesson 3. For now treat it as a box that holds text.)
A variable needs a value before you read it
A box that was declared but never filled has nothing meaningful in it. Java refuses to guess. If a local variable (one declared inside a method like main) might be read before any value was put in, the program does not compile. We will meet this message in the examples.
Names
Choose a name that says what the box holds: age, city, itemCount. A name is made of letters and digits and must not start with a digit; it cannot contain spaces. Java is case sensitive, so age and Age are two different names. The style rules for names (why itemCount and not Item_Count) are in Lesson 4. For now, start with a lowercase letter and join words with a capital letter in the middle.
Examples
Example 1: a single box (simple)
public class Age {
public static void main(String[] args) {
int age = 30;
System.out.println(age);
age = 31;
System.out.println(age);
}
}Compiled with JDK 21 and run, it prints:
30
31Step by step: the first line creates the box age holding 30; the second prints it; the third replaces the contents with 31; the fourth prints the new contents. The declaration (int age = 30;) happened once. The second line that mentions age (age = 31;) is an assignment and does not repeat int.
Example 2: boxes of different types (practical)
public class Order {
public static void main(String[] args) {
String city = "Cairo";
double price = 19.99;
System.out.println(city + " costs " + price);
}
}Output:
Cairo costs 19.99Two boxes, two types. The + between a String and another value joins them into text, exactly as you saw with println in BEG-008. The variable price is read, and its value 19.99 becomes part of the sentence.
A useful habit: after a few lines, ask "what is in each box right now?" It is the same tracing skill you will use to find bugs.
Example 3: using a value, then replacing it (realistic)
Swapping the contents of two boxes is a classic exercise. You need a third, temporary box, because assigning straight from one to the other would overwrite a value you still need:
public class Swap {
public static void main(String[] args) {
int first = 10;
int second = 20;
int temp = first; // keep the old first value safe
first = second; // first now holds 20
second = temp; // second gets the saved 10
System.out.println("first = " + first + ", second = " + second);
int score = 0;
score = score + 10;
score = score + 5;
System.out.println("Score: " + score);
}
}Output:
first = 20, second = 10
Score: 15The second half shows the "read, change, store back" pattern: score goes 0, then 10, then 15. Programs that count, total, or accumulate are built from this pattern.
Backend Insight
A backend service receives data and has to hold it somewhere while it works. When a request such as "add 2 items of product 17 to the basket" arrives, the program typically puts the product id in an int variable, the quantity in another, the user's name in a String, and then computes with them. Later modules wrap many variables into objects, but the underlying pieces are always these labeled boxes.
Two habits pay off from day one:
- Meaningful names.
int q = 2;forces the next reader (often you, in six months) to guess.int quantity = 2;does not. In a service with thousands of lines, good names are the cheapest documentation. - Choosing the type when you declare. The type is a promise about what the variable can hold. If the type is wrong for the data, for example storing a price in an
intand losing the cents, the bug is created at the declaration and may only show up as a wrong total much later.
Also remember where these boxes live: the variables you declare inside main exist in RAM while the program runs (Module 1) and disappear when the program ends. To keep a value permanently, a program has to write it to storage, which later modules cover.
Common Mistakes
Mistake 1: Reading a variable that was never given a value
int total;
System.out.println(total);The compiler (JDK 21) says:
L1B.java:4: error: variable total might not have been initialized
System.out.println(total);
^
1 errorFix: give the variable a value before you use it, for example int total = 0;.
Mistake 2: Declaring the same name twice
int count = 5;
int count = 6;The message is variable count is already defined in method main(String[]). A box can only be created once. To change the contents, drop the type: count = 6;.
Mistake 3: Putting the wrong kind of value in a box
count = "six";Message: incompatible types: String cannot be converted to int. The label says whole numbers only. Either use a number, or declare a String box if you really need text.
Mistake 4: Reading = as "equals"
score = score + 10; would be impossible as a maths equation, but as an instruction it is perfectly fine: work out the right side, store it on the left. Beginners also forget that assignment copies the value; it does not link the two boxes together afterwards.
Mistake 5: Wrong capitalisation
Age and age are different names. If you declared age and then write Age, the compiler reports cannot find symbol. This is the same kind of message you saw in BEG-008 for a misspelled name.
Exercises
Try each exercise yourself before opening the solutions. If you have a JDK, put each one in a small file and compile it; if not, trace it on paper.
Level A: Foundation
A1. In int level = 4;, name the type, the name, and the value.
أظهر الحل A1
A1. Type int, name level, value 4.
A2. Write a declaration with an initial value for each: a whole number of students (28), a price (4.5), and a city name (Alexandria).
أظهر الحل A2
A2.
int students = 28;
double price = 4.5;
String city = "Alexandria";A3. What does this print?
int x = 3;
x = 8;
System.out.println(x);أظهر الحل A3
A3. 8. The first value 3 was replaced.
Level B: Application
B1. Trace the boxes line by line and give the final output:
int a = 4;
int b = a;
a = 9;
System.out.println(a + " " + b);أظهر الحل B1
B1. a starts as 4; b gets a copy of 4; a becomes 9; b still holds 4. Output: 9 4. Assignment copies the value, so the boxes are not linked.
B2. This program does not compile. Name the problem in each of the two marked lines.
int points = 10;
int points = 20; // line 2
String label = 5; // line 3أظهر الحل B2
B2. Line 2 declares the name points a second time (variable points is already defined). Line 3 puts a number into a String box (incompatible types: int cannot be converted to String). Fixes: write points = 20; and String label = "5";, or make label an int.
B3. Write code that starts balance at 100, then adds 25, then subtracts 40, then prints Balance: followed by the value.
أظهر الحل B3
B3.
int balance = 100;
balance = balance + 25;
balance = balance - 40;
System.out.println("Balance: " + balance);It prints Balance: 85.
Level C: Challenge
C1. You have int left = 1; and int right = 2;. Write the lines that swap them without declaring a third variable named temp. (Hint: you may use arithmetic and the "read, change, store back" pattern, but verify with a trace that you never lose a value.)
أظهر الحل C1
C1. One way:
left = left + right; // left is 3
right = left - right; // right is 1
left = left - right; // left is 2Trace: after line 1 left is 3, right is 2; after line 2 right is 1; after line 3 left is 2. The numbers are now swapped. (This trick is clever but harder to read than using a temporary box, and it can go wrong for very large numbers, as a later lesson will show. In real code, prefer the temporary variable.)
C2. A teammate writes int total; total = total + 5; and says "it starts at zero by default". Explain why the program does not compile, and show the corrected version.
أظهر الحل C2
C2. A local variable is not given a default value. Reading total in total + 5 happens before any value was stored, so the compiler reports variable total might not have been initialized. Fix: int total = 0; total = total + 5;.
Mini Challenge
Write a program called Profile with these variables, each with a sensible name and the right type: your age in years, a score with one decimal place, and your first name. Print one line that uses all three, such as Sara is 24 years old with a score of 7.5. Then change the score and print a second line.
Check your work: it compiles without errors; there is exactly one declaration per variable; the second score line uses an assignment (no type in front); and every name tells a reader what is inside the box.
Summary & Next Lesson
Key takeaways
- A variable is a named box with a type (what it can hold) and a value (what it holds now).
- Declare with
type name;, or initialize at once withtype name = value;. - A later assignment
name = value;replaces the contents and does not repeat the type. =means "store the right side in the left box", not mathematical equality.- The type never changes, and a local variable must have a value before it is read.
Next lesson
You have used int, double, and String. The next lesson, "The eight primitive types", shows the full set of simple types, their sizes and ranges, and how to choose the right one for a given piece of data.
Self-check
- What two things does every declaration need?
- What is the difference between
int n = 5;andn = 5;? - What does
x = x + 1;do? - What happens if you read a local variable that was never given a value?
- Can an
intbox later hold the text"hi"?
أظهر الإجابات
- A type and a name.
- The first declares a new box and fills it; the second only replaces the contents of an existing box.
- It reads the current value, adds 1, and stores the result back in
x. - The code does not compile; the compiler reports that the variable might not have been initialized.
- No. The type is fixed, so the compiler reports an incompatible-types error.
References
- Oracle, The Java Tutorials: Variables. It describes the kinds of variables (local variables among them) and the rules for legal variable names, including case sensitivity.
- Oracle, The Java Tutorials: Primitive Data Types. It describes
int,double, and the special support the language givesString. - Oracle, The Java Language Specification, Java SE 21, Chapter 4. It states that the language has primitive and reference types.
- All code and compiler messages were compiled and run with JDK 21. Other JDK versions may word messages differently. The "declared once, assigned many times" framing and the box analogy are this course's own teaching device. The detail that a local variable gets no default value is standard Java behavior; the example message above is the observed confirmation. The swap-without-temp trick in C1 is shown on small numbers only.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.