الترجمة والتشغيل من الطرفية
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
Time to do by hand what an IDE normally hides. In this lesson you will write a small Java program, compile it with javac, and run it with java, using only the terminal skills from BEG-006 and the JDK from BEG-005. Two commands carry the whole pipeline from L02: javac turns a .java file into a .class file, and java starts the JVM to run it.
We keep the translated-book analogy: javac is the translator who produces the finished book, and java is the reader who reads it aloud. You will also meet the three most common beginner stumbles: a file name that does not match the class, typing .class when running, and believing that "no error" means "correct".
Why this matters: IDEs and build tools run exactly these steps for you. When something goes wrong in a build, knowing the manual version lets you understand the message instead of guessing.
This lesson builds on L02 and L03 (pipeline, JDK), BEG-005 (JDK installed, PATH, file extensions), and BEG-006 (terminal navigation and file commands).
Learning Objectives
By the end of this lesson you will be able to:
- Create a
.javafile in a project folder and save it with the correct name and extension. - Compile it with
javacand identify the.classfile it creates. - Run it with
javausing the class name, and explain why.classis not typed. - Explain the rule linking the file name to a public class name.
- Read a compile error message and find the file, line number, and problem.
- Explain why a program that compiled can still fail while running.
Written Explanation
Step 0: a working folder
Use the terminal skills from BEG-006. The commands below create a folder, enter it, and show the current location. The exact commands differ a little between shells, so use the version that matches yours.
mkdir hello-java
cd hello-java
pwdThese work in Bash and in PowerShell (pwd is accepted in both). In the Windows Command Prompt use cd with no argument to show the folder. Keep the terminal open in this folder: both javac and java will look here.
Step 1: write the source file
Create a file named exactly Hello.java containing this program. Use any plain-text editor (an IDE is fine, as is the editor of your choice). On Windows, make sure the editor does not secretly save it as Hello.java.txt: recall from BEG-005 that hidden file extensions can cause this.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello from the terminal!");
}
}Read it once so that nothing is mysterious:
public class Hellodeclares a class namedHello. A class is the basic container for Java code.public static void main(String[] args)is the entry point: the method thejavacommand calls first. You will study methods properly later; for now treat this line as a fixed phrase that must be typed exactly.System.out.println(...)prints a line of text. The text in double quotes is what appears.- Curly braces
{ }mark where the class and the method start and end. Each statement ends with a semicolon.
Capitalisation matters: Hello and hello are different names.
The file-name rule
A public class named Hello must live in a file named Hello.java: the class name plus .java, capital letters included. The Java Language Specification describes this as something a system that stores code in files may enforce, and the standard javac does enforce it. If you save the program above as Greeting.java, compilation fails. The message typically says that class Hello is public and should be declared in a file named Hello.java (the exact wording can vary between versions).
Use this as a habit: one public class per file, and the file name equals the class name.
Step 2: compile with javac
Check that the file is there, then compile:
ls (Bash or PowerShell: use dir in Command Prompt)
javac Hello.java
ls- You give
javacthe file name, including.java. - If the code is valid,
javacprints nothing at all. In the terminal, silence is success. - Listing the folder afterwards should show a new file,
Hello.class. By defaultjavacputs each class file in the same folder as the source, and names it after the class.
Now you have both files: Hello.java (source, text) and Hello.class (bytecode, binary).
Step 3: run with java
java HelloThe output should be:
Hello from the terminal!Note what you typed: Hello, not Hello.class and not Hello.java. The java command expects the name of a class, and it finds that class's .class file for you. The documentation for the launcher describes its argument as a class name, and its examples never include an extension.
So the two commands differ in what they take:
| Command | Takes | Example |
|---|---|---|
javac | A file name | javac Hello.java |
java | A class name | java Hello |
If you type java Hello.class, the launcher looks for a class literally named Hello.class, finds nothing, and reports that it could not find or load the main class. The fix is to drop the extension.
A shortcut you will see
Recent JDKs can also run a single source file in one step: java Hello.java compiles it in memory and runs it, without leaving a .class file behind. The java documentation calls this source-file mode. It is handy for quick experiments. In this module, use the two-step version, because the point is to see the compile stage and its output file.
Reading a compile error
Suppose you delete the semicolon after the println(...) call and compile. Compilation fails, no new .class file is produced from this run, and a message appears. It typically has this shape (wording may vary by JDK version):
Hello.java:3: error: ';' expected
System.out.println("Hello from the terminal!")
^
1 errorRead it in parts:
Hello.java:3is the file and the line number wherejavacnoticed the problem.error: ';' expectedsays what it believes is wrong.- The caret
^points to the spot. 1 errorcounts the problems.
Sometimes the problem is on the line before the reported one, because the compiler only noticed when it kept reading. If the reported line looks fine, check the line above.
If an old Hello.class already exists from an earlier successful compile, it stays in the folder and java Hello would still run that old version. That is a good reason to read the compile output before running.
Compiling is not the same as working
A program can compile cleanly and still fail when run. For example, this compiles without complaint:
public class Divide {
public static void main(String[] args) {
int people = 0;
System.out.println(90 / people);
}
}At run time the JVM stops with a message that begins with Exception in thread "main" java.lang.ArithmeticException: / by zero and shows where it happened. Integer division by zero is specified by the Java language to throw an ArithmeticException. This is a runtime error, and the demo in the next lesson walks through it step by step. For now, the point is the two-stage nature of the pipeline: javac checks the rules, and the JVM meets the data.
The full cycle
Every change follows the same loop:
- Edit and save the
.javafile. javac Hello.java. Fix errors until it is silent.java Hello. Check the output.- Back to 1.
Examples
Example 1: first success (simple)
mkdir hello-java
cd hello-java
(create Hello.java with the program above)
javac Hello.java
java Hello
Hello from the terminal!Listing the folder shows two files, Hello.java and Hello.class. Success is visible in two ways: javac printed nothing, and java printed the text.
Example 2: the wrong name (practical)
You save the same program as hello.java with a lowercase h, then run javac hello.java. The file name does not match the public class Hello. javac rejects it with a message about the class needing to be in Hello.java. Fix: rename the file to Hello.java, or change the class name to match the file. Then compile again.
Example 3: a program with an argument (realistic)
The args in main receives words typed after the class name. This program greets whoever you name, and falls back to a default when nobody is named:
public class Greet {
public static void main(String[] args) {
String name = "world";
if (args.length > 0) {
name = args[0];
}
System.out.println("Hello, " + name + "!");
}
}Save as Greet.java, then:
javac Greet.java
java Greet
java Greet AminaThe outputs are Hello, world! and Hello, Amina!. Command-line arguments are how many backend tools and scripts are configured. Here the compile happened once, and the program ran twice with different input. That is the translated-book idea at work: translate once, read many times.
Backend Insight
Backend services are started from the terminal, or by scripts that run the same commands, such as java followed by a name or a packaged file, with arguments or settings. When a deployment fails, the first useful questions are the ones from this lesson:
- Did the build (compile) succeed? Look for
javacor build-tool output. - Did the launch fail because of the command, for instance a wrong class name or a missing file?
- Or did the program start and then fail while running?
Build tools such as Maven and Gradle (covered in BEG-054) call javac for you, with many more options. The messages you read here, a file name and a line number and a short reason, are the same kind you will read in their output.
Common Mistakes
Mistake 1: Class name not matching the file name
- Incorrect: public class
Helloinhello.javaor inGreeting.java. - Correct: public class
HelloinHello.java, capitals included.
Mistake 2: Running with the extension
- Incorrect:
java Hello.class(orjava Hello.javain an older setup that does not support source-file mode). - Correct:
java Hello.
Mistake 3: Running from the wrong folder
If you are not in the folder that holds Hello.class, java Hello may fail to find the class. Use pwd and ls (BEG-006) to check where you are. Packages and class paths change this picture later, but for a single file in the current folder, being in the right folder is what matters.
Mistake 4: Forgetting to recompile
You edit and save Hello.java, then run java Hello and see the old behaviour. The .class file was not rebuilt. Compile again.
Mistake 5: Believing "it compiled" means "it works"
A silent javac means the language rules were followed. It says nothing about what happens when the program runs on real data.
Exercises
Try each exercise yourself before opening the solutions. Do the hands-on items on your own machine. The exact output may differ slightly depending on your JDK version and operating system.
Level A: Foundation
A1. List the two commands that compile and then run a class named Planner, defined in the file Planner.java.
أظهر الحل A1
A1. javac Planner.java, then java Planner.
A2. After a successful javac Planner.java, what new file appears, and what does it contain?
أظهر الحل A2
A2. Planner.class, created in the same folder. It contains the bytecode for the class.
A3. True or false: java Planner.class is the correct way to run the program.
أظهر الحل A3
A3. False. java takes the class name: java Planner.
Level B: Application
B1. On your machine, create Hello.java as in the lesson, compile it, run it, and write down the exact output and the list of files in the folder before and after compiling.
أظهر الحل B1
B1. Before compiling: only Hello.java. After compiling: Hello.java and Hello.class. The run prints Hello from the terminal!.
B2. Change the message in Hello.java to include your name. Run java Hello without recompiling. Which message appears and why? Then compile and run again.
أظهر الحل B2
B2. The old message appears, because java runs Hello.class, which was built from the old source. Only after running javac Hello.java again does the new message appear.
B3. A class is declared as public class Report but the file is saved as report.java. What is the problem, and name two ways to fix it.
أظهر الحل B3
B3. The public class name Report does not match the file name report.java (capitalisation differs), so javac reports an error. Fix by renaming the file to Report.java, or by renaming the class to report (not recommended, since class names conventionally start with a capital letter).
Level C: Challenge
C1. Create Greet.java from Example 3. Run it with no argument, one argument, and two arguments (java Greet Amina Omar). Describe what happens to the second word and why.
أظهر الحل C1
C1. With no argument it prints Hello, world!. With one argument it greets that name. With two arguments it greets only the first one (Amina), because the program reads only args[0]. The second word is stored in args[1] but never used.
C2. Create a program that compiles but fails at run time, for example by reading args[0] when no arguments are given. Run it with no arguments and record the error. Classify it as compile-time or runtime, and explain how you could change the program so that it no longer crashes.
أظهر الحل C2
C2. For example, System.out.println(args[0]); compiles, but running java Name with no arguments stops with an ArrayIndexOutOfBoundsException (the exact message text varies by version). It is a runtime error, because the code is valid and the problem appears only for a specific input. To fix it, check args.length > 0 first, as in Greet.
Mini Challenge
Write a short, numbered "terminal recipe" for a classmate who has never compiled Java, covering: making a folder, creating the file, compiling, running, and the two most common errors and what each message tells you. Test it by following it yourself from a new, empty folder, and fix any step that did not work as written.
Check your work: the recipe uses javac with a file name and java with a class name, and mentions the file-name rule.
Summary & Next Lesson
Key takeaways
- Compile with
javac Hello.java, which producesHello.classand prints nothing when it succeeds. - Run with
java Hello. Use the class name, not the file name or.class. - A public class must be in a file with the same name plus
.java, capitals included. - A compile error message gives the file, the line number, and a short reason. Check the line above if the reported line looks fine.
- Edit, compile, and run in a loop. A program that compiles can still fail at run time.
Next lesson
You can now compile and run by hand. The next lesson, "Demo: compile, run, break, and fix Hello World in the terminal", repeats the cycle with deliberate mistakes so that you see both kinds of error, and prepares you for the lab.
Self-check
- What does
javactake as its argument, and what doesjavatake? - What file does
javac Hello.javacreate? - What is wrong with
java Hello.class? - What must be true about a public class
Helloand its file? - A program compiled with no errors. Does that prove it works?
أظهر الإجابات
javactakes a file name (Hello.java).javatakes a class name (Hello).Hello.class, containing bytecode.javaexpects a class name, so the extension must be omitted:java Hello.- The file must be named
Hello.java, with the same capitalisation. - No. It only proves that the language rules were followed. The program can still fail at run time or give wrong results.
References
- Oracle,
javacommand reference, JDK 21. It says the launcher takes the fully qualified class name to run and calls itspublic static void main(String[]), passes later arguments tomain, and documents source-file mode (java HelloWorld.java). - Oracle,
javaccommand reference, JDK 21. It says each compiled type produces a class file named after the class, placed by default next to the source file. - Oracle, The Java Tutorials: "Hello World!" for Microsoft Windows. It walks through saving
HelloWorldApp.java, runningjavac, and runningjavawith the class name, and warns that names are case-sensitive. - Oracle, The Java Language Specification, Java SE 21, section 7.6. It describes the public-class-in-matching-file rule as one a host system may enforce.
- Oracle, The Java Language Specification, Java SE 21, section 15.6, and the
ArithmeticExceptionAPI page. They state that integer division by zero throwsArithmeticException. The exact text of the message, and the exact wording of the compile errors shown, were not verified against a live run and may differ by JDK version.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.