تشريح Hello World
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
In BEG-007 you compiled and ran Hello World from the terminal, but you treated the program as a block of text to copy. In this module you start to read and write Java on purpose. This first lesson takes the smallest useful program apart, piece by piece, and tells you what each piece is for.
We will use the module's picture of a recipe card. A recipe card has a title (the class), a heading that says "start cooking here" (the main line), steps (the statements), and boundaries that show where the steps begin and end (the braces). If you can point at each part, you can read any Java program in this module.
Why this matters: every Java program you will ever run, from a ten-line exercise to a large web service, starts at a main method inside a class. Knowing the parts means a compiler message such as "class Hello is public, should be declared in a file named Hello.java" reads as a clear instruction instead of noise.
This lesson builds on BEG-007 (compiling with javac, running with java) and BEG-006 (creating files from the terminal). We do not teach anything about objects yet. Some words in the main line will be explained only in part, and that is deliberate.
Learning Objectives
By the end of this lesson you will be able to:
- Point at the class declaration, the
mainmethod line, the braces, and a statement in a minimal Java program. - Write the exact
mainline from memory and say, in plain words, what each keyword in it signals. - Explain that a Java program starts running at
mainand runs its statements from top to bottom. - Explain why the file name must match a public class name.
- Explain that Java is case sensitive and give two examples of what that breaks.
- Write, compile, and run a small program of your own in a file whose name matches its class.
Written Explanation
The smallest useful program
Here is the program from the module's first demo. Create a file named Hello.java with this content:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}Compile and run it as you did in BEG-007:
javac Hello.java
java HelloYou should see Hello, Java! on its own line. Now let us name the parts.
| Part | In the program | Recipe-card picture |
|---|---|---|
| Class declaration | public class Hello | The title on the card |
main method line | public static void main(String[] args) | The heading "start cooking here" |
| Braces | { and } | The lines that mark where a section starts and ends |
| Statement | System.out.println("Hello, Java!"); | One step in the recipe |
Part 1: the class
public class Hello {
...
}Java code does not float free in a file. In Java, code that does work lives inside a class. For now, think of a class as a named container for code. The line public class Hello has three pieces:
publicmeans this class can be used from anywhere. We need it for the file-name rule below.classis the keyword that says "a class starts here".Hellois the name you chose. By convention, class names start with a capital letter.
The opening brace { begins the class and the final } ends it. Everything between them belongs to the class.
Part 2: the main line
public static void main(String[] args) {This line is the entry point. When you type java Hello, the Java launcher loads the class Hello and then calls its main method. The Java Language Specification requires that this method be public, static, void, and take one parameter whose type is an array of String. The java documentation describes the same form.
You do not need to understand every word yet. Here is what each one signals, with the full explanation arriving in later modules:
| Word | What it signals for now |
|---|---|
public | The launcher is allowed to call this method from outside the class. |
static | The method can be called on the class itself, without first creating an object. (Objects come much later.) |
void | The method does not hand back a result. |
main | The special name the launcher looks for. |
String[] args | A list of text values the program can receive from the command line. We ignore it for now. |
The name args is only a convention. String[] words works equally well, because it is just a name for the parameter. The words public, static, void, main, and String[] are the part you must not change.
Treat this line as a fixed phrase, like the title of a form. Learn it exactly, and type it the same way every time.
A note on newer Java. Some recent JDK releases add shorter ways to write a program's entry point. This course uses the classic full form above, because it works in every JDK you are likely to meet, and because it makes the structure visible. Check your own JDK's documentation if you want to read about the newer forms.
Part 3: braces and blocks
Curly braces mark where something begins and ends. In our program there are two pairs:
- The outer pair belongs to the class
Hello. - The inner pair belongs to the method
main.
The inner pair sits inside the outer pair, like a small box inside a larger box. Every { must be closed by a matching }, and the compiler stops with an error if it cannot find the partner. We study this in detail in the next lesson.
Part 4: statements
Inside main's braces we have one statement:
System.out.println("Hello, Java!");A statement is one instruction, and it ends with a semicolon. When the program runs, the JVM starts at the first statement inside main and carries them out one after another, top to bottom. When it runs out of statements, main ends, and the program ends with it.
This particular statement sends the text between the quotes to the screen and then moves to the next line. We look at it closely in Lesson 3.
Two rules that trip up beginners
Rule 1: Java is case sensitive. Main and main are different words. So are System and system, and String and string. If you write public static void Main(String[] args), the program compiles, because it is a valid method with a legal name. But the launcher looks for exactly main, so running it fails with a message saying it cannot find the main method. (You will try this yourself in Lesson 5.)
Rule 2: a public class lives in a file with the same name. The Java Language Specification says that when a class is declared public, it must be stored in a file whose name is the class name plus .java. So public class Hello must be in Hello.java, including capital letters. If it is in hello.java, javac refuses, as you saw in the BEG-007 demo. You then run the program with the class name, not the file name: java Hello.
Examples
Example 1: labelling a program (simple)
Take this program and label the parts, using the line numbers:
public class Greeter {
public static void main(String[] args) {
System.out.println("Welcome to Sakhaa Academy!");
System.out.println("Lesson 1 starts now.");
}
}- Line 1: the class declaration. The class is named
Greeter, so the file must beGreeter.java. - Line 2: the
mainline, the entry point. - Lines 3 and 4: two statements, run in this order.
- Line 5: the closing brace of
main. - Line 6: the closing brace of the class.
Saved as Greeter.java, compiled with javac Greeter.java, and run with java Greeter, it prints:
Welcome to Sakhaa Academy!
Lesson 1 starts now.Example 2: order matters (practical)
public class Order {
public static void main(String[] words) {
System.out.println("Order received");
System.out.println("Order saved");
System.out.println("Receipt sent");
}
}Output:
Order received
Order saved
Receipt sentTwo things to notice. First, the parameter is called words instead of args. The program is valid anyway, as explained above. Second, the three lines appear in the order they are written. If you swapped the second and third statements, "Receipt sent" would be printed before "Order saved". Program order is the order of the steps.
Example 3: reading a message with the parts in mind (realistic)
A colleague saves the program from Example 1 as greeter.java (lowercase g) and runs javac greeter.java. The compiler prints a message like:
greeter.java:1: error: class Greeter is public, should be declared in a file named Greeter.java
public class Greeter {
^
1 errorNow that you know the parts, the message is easy to read. It names the class on line 1 (Greeter), says the class is public, and says the file must be called Greeter.java. There are two fixes: rename the file to Greeter.java, or remove public from the class line. The first is the habit to build, because later in the course every public class gets its own file.
(Exact message wording can vary slightly between JDK versions, so treat the text above as typical.)
Backend Insight
A backend service looks much bigger than Hello World, but the entry point is the same idea. A server application has a main method somewhere, and when the operating system starts the application, the JVM calls main. The code there usually sets things up and then starts accepting requests. Frameworks you will meet later hide the main line in a small starter class, but it is still there.
When a deployment fails with "Main method not found" or "Could not find or load main class", the cause is often one of the two rules from this lesson: a misspelled or mis-typed main signature, or a class name that does not match what the launcher was told. Knowing the parts lets you check those two things first.
Common Mistakes
Mistake 1: Changing the case
- Incorrect:
public static void Main(String[] args) - Correct:
public static void main(String[] args)
Main is a legal method name, so this compiles, and the failure only appears when you run the program. Java does not treat Main as the entry point.
Mistake 2: Leaving out a word in the main line
- Incorrect:
public void main(String[] args)(nostatic) - Incorrect:
public static void main(String args)(no[]) - Correct:
public static void main(String[] args)
Each of these is a legal method, so javac accepts the file, but the launcher cannot use it as the entry point.
Mistake 3: File name and class name differ
A public class Hello in hello.java or Hello1.java is rejected by javac. Match them exactly, including capital letters.
Mistake 4: Running the file instead of the class
- Incorrect:
java Hello.classorjava Hello.java(when following the two-step method) - Correct:
java Hello
The launcher wants a class name, not a file name.
Exercises
Try each exercise yourself before opening the solutions. Hands-on items must be done on your machine.
Level A: Foundation
A1. Write the exact main line from memory. Then check it against the lesson.
أظهر الحل A1
A1. public static void main(String[] args)
A2. For the program in Example 2, name the class, name the file it must be saved in, and give the command that runs it.
أظهر الحل A2
A2. The class is Order. It must be saved as Order.java. Compile with javac Order.java and run with java Order.
A3. True or false, with a reason: (a) Main and main are the same word in Java. (b) A program stops running when main has no more statements. (c) The parameter must be called args.
أظهر الحل A3
A3. (a) False. Java is case sensitive, so Main and main are different words. (b) True. When the last statement of main finishes, main ends and the program ends. (c) False. args is only a conventional name, and String[] words works the same way.
Level B: Application
B1. Write a program, in a file whose name matches the class Card, that prints three lines: Ana Hassan, Backend Student, Cairo. Compile and run it. Write down the commands you used.
أظهر الحل B1
B1. For example, Card.java:
public class Card {
public static void main(String[] args) {
System.out.println("Ana Hassan");
System.out.println("Backend Student");
System.out.println("Cairo");
}
}Commands: javac Card.java, then java Card. The output is the three lines in that order.
B2. Predict the output of this program, then run it to check:
public class Steps {
public static void main(String[] args) {
System.out.println("Step 3");
System.out.println("Step 1");
System.out.println("Step 2");
}
}أظهر الحل B2
B2. The output follows the order of the statements:
Step 3
Step 1
Step 2B3. A student has a public class Report in a file called Report.txt and runs javac Report.txt. Without running anything, explain what the problem is and what to do. (Hint: think about what the compiler expects of the file name.)
أظهر الحل B3
B3. The compiler expects Java source files to end in .java, and a public class Report must be in Report.java. Rename the file to Report.java, then run javac Report.java and java Report. (Exactly what javac prints for a wrong extension can vary, but renaming is the fix either way.)
Level C: Challenge
C1. Draw (on paper or in a comment) the nesting of braces for Example 1: which pair encloses which? Then say in one sentence where a statement such as System.out.println("x"); must be placed.
أظهر الحل C1
C1. The outer pair encloses the whole class. The inner pair, which starts after the main line, encloses the statements of main, so the inner pair is inside the outer pair. In this course every statement belongs inside a method such as main, which is what tells Java when the statement runs. A statement placed directly in the class body is a compile-time error.
C2. Take Hello.java and change the class name to Welcome on the class line only, leaving the file name as Hello.java. Compile it and record the message. Then give two different ways to fix it.
أظهر الحل C2
C2. A typical message is Hello.java:1: error: class Welcome is public, should be declared in a file named Welcome.java. Fix 1: rename the file to Welcome.java. Fix 2: change the class name back to Hello so it matches the file.
Mini Challenge
Write a program of your own named Recipe that prints a tiny recipe card with a title line and three step lines, for example a recipe for tea. Use the exact main line. Save, compile, and run it, then copy your program into a note and label the four parts: class declaration, main line, braces, statements.
Check your work: the file is Recipe.java, the class is public class Recipe, you used System.out.println for every line, and the output lines appear in the order you wrote them.
Summary & Next Lesson
Key takeaways
- A minimal Java program is a class that contains a
mainmethod, which contains statements. - The entry point is
public static void main(String[] args). Learn it as a fixed phrase. - Braces mark where the class and the method begin and end.
- Statements run in order from top to bottom, and the program ends when
mainfinishes. - Java is case sensitive, and a public class must be in a file named after it, plus
.java.
Next lesson
You can now name the parts of a program. In the next lesson, "Statements, semicolons, and blocks", you look more closely at the steps inside the braces: what ends a statement, what a block is, and how to lay your code out so people can read it.
Self-check
- Where does a Java program start running?
- Which part of the
mainline can you rename safely? - In what order do the statements inside
mainrun? - Why does
Mainnot work in place ofmain? - A public class is called
Menu. What must the file be called?
أظهر الإجابات
- At the
mainmethod. - The parameter name,
args. It is only a convention. - One after another, from top to bottom.
- Java is case sensitive, so
Mainis a different name, and the launcher looks for exactlymain. Menu.java.
References
- Oracle, The Java Language Specification, Java SE 21, section 12.1.4. It says the program's
mainmethod must bepublic,static,void, and take one parameter that is an array ofString. - Oracle, The Java Language Specification, Java SE 21, section 7.6. It states that a public class goes in a file whose name matches the class (checked in BEG-007 and not re-read here).
- Oracle,
javacommand reference, JDK 21. It describes the launcher loading a class and calling itsmainmethod. - Oracle, The Java Language Specification, Java SE 21, section 14.2. It defines a block as statements enclosed in braces that run in order.
- The error and output texts shown were produced by compiling and running the examples with JDK 21 on Windows. Other JDK versions may word messages differently. Not verified from an official source: the statement that some recent JDK releases add shorter entry-point forms (stated from general knowledge and hedged in the text).
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.