נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
1
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

מה זה תכנות? JVM, JDK, IntelliJ ו-jshellWhat is programming? JVM, JDK, IntelliJ & jshell

איך מחשב מבצע הוראות, איך Java רצה (קוד, javac, bytecode, JVM), התקנת JDK ו-IntelliJ ב-Windows וב-Mac, jshell, והתוכנית הראשונה.

How a computer follows instructions, how Java runs (source, javac, bytecode, the JVM), installing the JDK and IntelliJ on Windows and Mac, jshell, and a first program.

01מה זה תכנות?What is programming?

מחשב הוא מכונה מהירה מאוד, אבל הוא לא מנחש. הוא עושה בדיוק מה שאומרים לו, ורק את זה. תוכנית היא רשימת הוראות שהמחשב מבצע לפי הסדר, ותכנות הוא כתיבת ההוראות האלה בשפה שהמחשב יודע לבצע.

A computer is a very fast machine, but it never guesses. It does exactly what it's told, and only that. A program is a list of instructions the computer carries out in order, and programming is writing those instructions in a language the computer can run.

הטקסט שאנחנו כותבים נקרא קוד. הנה תוכנית Java שלמה. היא נראית ארוכה בשביל שתי הדפסות, ובהמשך המפגש נבין כל מילה בה. בינתיים מספיק לשים לב לשתי השורות שמתחילות ב-System.out.println: כל אחת אומרת "תציג את הטקסט הזה".

The text we write is called code. Here's a complete Java program. It looks long for two prints, and later this session we'll understand every word of it. For now, just notice the two lines that start with System.out.println: each one says "show this text".

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("שלום! זו התוכנית הראשונה שלי ב-Java");
        System.out.println("Java מבצעת שורה אחרי שורה");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello! This is my first Java program");
        System.out.println("Java runs one line after another");
    }
}
פלטOutput
שלום! זו התוכנית הראשונה שלי ב-Java
Java מבצעת שורה אחרי שורה
Hello! This is my first Java program
Java runs one line after another
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

תחשבו על רובוט-שף שמקבל מתכון. הוא יבצע "שבור 2 ביצים" בדיוק, צעד אחרי צעד. אבל אם כתבתם "שבור 2 ביצם", הוא לא ינחש שהתכוונתם לביצים. הוא יעצור ויגיד "לא הבנתי". ככה בדיוק מתנהגת Java: מדויקת, צייתנית, ובלי דמיון.

Think of a robot chef following a recipe. It will "crack 2 eggs" exactly, step by step. But if you wrote "crack 2 egs", it won't guess you meant eggs. It stops and says "I didn't understand". Java behaves exactly like that: precise, obedient, and with zero imagination.

טעות נפוצהCommon mistake

כותבים Println עם P גדולה. לבני אדם זה אותו דבר, אבל ל-Java אלה שתי מילים שונות לגמרי.

Writing Println with a capital P. To a person it's the same, but to Java they're two completely different words.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.Println("שלום");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.Println("Hello");
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: cannot find symbol
        System.out.Println("שלום");
                  ^
  symbol:   method Println(String)
  location: variable out of type PrintStream
1 error
Main.java:3: error: cannot find symbol
        System.out.Println("Hello");
                  ^
  symbol:   method Println(String)
  location: variable out of type PrintStream
1 error
בעברית פשוטה: In plain words: cannot find symbol אומרת "אני לא מכירה את השם הזה". השורה symbol: method Println(String) מראה בדיוק איזה שם: אין מתודה Println. מתקנים ל-println עם p קטנה.cannot find symbol means "I don't know this name". The line symbol: method Println(String) shows exactly which name: there's no method Println. Fix it to lowercase println.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

02למה דווקא Java?Why Java?

יש מאות שפות תכנות. Java היא אחת הוותיקות והנפוצות בעולם: היא מריצה שרתים של חברות ענק, אפליקציות Android, מערכות בנקאיות, כלי ביג-דאטה, וגם את Minecraft במחשב. מי שיודע Java טוב מוצא עבודה כמעט בכל מקום.

There are hundreds of programming languages. Java is one of the oldest and most widely used: it runs servers at huge companies, Android apps, banking systems, big-data tools, and also Minecraft on the computer. Someone who knows Java well finds work almost anywhere.

החוזקה של JavaJava's strengthמה זה נותןWhat it gives youאיפה בקורסWhere in the course
טיפוסים ומהדר קפדןTypes and a strict compilerטעויות נתפסות עוד לפני שהתוכנית רצהMistakes are caught before the program even runsמפגשים 2, 22Sessions 2, 22
OOP: מחלקות ועצמיםOOP: classes and objectsמסדרים תוכנה גדולה לחלקים ברוריםBig software organized into clear partsחלקים 3-4Parts 3-4
ספרייה ענקיתA huge libraryרשימות, מילונים, קבצים ורשת בלי להתקין כלוםLists, maps, files and networking with nothing to installחלק 5Part 5
Threads ו-ConcurrencyThreads and concurrencyכמה דברים קורים באותו זמן, בבטחהSeveral things happen at once, safelyחלק 6Part 6
רץ בכל מקוםRuns everywhereאותה תוכנה ב-Windows, ב-Mac, ב-Linux ובדפדפןThe same program on Windows, Mac, Linux and the browserהסעיף הבאThe next section
אנלוגיה מהחייםReal-life analogy

המהדר של Java הוא כמו מורה קפדנית שבודקת את שיעורי הבית לפני השיעור: היא לא תיתן לכם להגיש עבודה עם מילה חסרה. זה מתסכל בהתחלה, אבל זה חוסך הרבה הפתעות כשהתוכנה כבר עובדת אצל אנשים אמיתיים.

Java's compiler is like a strict teacher who checks your homework before class: she won't let you hand in work with a missing word. It's frustrating at first, but it saves a lot of surprises once the software is running for real people.

עוד דבר חשוב: מירכאות משנות הכול. מה שבתוך מירכאות כפולות הוא טקסט (מחרוזת), ו-Java מציגה אותו כמו שהוא. מה שבלי מירכאות, Java מחשבת.

One more key thing: quotes change everything. Whatever is inside double quotes is text (a string), and Java shows it as is. Without quotes, Java calculates.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(2 + 3);
        System.out.println("2 + 3");
    }
}
פלטOutput
5
2 + 3
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

טעות נפוצהCommon mistake

משאירים חישוב באמצע. אחרי ה-+ חסר משהו, ולכן המהדר לא מבין את השורה בכלל, ושום דבר לא רץ.

Leaving a calculation half-written. Something is missing after the +, so the compiler can't understand the line at all, and nothing runs.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(2 +);
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: illegal start of expression
        System.out.println(2 +);
                              ^
1 error
בעברית פשוטה: In plain words: illegal start of expression היא שגיאת קומפילציה: השורה לא כתובה לפי חוקי ה-תחביר. ה-^ מצביע בערך למקום שבו המהדר הסתבך. משלימים: System.out.println(2 + 3);.illegal start of expression is a compile error: the line doesn't follow the syntax rules. The ^ points roughly to where the compiler got confused. Complete it: System.out.println(2 + 3);.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03איך Java רצה: javac, bytecode ו-JVMHow Java runs: javac, bytecode and the JVM

את הקוד של Java המחשב לא מריץ ישירות. יש שני שלבים: קודם המהדר javac קורא את כל הקוד, בודק שהוא תקין, ומתרגם אותו ל-bytecode: שפה פשוטה שנשמרת בקובץ ‎.class. אחר כך הפקודה java מפעילה את ה-JVM, "מחשב וירטואלי" שמבצע את ה-bytecode, שורה אחרי שורה, החל מ-main.

The computer doesn't run Java code directly. There are two steps: first the compiler javac reads all the code, checks it, and translates it into bytecode: a simple language stored in a .class file. Then the java command starts the JVM, a "virtual computer" that runs the bytecode step by step, starting at main.

שלבStepפקודהCommandמה נכנסGoes inמה יוצאComes out
1. קומפילציה1. Compilejavac Main.javaקוד שבני אדם כתבוCode people wroteMain.class עם bytecode, או שגיאת קומפילציהMain.class with bytecode, or a compile error
2. הרצה2. Runjava MainMain.classMain.classמה שהתוכנית מדפיסה, או חריגהWhat the program prints, or an exception
אנלוגיה מהחייםReal-life analogy

דמיינו מתכון שכתוב בעברית. המהדר מתרגם אותו פעם אחת ל"שפת הרובוטים" (bytecode). בכל מטבח בעולם יש רובוט שמדבר את השפה הזו (JVM): אחד ל-Windows, אחד ל-Mac, אחד ל-Linux ואפילו אחד לדפדפן. לכן את אותו מתכון מתורגם אפשר לתת לכל מטבח. בעולם של Java קוראים לזה "כותבים פעם אחת, רץ בכל מקום".

Picture a recipe written in English. The compiler translates it once into "robot language" (bytecode). Every kitchen in the world has a robot that speaks that language (a JVM): one for Windows, one for Mac, one for Linux and even one for the browser. So the same translated recipe can go to any kitchen. In the Java world this is called "write once, run anywhere".

ככה זה נראה בטרמינל אמיתי. javac לא מדפיסה כלום כשהכול תקין, אבל אחריה מופיע בתיקייה קובץ חדש, Main.class. את java מריצים עם שם המחלקה, בלי סיומת:

Here's how it looks in a real terminal. javac prints nothing when all is well, but afterwards a new file, Main.class, appears in the folder. You run java with the class name, no extension:

Terminal
javac Main.java
ls
java Main
פלטOutput
$ javac Main.java
$ ls
Main.class
Main.java
$ java Main
Hello from the terminal!

ב-Java 11 ומעלה יש גם קיצור לתוכנית של קובץ אחד: java Main.java מקמפל בזיכרון ומריץ מיד, בלי ליצור Main.class. נוח לניסויים, אבל בפרויקט אמיתי משתמשים בשני השלבים (או ב-IntelliJ, שעושה אותם בשבילנו).

From Java 11 there's also a shortcut for one-file programs: java Main.java compiles in memory and runs right away, without creating Main.class. Handy for experiments, but real projects use the two steps (or IntelliJ, which does them for us).

Terminal
java Main.java
פלטOutput
Compiled in memory, then run

נסו עכשיו בסימולטור. הוא מתנהג כמו טרמינל אמיתי (ב-Mac או ב-Windows), אבל הכול קורה בתוך העמוד. בתיקייה Downloads כבר מחכה קובץ Hello.java. בצעו את המשימות שמתחת:

Try it now in the simulator. It behaves like a real terminal (Mac or Windows), but everything happens inside this page. A file Hello.java is already waiting in Downloads. Complete the tasks below it:

סימולטור טרמינלTerminal simulator נסו בעצמכם. שום דבר כאן לא נוגע במחשב שלכם.Try it yourself. Nothing here touches your computer.
  • בדקו איזו גרסת Java מותקנת: java --versionCheck which Java version is installed: java --version
  • היכנסו לתיקייה: cd DownloadsGo into the folder: cd Downloads
  • ראו מה יש בה: ls (ב-Windows גם dir)See what's there: ls (on Windows dir works too)
  • קמפלו: javac Hello.java, והריצו שוב ls. מה הופיע?Compile: javac Hello.java, then run ls again. What appeared?
  • הריצו: java HelloRun it: java Hello
טעות נפוצהCommon mistake

מריצים java עם שם הקובץ המקומפל (Main.class) במקום עם שם המחלקה. java מחפשת מחלקה בשם "Main.class", ואין כזו.

Running java with the compiled file's name (Main.class) instead of the class name. java looks for a class called "Main.class", and there's none.

Terminal
javac Main.java
java Main.class
מה הטרמינל עונהWhat the terminal says
$ javac Main.java
$ java Main.class
Error: Could not find or load main class Main.class
Caused by: java.lang.ClassNotFoundException: Main.class
בעברית פשוטה: In plain words: Error: Could not find or load main class Main.class אומרת "לא מצאתי מחלקה בשם הזה". נותנים ל-java את שם המחלקה בלבד: java Main.Error: Could not find or load main class Main.class means "I found no class with this name". Give java just the class name: java Main.

04התקנת JDK 21 (Windows ו-Mac)Installing JDK 21 (Windows and Mac)

כדי לכתוב Java מתקינים JDK (Java Development Kit): הוא כולל את ה-JVM, את המהדר javac, את jshell ועוד כלים. בקורס משתמשים ב-Java 21, גרסת LTS שמקבלת עדכונים במשך שנים. מומלץ להוריד את Eclipse Temurin מהאתר adoptium.net: חינמי, רשמי ופתוח.

To write Java you install a JDK (Java Development Kit): it includes the JVM, the javac compiler, jshell and more tools. The course uses Java 21, an LTS version that gets updates for years. We recommend Eclipse Temurin from adoptium.net: free, official and open.

שםNameמה יש בוWhat's in itמתי צריךWhen you need it
JVMהמכונה שמריצה bytecodeThe machine that runs bytecodeתמיד, כדי להריץAlways, to run
JREJVM וספריות, בלי מהדרA JVM and libraries, no compilerרק להריץ תוכנות של אחריםOnly to run other people's programs
JDKJRE ועוד javac, jshell וכליםA JRE plus javac, jshell and toolsכדי לכתוב Java: זה מה שמתקיניםTo write Java: this is what you install

WindowsWindows

  1. ב-adoptium.net בוחרים Temurin 21 (LTS), מערכת Windows, ומורידים את קובץ ה-‎.msi.On adoptium.net choose Temurin 21 (LTS), Windows, and download the .msi file.
  2. מריצים את ההתקנה. במסך Custom Setup פותחים את Set JAVA_HOME variable ובוחרים "Will be installed on local hard drive". Add to PATH כבר מסומן.Run the installer. On the Custom Setup screen open Set JAVA_HOME variable and choose "Will be installed on local hard drive". Add to PATH is already on.
  3. מסיימים, סוגרים ופותחים מחדש את PowerShell (חלון ישן לא מכיר את ההתקנה החדשה), ובודקים:Finish, close and reopen PowerShell (an old window doesn't know about the new install), and check:
PowerShell
java --version
javac --version
פלט לדוגמהSample output
openjdk 21.0.5 2024-10-15 LTS
OpenJDK Runtime Environment Temurin-21.0.5+11 (build 21.0.5+11-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.5+11 (build 21.0.5+11-LTS, mixed mode, sharing)
javac 21.0.5

MacMac

  1. ב-adoptium.net בוחרים Temurin 21 (LTS) ו-macOS. במחשב עם שבב Apple (M1 ומעלה) בוחרים aarch64, ובמק ישן עם Intel בוחרים x64.On adoptium.net choose Temurin 21 (LTS) and macOS. On an Apple-chip Mac (M1 or later) pick aarch64; on an older Intel Mac pick x64.
  2. פותחים את קובץ ה-‎.pkg ועוברים על המסכים (Continue, Agree, Install).Open the .pkg file and go through the screens (Continue, Agree, Install).
  3. פותחים Terminal (‏Cmd+Space ומקלידים Terminal) ובודקים:Open Terminal (Cmd+Space and type Terminal) and check:
Terminal (Mac)
java --version
javac --version
פלט לדוגמהSample output
openjdk 21.0.5 2024-10-15 LTS
OpenJDK Runtime Environment Temurin-21.0.5+11 (build 21.0.5+11-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.5+11 (build 21.0.5+11-LTS, mixed mode, sharing)
javac 21.0.5
טיפTip

המספרים אצלכם יכולים להיות קצת שונים (למשל 21.0.6). כל גרסה שמתחילה ב-21 מתאימה לקורס. גרסה חדשה יותר (25) תעבוד גם היא.

Your numbers may be slightly different (say 21.0.6). Any version starting with 21 works for the course. A newer one (25) works too.

טעות נפוצהCommon mistake

ב-Windows ההתקנה לא הוסיפה את Java ל-PATH, או שהטרמינל נפתח לפני ההתקנה. הטרמינל לא יודע איפה javac נמצא.

On Windows the installer didn't add Java to PATH, or the terminal was opened before installing. The terminal doesn't know where javac is.

PowerShell
javac --version
מה הטרמינל עונהWhat the terminal says
javac : The term 'javac' is not recognized as the name of a cmdlet, function, script file, or operable program.
בעברית פשוטה: In plain words: "not recognized" אומר שהטרמינל לא מצא תוכנה בשם הזה. קודם סוגרים ופותחים PowerShell חדש. אם זה לא עוזר, מריצים שוב את ההתקנה ומסמנים Add to PATH ו-Set JAVA_HOME (פרטים במדריך הטכני)."not recognized" means the terminal found no program with that name. First close and open a new PowerShell. If that doesn't help, run the installer again and tick Add to PATH and Set JAVA_HOME (details in the tech guide).

05IntelliJ IDEA והתוכנית הראשונהIntelliJ IDEA and the first program

אפשר לכתוב Java בכל עורך טקסט ולהריץ מהטרמינל, אבל רוב המתכנתים עובדים ב-סביבת פיתוח. בקורס משתמשים ב-IntelliJ IDEA Community: חינמית, מסמנת טעויות עוד לפני שמריצים, משלימה קוד, ומריצה בלחיצה. (מעדיפים VS Code? גם אפשר, עם Extension Pack for Java. ההוראות במדריך הטכני.)

You can write Java in any text editor and run it from the terminal, but most programmers work in an IDE. The course uses IntelliJ IDEA Community: free, it marks mistakes before you run, completes code, and runs with one click. (Prefer VS Code? That works too, with the Extension Pack for Java. Instructions in the tech guide.)

  1. מורידים מ-jetbrains.com/idea/download את IntelliJ IDEA Community ומתקינים.Download IntelliJ IDEA Community from jetbrains.com/idea/download and install it.
  2. New Project: שם java-course, שפה Java, Build system IntelliJ, ו-JDK 21 (אם הוא לא ברשימה: Add JDK ובוחרים את התיקייה שהותקנה).New Project: name java-course, language Java, build system IntelliJ, and JDK 21 (if it's not listed: Add JDK and pick the installed folder).
  3. בעץ שמשמאל, קליק ימני על התיקייה src, ואז New ← Java Class, וכותבים Main.In the tree on the left, right-click the src folder, then New → Java Class, and type Main.
  4. בתוך המחלקה כותבים psvm ולוחצים Tab: IntelliJ כותב את כל השורה של main. בתוכה כותבים sout ו-Tab: מתקבל System.out.println();.Inside the class type psvm and press Tab: IntelliJ writes the whole main line. Inside it type sout and Tab: you get System.out.println();.
  5. לוחצים על המשולש הירוק שליד main ובוחרים Run. הפלט מופיע בחלון Run למטה.Click the green triangle next to main and choose Run. The output shows in the Run window at the bottom.
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("שלום מ-IntelliJ");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello from IntelliJ");
    }
}
פלטOutput
שלום מ-IntelliJ
Hello from IntelliJ
אנלוגיה מהחייםReal-life analogy

עורך טקסט רגיל הוא כמו מחברת ועט. IntelliJ הוא כמו סדנה מסודרת: יש בה מחברת, אבל גם מורה שמסמנת טעויות בזמן הכתיבה, מכונה שמשלימה מילים, וכפתור אחד שמקמפל ומריץ. מאחורי הכפתור הירוק IntelliJ מריץ בדיוק את מה שראינו: javac ואחריו java.

A plain text editor is like a notebook and a pen. IntelliJ is like a well-equipped workshop: there's a notebook, but also a teacher who marks mistakes as you write, a machine that finishes words, and one button that compiles and runs. Behind the green button IntelliJ runs exactly what we saw: javac, then java.

טעות נפוצהCommon mistake

שם המחלקה לא תואם לשם הקובץ: בקובץ Main.java כתוב public class Hello. ב-Java מחלקה ציבורית חייבת לגור בקובץ עם אותו שם בדיוק.

The class name doesn't match the file name: the file Main.java says public class Hello. In Java a public class must live in a file with exactly the same name.

Main.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hi");
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:1: error: class Hello is public, should be declared in a file named Hello.java
public class Hello {
       ^
1 error
בעברית פשוטה: In plain words: class Hello is public, should be declared in a file named Hello.java: המהדר מבקש להתאים. משנים את שם הקובץ ל-Hello.java (ב-IntelliJ: קליק ימני ← Refactor ← Rename), או את שם המחלקה ל-Main.class Hello is public, should be declared in a file named Hello.java: the compiler wants them to match. Rename the file to Hello.java (in IntelliJ: right-click → Refactor → Rename), or rename the class to Main.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06המבנה של תוכנית JavaThe shape of a Java program

עכשיו נפרק את התוכנית לחלקים. בכל תוכנית Java יש לפחות מחלקה אחת, ובתוכה מתודה בשם main. כשמריצים, ה-JVM נכנסת ל-main ומבצעת את המשפטים שבה מלמעלה למטה. כל משפט נגמר בנקודה-פסיק ;, וכל בלוק נפתח ב-{ ונסגר ב-}.

Now let's take the program apart. Every Java program has at least one class, and inside it a method called main. When you run it, the JVM goes into main and runs its statements top to bottom. Each statement ends with a semicolon ;, and each block opens with { and closes with }.

החלקThe partמה הוא אומרWhat it says
public class Main {פותחים מחלקה בשם Main. הקובץ חייב להיקרא Main.java.Open a class called Main. The file must be named Main.java.
public static void main(String[] args) {הדלת הראשית: כאן התוכנית מתחילה. את המשמעות של כל מילה נלמד בהמשך הקורס.The front door: the program starts here. We'll learn what each word means later in the course.
System.out.println(...);משפט אחד: הצג את מה שבסוגריים וירד שורה.One statement: show what's in the brackets and go to a new line.
// ...הערה: בשביל בני אדם. המהדר מדלג עליה.A comment: for people. The compiler skips it.
}סוגר בלוק: הראשון סוגר את main, השני את המחלקה.Closes a block: the first closes main, the second the class.

לחצו הבא בסימולציה וראו איך Java עוברת על התוכנית: היא מתחילה ב-main, מדלגת על ההערה, ומבצעת משפט אחרי משפט. שימו לב שמסך הפלט מתמלא שורה אחרי שורה.

Press Next in the simulation and watch Java walk through the program: it starts at main, skips the comment, and runs one statement after another. Notice the output screen filling up line by line.

סימולציהSimulationJava עוברת על התוכניתJava walks through the program

מה קורה עכשיוWhat happens now

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

תחשבו על בובות מטריושקה: המחלקה היא הבובה הגדולה, main היא הבובה שבתוכה, והמשפטים הם מה שבפנים. כל { פותח בובה וכל } סוגר אותה, ולכן הם תמיד באים בזוגות.

Think of Russian nesting dolls: the class is the big doll, main is the doll inside it, and the statements are what's inside that. Each { opens a doll and each } closes it, so they always come in pairs.

טעות נפוצהCommon mistake

שוכחים נקודה-פסיק בסוף משפט. לבני אדם זה פרט קטן, אבל למהדר זה כמו משפט בלי נקודה: הוא לא יודע איפה המשפט נגמר.

Forgetting the semicolon at the end of a statement. For people it's a small detail, but to the compiler it's like a sentence with no full stop: it doesn't know where the statement ends.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("שורה ראשונה")
        System.out.println("שורה שנייה");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("First line")
        System.out.println("Second line");
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: ';' expected
        System.out.println("שורה ראשונה")
                                         ^
1 error
Main.java:3: error: ';' expected
        System.out.println("First line")
                                        ^
1 error
בעברית פשוטה: In plain words: ';' expected אומרת "ציפיתי לנקודה-פסיק". ה-^ מצביע לסוף השורה שבה היא חסרה. מוסיפים ;. שימו לב: התוכנית לא הדפיסה אפילו את השורה השנייה, כי עם שגיאת קומפילציה שום דבר לא רץ.';' expected means "I expected a semicolon". The ^ points at the end of the line where it's missing. Add the ;. Notice: the program didn't print even the second line, because with a compile error nothing runs.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

טעות נפוצהCommon mistake

כותבים system עם s קטנה. System עם S גדולה היא מחלקה מוכנה של Java, ואילו system לא קיים בכלל.

Writing system with a small s. System with a capital S is a ready-made Java class, while system doesn't exist at all.

Main.java
public class Main {
    public static void main(String[] args) {
        system.out.println("Hi");
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: package system does not exist
        system.out.println("Hi");
              ^
1 error
בעברית פשוטה: In plain words: package system does not exist: המהדר חשב ש-system הוא שם של חבילה (תיקייה של מחלקות), ולא מצא כזו. מתקנים ל-System עם S גדולה.package system does not exist: the compiler thought system was a package name (a folder of classes), and found none. Fix it to System with a capital S.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הערות לא משנות את הפלט. הן שם בשביל מי שיקרא את הקוד מחר (כולל אתם).

Comments don't change the output. They're there for whoever reads the code tomorrow (you included).

עוד דוגמה: הערות שמסבירותOne more: comments that explain
Main.java
public class Main {
    public static void main(String[] args) {
        // מדפיס את לוח הזמנים של היום
        System.out.println("09:00 Java");   // השיעור הראשון
        /* הפסקה ארוכה */
        System.out.println("11:00 Lunch");
    }
}
public class Main {
    public static void main(String[] args) {
        // Prints today's schedule
        System.out.println("09:00 Java");   // first class
        /* a long break */
        System.out.println("11:00 Lunch");
    }
}
פלטOutput
09:00 Java
11:00 Lunch
09:00 Java
11:00 Lunch
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

07println, print ו-printfprintln, print and printf

System.out.println מציגה ערך ואז יורדת שורה. האחות שלה, System.out.print, מציגה בלי לרדת שורה, כך שההדפסה הבאה ממשיכה באותה שורה. ו-println() ריקה מדפיסה שורה ריקה.

System.out.println shows a value and then moves to a new line. Its sister, System.out.print, shows it without a new line, so the next print continues on the same line. An empty println() prints a blank line.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.print("אחת, ");
        System.out.print("שתיים, ");
        System.out.println("שלוש!");
        System.out.println();
        System.out.println("אחרי שורה ריקה");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.print("One, ");
        System.out.print("two, ");
        System.out.println("three!");
        System.out.println();
        System.out.println("After a blank line");
    }
}
פלטOutput
אחת, שתיים, שלוש!

אחרי שורה ריקה
One, two, three!

After a blank line
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

println היא כמו מכונת כתיבה שאחרי כל משפט מחזירה את הגלגלת לשורה חדשה. print כותבת ומשאירה את הגלגלת בדיוק איפה שעצרה.

println is like a typewriter that returns the carriage to a new line after each sentence. print types and leaves the carriage exactly where it stopped.

ה-אופרטור + עושה שני דברים שונים: בין מספרים הוא מחבר, ובין טקסט למשהו אחר הוא מדביק טקסט. Java קוראת משמאל לימין, ולכן כשיש כבר טקסט בהתחלה, כל + שאחריו מדביק. סוגריים מחשבים קודם:

The + operator does two different things: between numbers it adds, and between text and anything else it glues text together. Java reads left to right, so once there's text at the start, every + after it glues. Brackets calculate first:

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("1 + 1 = " + 1 + 1);
        System.out.println("1 + 1 = " + (1 + 1));
        System.out.println(1 + 1 + " = 1 + 1");
    }
}
פלטOutput
1 + 1 = 11
1 + 1 = 2
2 = 1 + 1
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

חשבון: + - * / ו-% (השארית מחלוקה). זהירות: כששני המספרים שלמים, / היא חלוקה של שלמים וזורקת את מה שאחרי הנקודה. מספיק שאחד מהם יהיה עם נקודה כדי לקבל תוצאה מדויקת:

Arithmetic: + - * / and % (the remainder of a division). Careful: when both numbers are whole, / is integer division and throws away what's after the point. One number with a decimal point is enough for an exact result:

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(7 + 3 * 2);
        System.out.println(7 / 2);
        System.out.println(7 / 2.0);
        System.out.println(7 % 2);
    }
}
פלטOutput
13
3
3.5
1
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ולטעימה: printf מדפיסה לפי תבנית. כל % בתבנית הוא מקום שמתמלא בערך הבא: %s לטקסט, %d למספר שלם, %.2f למספר עם 2 ספרות אחרי הנקודה, ו-%n לשורה חדשה. נעמיק בזה במפגש 3.

And a taste: printf prints by a template. Every % in the template is a slot filled by the next value: %s for text, %d for a whole number, %.2f for a number with 2 digits after the point, and %n for a new line. More in session 3.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.printf("%s בת %d%n", "נועה", 15);
        System.out.printf("%.2f%n", 10 / 3.0);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.printf("%s is %d%n", "Noa", 15);
        System.out.printf("%.2f%n", 10 / 3.0);
    }
}
פלטOutput
נועה בת 15
3.33
Noa is 15
3.33
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

טעות נפוצהCommon mistake

שוכחים מירכאות סביב טקסט. בלי מירכאות, המהדר חושב ש-Hello הוא שם של משתנה, ומחפש אותו.

Forgetting the quotes around text. Without quotes, the compiler thinks Hello is the name of a variable, and looks for it.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(Hello);
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:3: error: cannot find symbol
        System.out.println(Hello);
                           ^
  symbol:   variable Hello
  location: class Main
1 error
בעברית פשוטה: In plain words: cannot find symbol עם symbol: variable Hello: המהדר חיפש משתנה בשם Hello ולא מצא. טקסט תמיד בין מירכאות כפולות: "Hello".cannot find symbol with symbol: variable Hello: the compiler looked for a variable named Hello and found none. Text always goes between double quotes: "Hello".
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

כמה println אחד אחרי השני יוצרים ציור קטן. כל println מסיימת בשורה חדשה.

A few printlns in a row make a small picture. Each println ends with a new line.

עוד דוגמה: כרטיס ברכהOne more: a greeting card
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("*************");
        System.out.println("*  Hello!   *");
        System.out.println("*************");
        System.out.println("Made by me");
    }
}
פלטOutput
*************
*  Hello!   *
*************
Made by me
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

Java היא גם מחשבון: פיצה ב-84 שקלים לשלושה חברים, ואותו חשבון עם חלוקה של שלמים ובלעדיה.

Java is a calculator too: an 84-shekel pizza for three friends, with and without integer division.

עוד דוגמה: כמה עולה פיצה לכל אחדOne more: pizza per person
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println(84 / 3);
        System.out.println(85 / 3);
        System.out.println(85 / 3.0);
        System.out.println(85 % 3);
        System.out.println(2 * (3 + 1));
    }
}
פלטOutput
28
28
28.333333333333332
1
8
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

08jshell: לנסות שורה אחתjshell: try one line

לפעמים רוצים רק לבדוק משהו קטן: כמה זה 7 / 2? מה עושה "Java".length()? בשביל זה ה-JDK מגיע עם jshell. כותבים בטרמינל jshell, ואז כל שורה רצה מיד, בלי מחלקה, בלי main, ואפילו בלי נקודה-פסיק בסוף. זה לא מחליף תוכנית אמיתית, אבל זה מקום מצוין לנסות.

Sometimes you just want to check something small: what's 7 / 2? What does "Java".length() do? For that the JDK comes with jshell. Type jshell in the terminal, and every line runs at once, with no class, no main, not even a semicolon at the end. It does not replace a real program, but it's a great place to try things.

זו הרצה אמיתית של jshell (מ-JDK 21). אחרי jshell> מופיע מה שהקלדנו, ומתחת מה שהוא ענה:

This is a real jshell session (from JDK 21). After jshell> is what we typed, and below it is jshell's answer:

jshellפלט אמיתי מ-JDK 21Real output from JDK 21
jshell> 2 + 3
$1 ==> 5
jshell> "Java".length()
$2 ==> 4
jshell> 7 / 2
$3 ==> 3
jshell> 7 / 2.0
$4 ==> 3.5
jshell> int x = 5
x ==> 5
jshell> x * 10
$6 ==> 50
jshell> System.out.println("Hello from jshell")
Hello from jshell
jshell> 10 / 0
|  Exception java.lang.ArithmeticException: / by zero
|        at (#8:1)
jshell> /exit
|  Goodbye
אנלוגיה מהחייםReal-life analogy

jshell הוא כמו דף טיוטה ליד המחברת: מנסים עליו תרגיל קטן, רואים מה יוצא, ואז כותבים את התשובה המסודרת במחברת (בתוכנית אמיתית).

jshell is like scratch paper next to your notebook: try a small sum on it, see what comes out, then write the neat answer in the notebook (a real program).

טיפTip

ב-IntelliJ יש jshell מובנה: Tools ← JShell Console. בטרמינל יוצאים עם /exit.

IntelliJ has jshell built in: Tools → JShell Console. In the terminal, leave with /exit.

טעות נפוצהCommon mistake

כותבים משפט ישר בתוך המחלקה, כמו ב-jshell, בלי main. בקובץ אמיתי משפטים חייבים לגור בתוך מתודה.

Writing a statement straight inside the class, like in jshell, with no main. In a real file, statements must live inside a method.

Main.java
public class Main {
    System.out.println("Hi");
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:2: error: <identifier> expected
    System.out.println("Hi");
                      ^
Main.java:2: error: illegal start of type
    System.out.println("Hi");
                       ^
2 errors
בעברית פשוטה: In plain words: <identifier> expected: בתוך מחלקה המהדר מצפה להגדרות (מתודות ושדות), לא למשפטים. מכניסים את השורה לתוך public static void main(String[] args) { ... }.<identifier> expected: inside a class the compiler expects definitions (methods and fields), not statements. Put the line inside public static void main(String[] args) { ... }.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

09שני סוגי שגיאות: קומפילציה וזמן ריצהTwo kinds of errors: compile time and run time

ב-Java יש שני סוגים עיקריים של שגיאות, וחשוב לדעת להבדיל ביניהם. שגיאת קומפילציה נמצאת על ידי javac לפני שהתוכנית רצה: שום שורה לא מתבצעת עד שמתקנים. חריגה קורית בזמן ריצה: הקוד תקין מבחינת התחביר, התוכנית מתחילה לרוץ, ובשורה מסוימת משהו בלתי אפשרי קורה.

Java has two main kinds of errors, and it's important to tell them apart. A compile error is found by javac before the program runs: not a single line runs until it's fixed. An exception happens at run time: the syntax is fine, the program starts running, and on some line something impossible happens.

שגיאת קומפילציהCompile errorחריגה (exception)Exception
מי מוצאWho finds itjavacה-JVM, בזמן ריצהThe JVM, while running
מתיWhenלפני שמשהו רץBefore anything runsבאמצע הריצהIn the middle of the run
איך זה נראהWhat it looks likeMain.java:3: error: ...Exception in thread "main" ...
מה כבר הודפסWhat already printedכלוםNothingכל מה שלפני השורה הבעייתיתEverything before the bad line

כך קוראים שגיאת קומפילציה: שם הקובץ ומספר השורה, המילה error, ההסבר, ואז השורה עצמה עם ^ מתחת למקום הבעייתי.

Here's how to read a compile error: the file name and line number, the word error, the explanation, then the line itself with a ^ under the problem spot.

טעות נפוצהCommon mistake

שוכחים לסגור מירכאות. המהדר לא יודע איפה הטקסט נגמר.

Forgetting to close the quotes. The compiler doesn't know where the text ends.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("ההתחלה");
        System.out.println("הסוף);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("The start");
        System.out.println("The end);
    }
}
מה javac עונה (הקוד לא מתקמפל)What javac says (the code doesn't compile)
Main.java:4: error: unclosed string literal
        System.out.println("הסוף);
                           ^
1 error
Main.java:4: error: unclosed string literal
        System.out.println("The end);
                           ^
1 error
בעברית פשוטה: In plain words: unclosed string literal = "מחרוזת שלא נסגרה". מוסיפים " לפני הסוגר. ושימו לב: אפילו השורה הראשונה, שהייתה תקינה, לא הודפסה. זו שגיאת קומפילציה.unclosed string literal = "a string that was never closed". Add the " before the bracket. And notice: even the first line, which was fine, didn't print. That's a compile error.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

וכך קוראים חריגה: השורה הראשונה אומרת מה קרה (סוג החריגה והודעה), והשורות שמתחילות ב-at הן ה-stack trace, שאומר איפה: באיזו מתודה ובאיזו שורה.

And here's how to read an exception: the first line says what happened (the exception type and a message), and the lines starting with at are the stack trace, which says where: in which method and on which line.

טעות נפוצהCommon mistake

מחלקים מספר שלם באפס. התחביר תקין, ולכן הקומפילציה עוברת והשורה הראשונה אפילו מודפסת, אבל בשורה השנייה ה-JVM נתקלת בחשבון בלתי אפשרי.

Dividing a whole number by zero. The syntax is fine, so compilation succeeds and the first line even prints, but on the second line the JVM hits impossible arithmetic.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("מחשבים...");
        System.out.println(10 / 0);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Calculating...");
        System.out.println(10 / 0);
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
מחשבים...
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:4)
Calculating...
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.main(Main.java:4)
בעברית פשוטה: In plain words: java.lang.ArithmeticException: / by zero היא חריגה: "חלוקה באפס". השורה at Main.main(Main.java:4) אומרת שזה קרה ב-main, בשורה 4. ההדפסה הראשונה כן הופיעה, כי היא רצה לפני הקריסה.java.lang.ArithmeticException: / by zero is an exception: "division by zero". The line at Main.main(Main.java:4) says it happened in main, on line 4. The first print did appear, because it ran before the crash.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

שגיאת קומפילציה היא כמו בדיקת איות לפני ששולחים מכתב: המכתב לא יוצא עד שמתקנים. חריגה היא כמו רכב שיצא לדרך ונתקע באמצע: הדרך עד שם כבר נעשתה.

A compile error is like a spellcheck before sending a letter: the letter doesn't go out until it's fixed. An exception is like a car that set off and broke down halfway: the road up to there was already travelled.

הדביקו כאן כל הודעת שגיאה שקיבלתם, והמפענח יסביר במילים פשוטות מה היא אומרת ואיפה לחפש:

Paste any error message you got here, and the decoder explains in plain words what it says and where to look:

מפענח שגיאותError decoder

הדביקו כאן הודעת שגיאה של javac או של Java (כולל השורה הראשונה) ולחצו פענוח.

Paste an error message from javac or from Java (including the first line) and press Decode.

כאן אין קריסה, אבל שימו לב לסדר: Java מבצעת שורה אחרי שורה, ולכן ההודעה האחרונה מופיעה רק בסוף.

No crash here, but notice the order: Java runs line by line, so the last message appears only at the end.

עוד דוגמה: מה הודפס לפני הקריסהOne more: what printed before the crash
Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("שלב 1");
        System.out.println("שלב 2: " + (10 / 2));
        System.out.println("סיימנו");
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Step 1");
        System.out.println("Step 2: " + (10 / 2));
        System.out.println("Done");
    }
}
פלטOutput
שלב 1
שלב 2: 5
סיימנו
Step 1
Step 2: 5
Done
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich