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

JavaJava

כל הסיכומיםAll summaries

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

The key points of every session. Each session also has a full summary page with a cheatsheet and an error table.

חלקPart 1: יסודותFoundations

מפגשSession 1: מה זה תכנות? JVM, JDK, IntelliJ ו-jshellWhat is programming? JVM, JDK, IntelliJ & jshell

  • תוכנית היא רשימת הוראות שהמחשב מבצע לפי הסדרA program is a list of instructions the computer carries out in order
  • המחשב לא מנחש: הוא עושה בדיוק מה שכתובThe computer never guesses: it does exactly what's written
  • Java רצה בשרתים, ב-Android, בבנקים, במערכות נתונים ובמשחקיםJava runs servers, Android, banks, data systems and games
  • ה-מהדר בודק את הקוד לפני שהוא רץ, ותופס הרבה טעויות מוקדםThe compiler checks the code before it runs, and catches many mistakes early
  • שני שלבים: javac Main.java מקמפל, java Main מריץTwo steps: javac Main.java compiles, java Main runs
  • ה-מהדר יוצר bytecode בקובץ ‎.class, וה-JVM מריצה אותוThe compiler makes bytecode in a .class file, and the JVM runs it
  • מתקינים JDK 21 (LTS), למשל Eclipse Temurin מ-adoptium.netInstall JDK 21 (LTS), for example Eclipse Temurin from adoptium.net
  • בודקים בטרמינל: java --version וגם javac --versionCheck in the terminal: java --version and also javac --version
  • IntelliJ IDEA Community היא סביבת פיתוח חינמית: עורך, הרצה ודיבוג במקום אחדIntelliJ IDEA Community is a free IDE: editor, running and debugging in one place

מפגשSession 2: משתנים וטיפוסים פרימיטיבייםVariables & primitive types

  • משתנה: קופסה עם שם ששומרת ערך.variable: A named box that holds a value.
  • טיפוס: מה מותר לשים בקופסה:type: What may go into a box:
  • ב-Java כותבים קודם את הטיפוס, אחר כך את השם, ואז = והערך.In Java you write the type first, then the name, then = and the value.
  • = הוא השמה: "שים בקופסה".= is an assignment: "put in the box".
  • int למספרים שלמים, double למספרים עם נקודה, boolean ל-true/false, char לתו אחד בין גרשיים בודדים, ו-long למספרים שלמים ענקיים (עם L בסוף).int for whole numbers, double for numbers with a point, boolean for true/false, char for one character in single quotes, and long for huge whole numbers (with an L at the end).
  • מ-int ל-double Java ממירה לבד (אין מה לאבד).From int to double Java converts by itself (nothing is lost).
  • בכיוון ההפוך צריך המרה מפורשת (cast) מפורש, והחלק העשרוני נחתך (לא מעוגל).The other way needs an explicit cast, and the decimal part is cut off (not rounded).
  • int מגיע עד 2147483647.int goes up to 2147483647.
  • אם עוברים אותו, אין שגיאה: התוצאה פשוט "מתגלגלת" למספר שלילי (גלישה).Go past it and there's no error: the result just "wraps around" to a negative number (overflow).

מפגשSession 3: String ו-StringBuilderString & StringBuilder

  • לא משתנה (immutable): עצם שאי אפשר לשנות אחרי שנוצר.immutable: An object that can't change once created.
  • מאגר המחרוזות (String pool): אזור שבו Java שומרת מחרוזות שנכתבו בקוד (ליטרלים).string pool: An area where Java keeps strings written in the code (literals).
  • String הוא עצם, ויש לו מתודות.A String is an object with methods.
  • האינדקס מתחיל מ-0.The index starts at 0.
  • המתודות מחזירות מחרוזת חדשה, והמקורית נשארת כמו שהיא.The methods return a new string, and the original stays as it is.
  • רוצים לשמור את השינוי?Want to keep the change?
  • == בודק אם שתי הפניות מצביעות לאותו עצם.== checks whether two references point to the same object.
  • equals בודק אם התוכן זהה.equals checks whether the contents match.
  • בתבנית כל % מתמלא בערך הבא.In a template every % is filled by the next value.

מפגשSession 4: תנאים ו-switch החדשConditions & the new switch

  • תנאי: שאלה של כן או לא שהתוכנית בודקת, למשל age >= 18.condition: A yes-or-no question the program checks, like age >= 18.
  • ביטוי בוליאני: ביטוי שהערך שלו הוא true או false:boolean expression: An expression whose value is true or false:
  • Java בודקת את התנאים מלמעלה למטה, ומבצעת רק את הענף הראשון שהתנאי שלו true.Java checks the conditions top to bottom and runs only the first branch whose condition is true.
  • else תופס את כל השאר.else catches everything else.
  • == שווה, != שונה, < <= > >=.== equal, != not equal, < <= > >=.
  • מחברים: && וגם, || או, ! לא.Joiners: && and, || or, ! not.
  • ב-switch החדש כל case עם -> מריץ רק את עצמו (בלי break), אפשר לשים כמה ערכים בשורה, ואפשר לשמור את התוצאה במשתנה.In the new switch each case with -> runs only itself (no break), several values can share a line, and the result can go into a variable.
  • default לכל השאר.default for everything else.
  • כשענף ב-switch צריך כמה שורות, פותחים בלוק ומחזירים עם yield.When a switch branch needs several lines, open a block and hand back the value with yield.

מפגשSession 5: לולאותLoops

  • לולאה: קוד שחוזר שוב ושוב:loop: Code that repeats:
  • סיבוב (איטרציה): פעם אחת שבה גוף הלולאה רץ.iteration: One time the loop body runs.
  • שלושה חלקים בסוגריים: התחלה (int i = 1), תנאי להמשך (i <= 3), ושינוי בסוף כל סיבוב (i++).Three parts in the brackets: a start (int i = 1), a condition to keep going (i <= 3), and a change at the end of each round (i++).
  • צפו בסימולציה איך i עולה, ואיך שורת ה-for נבדקת שוב בכל סיבוב.Watch in the simulation how i goes up, and how the for line is checked again each round.
  • צובר מתחיל לפני הלולאה, ובכל סיבוב מוסיפים לו.An accumulator starts before the loop, and each round adds to it.
  • בסוף הוא מחזיק את התוצאה.At the end it holds the result.
  • while בודק לפני כל סיבוב, ומתאים כשלא יודעים כמה סיבובים יהיו.while checks before every round, and suits cases where you don't know how many rounds there'll be.
  • do-while בודק בסוף, ולכן רץ לפחות פעם אחת.do-while checks at the end, so it runs at least once.
  • for-each עובר על כל פריט.for-each goes over every item.

מפגשSession 6: Scanner וקלטScanner & input

  • קלט: מה שהמשתמש מקליד לתוכנית בזמן שהיא רצה.input: What the user types into the program while it runs.
  • Scanner: מחלקה שקוראת קלט:Scanner: A class that reads input:
  • מייבאים את Scanner, יוצרים אחד על System.in, וקוראים.Import Scanner, create one on System.in, and read.
  • התוכנית מחכה עד שמקלידים ולוחצים Enter.The program waits until you type and press Enter.
  • nextInt קורא רק את המספר ומשאיר את ה-Enter בצד.nextInt reads only the number and leaves the Enter behind.
  • ה-nextLine שאחריו מקבל שורה ריקה!The nextLine after it gets an empty line!
  • hasNextInt() שואל אם המילה הבאה היא מספר, בלי לקרוא אותה.hasNextInt() asks whether the next token is a number without reading it.
  • אם לא, קוראים אותה עם next() וזורקים.If not, read it with next() and drop it.
  • לולאה שקוראת פקודה, switch שמחליט מה לעשות, ומשתנה שאומר מתי לצאת.A loop that reads a command, a switch that decides what to do, and a variable that says when to quit.

חלקPart 2: מתודות ומערכיםMethods & arrays

מפגשSession 7: מתודות, overloading ו-pass-by-valueMethods, overloading & pass-by-value

  • פרמטר: משתנה בהגדרת המתודה שמקבל ערך מבחוץ:parameter: A variable in the method's definition that receives a value from outside:
  • ארגומנט: הערך שנותנים לפרמטר בקריאה:argument: The value given to a parameter in a call:
  • מתודה היא פעולה עם שם.A method is a named action.
  • בהגדרה: טיפוס ההחזרה, שם ופרמטרים.In the definition: the return type, a name and parameters.
  • מתודה void לא מחזירה ערך.A void method returns nothing.
  • מתודות יכולות לקרוא זו לזו, וכל קריאה מקבלת מסגרת משלה.Methods can call each other, and each call gets its own frame.
  • Java בוחרת איזו גרסה להפעיל לפי הטיפוסים ומספר הארגומנטים.Java picks which version to run from the types and the number of arguments.
  • המתודה מקבלת עותק של כל ארגומנט.The method gets a copy of every argument.
  • x הוא עותק של 1, ולכן n לא משתנה.x is a copy of 1, so n doesn't change.

מפגשSession 8: מערכים ומערכים דו-ממדייםArrays & 2D arrays

  • מערך: שורה של תאים צמודים מאותו טיפוס, בגודל קבוע:array: A row of cells of the same type, with a fixed size:
  • length: מספר התאים במערך:length: The number of cells in an array:
  • מערך בגודל קבוע.An array has a fixed size.
  • התא הראשון באינדקס 0 והאחרון ב-length - 1.The first cell is index 0 and the last is length - 1.
  • for רגיל כשצריך את האינדקס, for-each כשצריך רק את הערכים.A plain for when you need the index, a for-each when you only need the values.
  • למקסימום מתחילים מהתא הראשון.For a maximum, start from the first cell.
  • b = a מעתיק את ההפניה, לא את המערך: שניהם מצביעים לאותו עצם (שתי הפניות לאותו עצם).b = a copies the reference, not the array: both point to the same object (aliasing).
  • clone() יוצר מערך חדש.clone() makes a new array.
  • Arrays.sort ממיין במקום.Arrays.sort sorts in place.

מפגשSession 9: ArrayList ו-HashMap ראשוניםFirst ArrayList & HashMap

  • ArrayList: רשימה שגדלה לבד:ArrayList: A list that grows by itself:
  • HashMap: מילון של מפתח וערך:HashMap: A key-value map:
  • בניגוד למערך, ל-ArrayList אין גודל קבוע.Unlike an array, an ArrayList has no fixed size.
  • add מוסיף לסוף, get(i) קורא, set מחליף, remove מוחק (והשאר זזים).add appends, get(i) reads, set replaces, remove deletes (and the rest shift).
  • אוספים מחזיקים רק עצמים, ולכן כותבים List<Integer>.Collections hold only objects, so you write List<Integer>.
  • autoboxing: Java ממירה בין int ל-Integer לבד.Autoboxing: Java converts between int and Integer by itself.
  • כמו במערך, same = names לא מעתיק את הרשימה: שתי הפניות לאותו עצם.As with arrays, same = names doesn't copy the list: two references to the same object.
  • בזיכרון רואים רשימה אחת ושני חצים.In memory you see one list and two arrows.
  • HashMap ממפה מפתח לערך.A HashMap maps a key to a value.

מפגשSession 10: static מול instancestatic vs instance

  • חבר static: שדה או מתודה ששייכים למחלקה עצמה, בעותק אחד:static member: A field or method that belongs to the class itself, in one copy:
  • חבר מופע: שדה או מתודה בלי static:instance member: A field or method without static:
  • שדה בלי static הוא שדה של העצם: ל-a ול-b יש n נפרד.A field without static is an object's field: a and b each have their own n.
  • בזיכרון רואים שני עצמי Counter שונים ב-heap.In memory you see two separate Counter objects on the heap.
  • static int count שייך למחלקה: יש רק אחד, וכל עצם חדש מעלה אותו.static int count belongs to the class: there's only one, and each new object bumps it.
  • ב-stack הוא מופיע בתור static, מחוץ לכל עצם, ו-id הוא של כל כרטיס בנפרד.In the stack it shows up as static, outside every object, while id belongs to each ticket.
  • ה-JVM קוראת ל-main בלי ליצור עצם, ולכן הוא static.The JVM calls main without creating an object, so it's static.
  • מתוך הקשר סטטי אי אפשר לקרוא למתודה של עצם.From a static context you can't call an object's method.
  • non-static method square(int) cannot be referenced from a static context:non-static method square(int) cannot be referenced from a static context:

מפגשSession 11: דיבוג ב-IntelliJDebugging in IntelliJ

  • דיבאגר: כלי שמריץ את התוכנית לאט, עוצר איפה שביקשתם ומראה את ערכי המשתנים.debugger: A tool that runs the program slowly, stops where you asked and shows the variables' values.
  • נקודת עצירה: נקודה אדומה שמסמנים בלחיצה ליד מספר השורה.breakpoint: A red dot you set by clicking next to a line number.
  • השורה הראשונה אומרת מה קרה (ArithmeticException: / by zero).The first line says what happened (ArithmeticException: / by zero).
  • השורות at אומרות איפה: העליונה היא המקום שבו זה נשבר, והבאות הן מי שקרא לו.The at lines say where: the top one is where it broke, and the next ones are who called it.
  • "צפו בזה רץ" עושה בדיוק מה ש-Step Over עושה ב-IntelliJ: שורה אחרי שורה, עם הערכים של המשתנים."Watch it run" does exactly what Step Over does in IntelliJ: line after line, with the variables' values.
  • כאן הסכום יוצא 10 במקום 15.Here the sum comes out 10 instead of 15.
  • כשאין דיבאגר בהישג יד, מדפיסים את המשתנים בתוך הלולאה.When there's no debugger at hand, print the variables inside the loop.
  • מסמנים את השורות ב-DEBUG כדי למצוא ולמחוק אותן אחר כך.Mark the lines with DEBUG so you can find and delete them later.
  • `StringIndexOutOfBoundsException:`StringIndexOutOfBoundsException:

מפגשSession 12: חריגות בסיסיותBasic exceptions

  • try ו-catch: `try { ...try and catch: `try { ...
  • finally: בלוק שרץ אחרי try/catch תמיד:finally: A block that runs after try/catch always:
  • Integer.parseInt("12a") זורקת NumberFormatException.Integer.parseInt("12a") throws a NumberFormatException.
  • אף אחד לא תופס אותה, ולכן התוכנית נעצרת, Java מדפיסה stack trace, והשורה האחרונה לא רצה.Nobody catches it, so the program stops, Java prints a stack trace, and the last line never runs.
  • עוטפים את מה שעלול להיכשל ב-try.Wrap what might fail in a try.
  • כשנזרקת חריגה, Java קופצת ל-catch המתאים, ואחריו התוכנית ממשיכה.When an exception is thrown, Java jumps to the matching catch, and then the program goes on.
  • 10 / 0 זורק ArithmeticException.10 / 0 throws an ArithmeticException.
  • השורה הבאה ב-try מדולגת, ה-catch רץ, ואז finally.The next line in the try is skipped, the catch runs, then finally.
  • מתודה שמקבלת ערך לא הגיוני זורקת IllegalArgumentException עם הודעה ברורה: מה מותר ומה התקבל.A method that gets a nonsense value throws an IllegalArgumentException with a clear message: what's allowed and what came in.

חלקPart 3: OOP: היסודותOOP: the basics

מפגשSession 13: מחלקות ועצמיםClasses & objects

  • עצם: מופע של מחלקה:object: An instance of a class:
  • שדה: משתנה שמוגדר בתוך מחלקה, מחוץ למתודות.field: A variable defined inside a class, outside the methods.
  • class Book מתארת מה יש לכל ספר: שדות (title, pages) ומתודות (describe).class Book describes what every book has: fields (title, pages) and methods (describe).
  • כל new Book() יוצר עצם חדש עם שדות משלו.Every new Book() makes a new object with its own fields.
  • b = a מעתיק את החץ: שני המשתנים מצביעים על אותו ספר, ושינוי דרך b נראה דרך a.b = a copies the arrow: both variables point to the same book, and a change through b shows through a.
  • c = null הוא חץ שלא מצביע לשום מקום.c = null is an arrow pointing nowhere.
  • מערך חדש של עצמים מלא ב-null.A new array of objects is full of null.
  • כשהלולאה מגיעה לתא הריק, b.title מנסה לקרוא שדה של כלום.When the loop reaches the empty cell, b.title tries to read a field of nothing.
  • Cannot read field "title" because "b" is null:Cannot read field "title" because "b" is null:

מפגשSession 14: בנאים ו-thisConstructors & this

  • בנאי: "מתודה" מיוחדת בשם המחלקה, בלי טיפוס החזרה, שרצה ב-new:constructor: A special "method" named after the class, with no return type, that runs on new:
  • this: הפניה לעצם הנוכחי.this: A reference to the current object.
  • בנאי רץ ב-new ומקבל ערכים.A constructor runs on new and takes values.
  • this.title הוא השדה, title הוא הפרמטר.this.title is the field, title is the parameter.
  • בנאי קצר מעביר את העבודה לבנאי המלא עם this(title, "unknown").A short constructor hands the work to the full one with this(title, "unknown").
  • כך האתחול כתוב במקום אחד.That way the setup lives in one place.
  • ברגע שכתבתם Book(String title), Java כבר לא נותנת Book().As soon as you write Book(String title), Java no longer gives you Book().
  • javac עוצר ומסביר מה נדרש ומה נמצא.javac stops and explains what's required and what was found.
  • כשהבנאי מתחיל, a כבר 5 (האתחול שליד השדה רץ קודם), ו-b עדיין 0.When the constructor starts, a is already 5 (the initializer next to the field ran first), and b is still 0.

מפגשSession 15: Encapsulation, getters, setters ו-immutabilityEncapsulation, getters, setters & immutability

  • כימוס: העצם שומר על הנתונים שלו בעצמו:encapsulation: The object guards its own data:
  • private: שדה או מתודה שנגישים רק מתוך המחלקה עצמה.private: A field or method reachable only inside its own class.
  • rating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי.rating is private, so the only way to change it is setRating, which throws on an illegal value.
  • הכלל "בין 1 ל-5" לא נשבר אף פעם.The rule "between 1 and 5" is never broken.
  • ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.
  • בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה.In an immutable object a "move" creates a new point.
  • בזיכרון רואים שתי נקודות: p נשארה (1, 2).In memory you see two points: p stayed (1, 2).
  • balance has private access in Account:balance has private access in Account:
  • מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5

מפגשSession 16: static, final וקבועיםstatic, final & constants

  • הפניה final: final int[] a אומר שאי אפשר להצביע עם a על מערך אחר.final reference: final int[] a means a can't be pointed at another array.
  • מספר קסם: מספר שמופיע בקוד בלי הסבר (0.17, 56).magic number: A number in the code with no explanation (0.17, 56).
  • משתנה final מקבל ערך פעם אחת.A final variable gets a value once.
  • ניסיון לשנות אותו נעצר בקומפילציה.Trying to change it is stopped at compile time.
  • MIN_RATING ו-MAX_RATING הם קבועים של המחלקה.MIN_RATING and MAX_RATING are class constants.
  • count הוא מונה static אחד, ו-id הוא שדה final של כל ספר, שנקבע פעם אחת בבנאי.count is one static counter, and id is a final field of each book, set once in the constructor.
  • final int[] scores נועל את החץ, לא את המערך: scores[0] = 95 מותר, אבל scores = new int[3] היה נעצר בקומפילציה.final int[] scores locks the arrow, not the array: scores[0] = 95 is allowed, but scores = new int[3] would be stopped at compile time.
  • cannot assign a value to final variable count:cannot assign a value to final variable count:
  • מדף, צעד 16: מונה ספרים וקבועי דירוגShelf, step 16: a book counter and rating constants

מפגשSession 17: equals, hashCode ו-toStringequals, hashCode & toString

  • equals: מתודה של Object שאומרת אם שני עצמים "שווים בתוכן".equals: An Object method saying whether two objects are "equal in content".
  • hashCode: מספר שמחושב מהתוכן של העצם.hashCode: A number computed from the object's content.
  • שני ספרים עם אותו תוכן הם שני עצמים.Two books with the same content are two objects.
  • בלי לדרוס את equals, גם היא בודקת "אותו עצם", בדיוק כמו ==.Without overriding equals, it also checks "the same object", exactly like ==.
  • equals משווה את השדות (עם instanceof עם משתנה), hashCode מחושב מאותם שדות, ו-toString נותן הדפסה קריאה.equals compares the fields (with a pattern instanceof), hashCode is computed from the same fields, and toString gives a readable print.
  • עכשיו HashSet רואה שני ספרים זהים כספר אחד.Now a HashSet sees two identical books as one.
  • ל-Tag יש equals אבל אין hashCode.Tag has equals but no hashCode.
  • לכל עצם יש hashCode אחר (לפי העצם, לא לפי התוכן), ולכן HashSet מחפש במגירה הלא נכונה ושומר את "אותה" תגית פעמיים.Each object gets a different hashCode (by object, not by content), so HashSet looks in the wrong drawer and keeps the "same" tag twice.
  • מדף, צעד 17: ספרים כפולים לא נכנסיםShelf, step 17: duplicates stay off

מפגשSession 18: פרויקט קטן: המדף כמערכת מחלקותMini project: the shelf as classes

  • אחריות אחת: לכל מחלקה תפקיד אחד ברור:single responsibility: Each class has one clear job:
  • הרכבה (has-a): עצם שמחזיק עצמים אחרים בשדות:composition (has-a): An object holding other objects in its fields:
  • הרכבה: שני ספרים מצביעים על אותו עצם Author.Composition: two books point to the same Author object.
  • בזיכרון רואים את הרשימה, שני ספרים, וחץ משותף לסופר.In memory you see the list, two books, and a shared arrow to the author.
  • Author ו-Book הם עצמים קטנים ובלתי משתנים.Author and Book are small immutable objects.
  • Shelf מחזיקה רשימה פרטית ומציעה ממשק: add (שמסרבת לכפולים) ו-report.Shelf holds a private list and offers an interface: add (which refuses duplicates) and report.
  • מדף, צעד 18: Shelf, Book ו-Author עובדים יחדShelf, step 18: Shelf, Book and Author working together

חלקPart 4: OOP מתקדםAdvanced OOP

מפגשSession 19: ירושה, super ו-overrideInheritance, super & override

  • ירושה: class EBook extends Book:inheritance: class EBook extends Book:
  • מחלקת על (הורה): המחלקה שממנה יורשים.superclass (parent): The class you inherit from.
  • EBook יורשת מ-Book: יש לה getTitle בלי לכתוב אותה.EBook inherits from Book: it has getTitle without writing it.
  • הבנאי שלה קורא קודם ל-super(title).Its constructor first calls super(title).
  • אם בנאי לא קורא ל-super(...), Java מוסיפה super() ריק.If a constructor doesn't call super(...), Java adds an empty super().
  • ל-Book אין בנאי ריק, ולכן javac עוצר.Book has no empty constructor, so javac stops.
  • Stack extends ArrayList נראה חסכוני, אבל עכשיו כל מי שמחזיק Stack יכול לקרוא ל-add(0, 99) ולשבור את הכלל "האחרון שנכנס יוצא ראשון".Stack extends ArrayList looks economical, but now anyone holding a Stack can call add(0, 99) and break the rule "last in, first out".
  • מחסנית היא לא סוג של רשימה, היא משתמשת ברשימה.A stack isn't a kind of list, it uses a list.
  • constructor Book in class Book cannot be applied to given types;:constructor Book in class Book cannot be applied to given types;:

מפגשSession 20: abstract ו-interfacesabstract & interfaces

  • מחלקה מופשטת: abstract class Shape:abstract class: abstract class Shape:
  • מתודה מופשטת: abstract double area();:abstract method: abstract double area();:
  • ל-Shape אין דרך לחשב שטח, ולכן area מופשטת.Shape has no way to compute an area, so area is abstract.
  • describe כתובה פעם אחת בהורה, ובזמן ריצה קוראת ל-area של העצם האמיתי (עיגול או ריבוע).describe is written once in the parent, and at run time it calls the real object's area (circle or square).
  • new Shape() לא מתקמפל: מה היה השטח שלו?new Shape() doesn't compile: what would its area be?
  • Duck מממשת שני interfaces.Duck implements two interfaces.
  • מ-Flyer היא מקבלת את describe (מתודת default) בחינם.From Flyer it gets describe (a default method) for free.
  • Circle is not abstract and does not override abstract method area() in Shape:Circle is not abstract and does not override abstract method area() in Shape:
  • מדף, צעד 20: interface בשם LendableShelf, step 20: a Lendable interface

מפגשSession 21: פולימורפיזם ו-dynamic dispatchPolymorphism & dynamic dispatch

  • פולימורפיזם: "הרבה צורות":polymorphism: "Many forms":
  • טיפוס סטטי: הטיפוס של המשתנה, כפי שכתוב בקוד (Item b).static type: The variable's type as written in the code (Item b).
  • שלושת המשתנים הם מסוג Item, אבל כל אחד מצביע על עצם מסוג אחר.All three variables are of type Item, but each points to a different kind of object.
  • line() כתובה רק ב-Item, ובתוכה kind() ו-loanDays() נבחרות לפי העצם האמיתי (dynamic dispatch).line() is written only in Item, and inside it kind() and loanDays() are chosen by the real object (dynamic dispatch).
  • העצם הוא EBook, אבל המשתנה הוא Item, ול-Item אין getSizeMb.The object is an EBook, but the variable is an Item, and Item has no getSizeMb.
  • javac בודק לפי הטיפוס הסטטי ועוצר.javac checks by the static type and stops.
  • it instanceof EBook e בודק את הסוג ונותן משתנה e מסוג EBook, כך שמותר לקרוא ל-getSizeMb.it instanceof EBook e checks the type and gives a variable e of type EBook, so you may call getSizeMb.
  • בלי הבדיקה, המרה של Dvd הייתה זורקת ClassCastException.Without the check, a downcast of a Dvd would throw a ClassCastException.
  • שני המשתנים מצביעים על אותה מחרוזת, אבל what(o) בוחרת את what(Object): גרסה של overloading נבחרת בזמן קומפילציה, לפי הטיפוס הסטטי.Both variables point to the same string, but what(o) picks what(Object): an overload is chosen at compile time, by the static type.

מפגשSession 22: GenericsGenerics

  • מחלקה גנרית: מחלקה עם פרמטר טיפוס:generic class: A class with a type parameter:
  • פרמטר טיפוס: השם בסוגריים המשולשים (T, A, B, K, V).type parameter: The name in angle brackets (T, A, B, K, V).
  • T הוא פרמטר טיפוס.T is a type parameter.
  • Box<String> מחזירה String בלי המרה, ו-Box<Integer> מחזירה Integer (וה-autoboxing הופך אותו ל-int).Box<String> returns a String with no cast, and Box<Integer> returns an Integer (autoboxing turns it into an int).
  • בלי generics, מספר היה נכנס לרשימת מחרוזות ומפיל את התוכנית מאוחר יותר.Without generics, a number would get into a list of strings and crash the program later.
  • עם List<String>, javac עוצר מיד, בשורה שבה הטעות.With List<String>, javac stops right away, on the line with the mistake.
  • last עובדת לכל רשימה.last works for any list.
  • ב-max, הגבול T extends Comparable<T> מבטיח שיש compareTo, ולכן אותה מתודה עובדת גם למספרים וגם למחרוזות.In max, the bound T extends Comparable<T> guarantees there's a compareTo, so the same method works for numbers and strings alike.
  • sum רק קוראת מספרים, ולכן `?sum only reads numbers, so `?

מפגשSession 23: records, enums, sealed ו-pattern matchingrecords, enums, sealed & pattern matching

  • record: record Book(String title, int year) {}:record: record Book(String title, int year) {}:
  • בנאי מקוצר: Book { if (year < 0) throw ...; } בתוך record:compact constructor: Book { if (year < 0) throw ...; } inside a record:
  • record Book נותן toString, getters (title(), בלי get), ו-equals/hashCode לפי כל השדות, ולכן ה-Set רואה ספר אחד.record Book gives a toString, getters (title(), no get), and equals/hashCode by every field, so the Set sees one book.
  • הבנאי המקוצר בודק את השנה.The compact constructor checks the year.
  • כל ערך של Genre נוצר פעם אחת עם הנתונים שלו.Each Genre value is created once with its data.
  • values() מחזירה את כולם לפי הסדר, ו-valueOf הופך טקסט לערך.values() returns them all in order, and valueOf turns text into a value.
  • Shape סגור: יש רק Circle ו-Rect.Shape is sealed: there's only Circle and Rect.
  • ה-switch מפרק כל record (פירוק record), ו-when מוסיף תנאי (ריבוע).The switch takes each record apart (record pattern), and when adds a condition (a square).
  • הוספנו Triangle לרשימת ה-permits, ושכחנו לעדכן את ה-switch.We added Triangle to the permits list and forgot to update the switch.

מפגשSession 24: SOLID ותבניות עיצובSOLID & design patterns

  • SOLID: חמישה עקרונות:SOLID: Five principles:
  • Strategy: משפחת אלגוריתמים מאחורי interface אחד (Comparator, Discount).Strategy: A family of algorithms behind one interface (Comparator, Discount).
  • books.sort(...) לא יודע איך משווים.books.sort(...) doesn't know how to compare.
  • כל אסטרטגיה היא מחלקה קטנה שמממשת Comparator, ומחליפים אותן בלי לגעת ברשימה.Each strategy is a small class implementing Comparator, and you swap them without touching the list.
  • הבנאי של Book הוא private.Book's constructor is private.
  • בונים דרך Book.Builder (מחלקה מקוננת static): כל מתודה מחזירה את ה-Builder עצמו, ולכן אפשר לשרשר.You build through Book.Builder (a static nested class): each method returns the Builder itself, so calls chain.
  • Shelf לא יודע מי מאזין ומה הוא עושה.Shelf doesn't know who listens or what they do.
  • הוא רק עובר על הרשימה וקורא ל-bookAdded.It just goes over the list calling bookAdded.
  • מדף, צעד 24: Strategy ו-BuilderShelf, step 24: Strategy and Builder

חלקPart 5: Java מודרנית וכליםModern Java & tools

מפגשSession 25: Collections לעומקCollections in depth

  • סיבוכיות (O גדול): כמה העבודה גדלה כשהאוסף גדל.complexity (big O): How the work grows as the collection grows.
  • LinkedHashSet: Set ששומר את סדר ההכנסה.LinkedHashSet: A Set that keeps insertion order.
  • שני ה-Sets מוחקים כפולים (fig מופיע פעם אחת).Both Sets drop duplicates (fig appears once).
  • LinkedHashSet שומר את סדר ההכנסה, ו-TreeSet ממיין.LinkedHashSet keeps insertion order, and TreeSet sorts.
  • TreeMap מחזיק את השנים ממוינות.A TreeMap keeps the years sorted.
  • headMap(1950) נותן את כל מה שלפני 1950, ו-ceilingKey(1900) את המפתח הראשון שגדול או שווה ל-1900.headMap(1950) gives everything before 1950, and ceilingKey(1900) the first key at or above 1900.
  • אותו ArrayDeque משמש כתור (offer/poll) וכמחסנית (push/pop).The same ArrayDeque serves as a queue (offer/poll) and a stack (push/pop).
  • PriorityQueue מוציא תמיד את הקטן ביותר.A PriorityQueue always takes out the smallest.
  • java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:

מפגשSession 26: Lambdas ו-functional interfacesLambdas & functional interfaces

  • למבדה: פונקציה קצרה בלי שם:lambda: A short nameless function:
  • functional interface: interface עם מתודה מופשטת אחת בדיוק (כמו Comparator, Runnable, Predicate).functional interface: An interface with exactly one abstract method (like Comparator, Runnable, Predicate).
  • במפגש 24 כתבנו מחלקה שלמה בשביל Comparator.In session 24 we wrote a whole class for a Comparator.
  • למבדה אומרת אותו דבר בשורה: (a, b) -> a.length() - b.length().A lambda says the same in one line: (a, b) -> a.length() - b.length().
  • Predicate בודק, Function ממיר, Consumer עושה משהו, ו-Supplier מייצר.A Predicate tests, a Function converts, a Consumer does something, and a Supplier produces.
  • אפשר להרכיב: negate(), andThen(...).They compose: negate(), andThen(...).
  • total משתנה בתוך הלמבדה, ולכן הוא לא effectively final.total changes inside the lambda, so it isn't effectively final.
  • javac עוצר.javac stops.
  • local variables referenced from a lambda expression must be final or effectively final:local variables referenced from a lambda expression must be final or effectively final:

מפגשSession 27: Streams ו-OptionalStreams & Optional

  • Stream: "פס ייצור" על אוסף:Stream: A "production line" over a collection:
  • פעולת ביניים: פעולה שמחזירה Stream חדש:intermediate operation: An operation returning a new Stream:
  • ה-Stream עובר ספר-ספר: filter משאיר רק מה שאחרי 1900, map הופך ספר לכותר, sorted ממיין, ו-toList אוסף.The Stream goes book by book: filter keeps what's after 1900, map turns a book into its title, sorted sorts, and toList collects.
  • הרשימה המקורית לא משתנה.The original list doesn't change.
  • mapToInt נותן IntStream עם sum, average, min.mapToInt gives an IntStream with sum, average, min.
  • average מחזיר OptionalDouble (אולי אין ספרים), ולכן orElse(0).average returns an OptionalDouble (maybe there are no books), hence orElse(0).
  • groupingBy(Book::author, TreeMap::new, counting()) בונה מפה ממוינת מסופר לכמות.groupingBy(Book::author, TreeMap::new, counting()) builds a sorted map from author to count.
  • joining מחבר מחרוזות עם מפריד, תחילית וסיומת.joining glues strings with a separator, prefix and suffix.
  • findFirst מחזיר Optional: אולי מצאנו, אולי לא.findFirst returns an Optional: maybe found, maybe not.

מפגשSession 28: חריגות checked מול unchecked ו-try-with-resourcesChecked vs unchecked exceptions & try-with-resources

  • חריגה checked: חריגה שיורשת מ-Exception (ולא מ-RuntimeException), כמו IOException.checked exception: An exception extending Exception (not RuntimeException), like IOException.
  • חריגה unchecked: חריגה שיורשת מ-RuntimeException (IllegalArgumentException, NullPointerException).unchecked exception: An exception extending RuntimeException (IllegalArgumentException, NullPointerException).
  • load מכריזה throws IOException.load declares throws IOException.
  • main קורא לה בלי try ובלי throws, ו-javac לא מקמפל.main calls it with no try and no throws, and javac won't compile.
  • InvalidYearException היא checked.InvalidYearException is checked.
  • parseYear הופכת את ה-NumberFormatException הטכני להודעה שמבינים, ושומרת אותו כ-cause.parseYear turns the technical NumberFormatException into a message people understand, and keeps it as the cause.
  • שני משאבים נפתחים, הגוף זורק חריגה, ובכל זאת שניהם נסגרים, בסדר הפוך, ורק אחר כך ה-catch רץ.Two resources open, the body throws, and still both close, in reverse order, and only then does the catch run.
  • unreported exception IOException; must be caught or declared to be thrown:unreported exception IOException; must be caught or declared to be thrown:
  • מדף, צעד 28: BookNotFoundExceptionShelf, step 28: BookNotFoundException

מפגשSession 29: קבצים עם NIO ו-JSONFiles with NIO & JSON

  • Path: כתובת של קובץ או תיקייה:Path: The address of a file or folder:
  • Files: מחלקת עזר עם כל הפעולות:Files: A utility class with all the operations:
  • Files עושה את כל העבודה: writeString יוצר את הקובץ, readAllLines מחזיר רשימת שורות.Files does all the work: writeString creates the file, readAllLines returns a list of lines.
  • main מכריז throws IOException, כי פעולות על קבצים יכולות להיכשל.main declares throws IOException, because file operations can fail.
  • StandardOpenOption.APPEND מוסיף לסוף במקום לדרוס.StandardOpenOption.APPEND adds to the end instead of overwriting.
  • Files.lines מחזיר Stream של שורות שמחזיק את הקובץ פתוח, ולכן הוא ב-try-with-resources.Files.lines returns a Stream of lines that keeps the file open, so it goes in a try-with-resources.
  • JSON הוא רק טקסט עם כללים: מחרוזות במירכאות, ומירכאות בתוך מחרוזת צריך לסמן ב-\".JSON is just text with rules: strings in quotes, and quotes inside a string must be escaped as \".
  • כאן כותבים אותו ביד כדי להבין את המבנה.Here we write it by hand to understand the shape.
  • קוראים קובץ שאף אחד לא יצר, ומקבלים NoSuchFileException.Reading a file nobody created gives a NoSuchFileException.

מפגשSession 30: JUnit 5, Maven, Gradle ו-GitJUnit 5, Maven, Gradle & Git

  • בדיקת יחידה: קוד קטן שבודק יחידה אחת (מתודה, מחלקה) במצב אחד:unit test: Small code checking one unit (a method, a class) in one situation:
  • JUnit 5: ספריית הבדיקות הנפוצה ב-Java.JUnit 5: Java's common testing library.
  • לפני JUnit, הרעיון עצמו ב-Java רגילה: כל בדיקה מפעילה את הקוד ומשווה לתוצאה צפויה.Before JUnit, the idea itself in plain Java: each test runs the code and compares with an expected result.
  • בדיקה טובה בודקת גם מקרי קצה (שלילי, אפס).A good test checks edge cases too (negative, zero).
  • ב-JUnit כל בדיקה היא מתודה עם @Test, ו-@BeforeEach בונה מדף חדש לפני כל אחת, כך שהבדיקות לא תלויות זו בזו.In JUnit each test is a method with @Test, and @BeforeEach builds a fresh shelf before each one, so the tests don't depend on each other.
  • assertThrows בודק שנזרקה חריגה.assertThrows checks an exception was thrown.
  • מדף, צעד 30: בדיקות למדףShelf, step 30: tests for the shelf

חלקPart 6: Concurrency ו-ThreadsConcurrency & threads

מפגשSession 31: Thread ו-Runnable, start מול run, ו-joinThread & Runnable, start vs run, and join

  • thread: "קו ביצוע" בתוך תוכנית.thread: A "line of execution" inside a program.
  • Runnable: functional interface עם void run():Runnable: A functional interface with void run():
  • start() מפעיל כל thread, ו-join() מחכה לו.start() launches each thread, and join() waits for it.
  • השורה main is done תמיד אחרונה, אבל A ו-B יכולים להתחלף.main is done is always last, but A and B can swap.
  • t.run() רץ ב-main עצמו, כמו כל קריאה למתודה.t.run() runs on main itself, like any method call.
  • רק t.start() יוצר thread חדש בשם worker.Only t.start() creates a new thread named worker.
  • מדף, צעד 31: טעינת שני קבצים במקבילShelf, step 31: loading two files at once

מפגשSession 32: Race conditions, synchronized ומוניטוריםRace conditions, synchronized & monitors

  • מרוץ (race condition): תוצאה שתלויה בסדר שבו threads רצים.race condition: A result that depends on the order threads run in.
  • קטע קריטי: קוד שניגש למשהו משותף, ושרק thread אחד צריך להריץ בכל רגע.critical section: Code touching something shared, that only one thread should run at a time.
  • שני threads מגדילים מונה 100,000 פעמים כל אחד.Two threads increment a counter 100,000 times each.
  • היינו מצפים ל-200,000.We'd expect 200,000.
  • עם synchronized, increment נעשית קטע קריטי: רק thread אחד בפנים.With synchronized, increment becomes a critical section: only one thread inside.
  • התוצאה תמיד 200,000.The result is always 200,000.
  • עותק אחד, שני אנשים.One copy, two people.
  • כל אחד בודק copies > 0 ואז מוריד.Each checks copies > 0 then decrements.
  • מדף, צעד 32: מונה השאלות בטוחShelf, step 32: a thread-safe loan counter

מפגשSession 33: volatile ו-Java Memory Modelvolatile & the Java Memory Model

  • נראות: כל מעבד עובד עם עותקים שמורים (cache), וה-JIT יכול להעביר קריאה אל מחוץ ללולאה.visibility: Each CPU works with cached copies, and the JIT can move a read out of a loop.
  • volatile: volatile boolean running:volatile: volatile boolean running:
  • ה-worker מסתובב כל עוד running.The worker spins while running.
  • בגלל ש-running הוא volatile, הוא רואה את ה-false של main ונעצר.Because running is volatile, it sees main's false and stops.
  • גם עם volatile, count++ הוא קריאה וכתיבה נפרדות, ולכן עדכונים עדיין הולכים לאיבוד.Even with volatile, count++ is a separate read and write, so updates still get lost.
  • volatile נותן נראות, לא אטומיות.volatile gives visibility, not atomicity.
  • data לא volatile, אבל נכתב לפני הכתיבה ל-ready (שכן volatile).data isn't volatile, but it's written before the write to ready (which is volatile).
  • לפי happens-before, מי שרואה ready == true רואה גם data = 42.By happens-before, whoever sees ready == true also sees data = 42.
  • מדף, צעד 33: דגל עצירה לייבוא ארוךShelf, step 33: a stop flag for a long import

מפגשSession 34: wait/notify, producer/consumer ו-BlockingQueuewait/notify, producer/consumer & BlockingQueue

  • wait ו-notify: lock.wait() משחרר את המנעול ונרדם עד ש-lock.notifyAll() מעיר אותו (ואז הוא מחכה לקבל את המנעול שוב).wait and notify: lock.wait() releases the lock and sleeps until lock.notifyAll() wakes it (then it waits to get the lock back).
  • התעוררות שקרית: thread יכול להתעורר מ-wait בלי סיבה, או אחרי שמישהו אחר כבר לקח את מה שחיכה לו.spurious wakeup: A thread can wake from wait for no reason, or after someone else already took what it waited for.
  • הצרכן נועל, ובודק ב-while אם יש חבילה.The consumer locks, and checks in a while whether there's a parcel.
  • אין?None?
  • ArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק.An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty.
  • הסדר processed 1..5 מובטח, כי זה תור.The order processed 1..5 is guaranteed, because it's a queue.
  • מדף, צעד 34: תור ייבואShelf, step 34: an import queue

מפגשSession 35: ExecutorService, thread pools, Callable ו-FutureExecutorService, thread pools, Callable & Future

  • ExecutorService: שירות שמקבל משימות (submit) ומריץ אותן על threads שהוא מנהל.ExecutorService: A service that takes tasks (submit) and runs them on threads it manages.
  • בריכת threads: מספר קבוע של threads שלוקחים משימות מתור.thread pool: A fixed number of threads taking tasks from a queue.
  • ארבע משימות, רק שני threads (pool-1-thread-1, pool-1-thread-2).Four tasks, only two threads (pool-1-thread-1, pool-1-thread-2).
  • כל thread לוקח משימה, מסיים, ולוקח את הבאה.Each thread takes a task, finishes it, and takes the next.
  • כל משימה מחזירה את אורך הכותר.Each task returns the title's length.
  • f.get() מחכה לתוצאה.f.get() waits for the result.
  • invokeAll מחזיר את ה-Futures בסדר שבו נתתם את המשימות, לא בסדר שבו הן סיימו.invokeAll returns the Futures in the order you gave the tasks, not the order they finished.
  • `java.util.concurrent.ExecutionException:`java.util.concurrent.ExecutionException:
  • מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import

מפגשSession 36: Locks, Atomic ו-ConcurrentHashMapLocks, Atomic & ConcurrentHashMap

  • Atomic: AtomicInteger, AtomicLong ודומיהם:Atomic: AtomicInteger, AtomicLong and friends:
  • compareAndSet: x.compareAndSet(expected, next):compareAndSet: x.compareAndSet(expected, next):
  • בלי synchronized ובלי מנעול, ובכל זאת תמיד 200,000: incrementAndGet אטומי.No synchronized and no lock, and still always 200,000: incrementAndGet is Atomic.
  • lock() ואז try, ו-unlock() תמיד ב-finally: גם אם הקוד בפנים זורק, המנעול משתחרר.lock() then try, and unlock() always in finally: even if the code inside throws, the lock is released.
  • ארבעה threads סופרים מילים לאותה מפה.Four threads count words into the same map.
  • merge אטומי, ולכן הספירה תמיד נכונה: כל מילה פי 4.merge is atomic, so the count is always right: each word times 4.
  • מדף, צעד 36: מטמון בטוח לפרטי ספריםShelf, step 36: a thread-safe book cache

מפגשSession 37: CompletableFuture ו-virtual threadsCompletableFuture & virtual threads

  • CompletableFuture: Future שאפשר לשרשר:CompletableFuture: A Future you can chain:
  • virtual thread: thread קל מאוד (Java 21) שה-JVM מנהל.virtual thread: A very light thread (Java 21) managed by the JVM.
  • supplyAsync מריץ את fetchTitle ב-thread אחר.supplyAsync runs fetchTitle on another thread.
  • כל thenApply רץ כשהשלב הקודם מסתיים.Each thenApply runs when the previous stage finishes.
  • thenCombine מחכה לשתי משימות ומחבר את התוצאות.thenCombine waits for two tasks and combines the results.
  • כשמשימה נכשלת, exceptionally נותן ערך חלופי במקום לזרוק.When a task fails, exceptionally gives a fallback value instead of throwing.
  • כל משימה ישנה 10ms.Each task sleeps 10ms.
  • עם 10,000 threads רגילים המחשב היה נאבק; עם virtual threads זה לוקח רגע.With 10,000 regular threads the computer would struggle; with virtual threads it takes a moment.
  • `java.util.concurrent.CompletionException:`java.util.concurrent.CompletionException:

מפגשSession 38: Deadlock, livelock ו-starvationDeadlock, livelock & starvation

  • deadlock: שני threads (או יותר) שכל אחד מחזיק משהו שהשני צריך, ומחכה לו.deadlock: Two (or more) threads each holding something the other needs, and waiting for it.
  • סדר נעילה: אם כולם נועלים מנעולים באותו סדר (למשל לפי id), מעגל המתנה לא יכול להיווצר.lock ordering: If everyone takes locks in the same order (say by id), a waiting cycle can't form.
  • T1 נועל A ואז רוצה B; T2 נועל B ואז רוצה A.T1 locks A then wants B; T2 locks B then wants A.
  • בלי זמן קצוב זה deadlock (את הגרסה הזו רק מדמים, כי היא הייתה תוקעת את הבנייה).Without a timeout that's a deadlock (we only simulate that version, since it would hang the build).
  • שני ה-threads נועלים קודם A ואז B.Both threads lock A first and then B.
  • מעגל לא יכול להיווצר, ושניהם תמיד מצליחים.A cycle can't form, and both always succeed.
  • מדף, צעד 38: השאלה בין שני מדפיםShelf, step 38: lending between two shelves

חלקPart 7: Java בעולם האמיתיJava in the real world

מפגשSession 39: JDBC ו-HttpClientJDBC & HttpClient

  • JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
  • SQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (' OR '1'='1).SQL injection: When user input is glued into an SQL string, the input can change the query (' OR '1'='1).
  • חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
  • כל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through ? and setString/setInt, never by gluing strings.
  • כדי להריץ באמת, התוכנית מרימה שרת HTTP קטן על המחשב עצמו (HttpServer מה-JDK), ואז שולחת אליו בקשות עם HttpClient.To really run, the program starts a tiny HTTP server on the machine itself (HttpServer from the JDK), then sends it requests with HttpClient.
  • הפלט אמיתי מזמן הבנייה.The output is real, from build time.
  • main מדבר רק עם BookRepository.main talks only to BookRepository.
  • היום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.
  • מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

מפגשSession 40: Spring Boot REST עם בדיקותSpring Boot REST with tests

  • REST: סגנון API מעל HTTP:REST: An API style over HTTP:
  • Spring Boot: framework שמרים שרת אינטרנט ב-Java בכמה שורות.Spring Boot: A framework that starts a Java web server in a few lines.
  • שלוש נקודות קצה: כל הספרים, ספר לפי כותר (או 404), והוספה (201).Three endpoints: every book, a book by title (or 404), and adding (201).
  • Spring ממיר את ה-record ל-JSON לבד.Spring turns the record into JSON for you.
  • כדי לראות מה Spring עושה בשבילכם: Request נכנס ל-controller, שמחליט לפי שיטה וכתובת, קורא ל-service, שקורא ל-repository.To see what Spring does for you: a Request enters the controller, which decides by method and address, calls the service, which calls the repository.
  • התשובה היא סטטוס ו-JSON.The answer is a status and JSON.
  • מדף, צעד 40: API למדףShelf, step 40: an API for the shelf

מפגשSession 41: Java בעידן ה-AIJava in the AI era

  • מודל שפה: תוכנה שמקבלת טקסט (prompt) ומחזירה טקסט.language model: Software that takes text (a prompt) and returns text.
  • prompt: הטקסט ששולחים למודל:prompt: The text sent to the model:
  • בקשת POST עם מפתח מתוך משתנה סביבה, גוף JSON עם המודל וההודעות, ותשובה ב-JSON.A POST request with an API key from an environment variable, a JSON body with the model and the messages, and a JSON reply.
  • ה-text block (""") שומר על ה-JSON קריא.The text block (""") keeps the JSON readable.
  • Model הוא interface עם מתודה אחת.Model is an interface with one method.
  • RecordedModel עונה מתשובות מוקלטות, ולכן כל הקוד שסביבו רץ ונבדק כאן, באותה צורה שבה ירוץ מול מודל אמיתי.RecordedModel answers from recorded replies, so all the code around it runs and is checked here, just as it will run against a real model.
  • מדף, צעד 41: המלצה לפי מצב רוחShelf, step 41: a recommendation by mood

מפגשSession 42: אלגוריתמים, ראיון עבודה ופרויקט גמרAlgorithms, interviews & final project

  • חיפוש בינארי: חיפוש במערך ממוין:binary search: Searching a sorted array:
  • שני מצביעים: שני אינדקסים שזזים על המערך (מהקצוות פנימה, או אחד אחרי השני).two pointers: Two indexes moving over the array (from the ends inward, or one behind the other).
  • במערך ממוין בודקים את האמצע: אם קטן מהמבוקש זורקים את החצי השמאלי, ואם גדול את הימני.In a sorted array, check the middle: if it's smaller than the target throw away the left half, if bigger the right.
  • בסימולציה רואים את lo, hi ו-mid מתכנסים.In the simulation you see lo, hi and mid close in.
  • שאלת הראיון הנפוצה ביותר: אילו שני מספרים מסתכמים ל-16?The most common interview question: which two numbers add up to 16?
  • במקום לבדוק כל זוג (O(n²)), זוכרים מה כבר ראינו ובודקים אם "המשלים" קיים: O(n).Instead of checking every pair (O(n²)), remember what you've seen and check whether the "complement" exists: O(n).
  • כל איבר "נכנס" למקום שלו בחלק הממוין שמשמאלו, כמו קלפים ביד.Each item "slides" into place in the sorted part to its left, like cards in a hand.
  • O(n²) במקרה הרע, אבל מהיר על מערך כמעט ממוין.O(n²) at worst, but fast on an almost-sorted array.
  • מדף, צעד 42: מיזוג שני מדפים ממויניםShelf, step 42: merging two sorted shelves

חלקPart 8: משחקים ב-JavaGames in Java

מפגשSession 43: חלון ראשון: Swing, ציור ו-game loopFirst window: Swing, drawing & the game loop

  • JFrame ו-JPanel: JFrame הוא החלון; JPanel הוא משטח בתוכו.JFrame and JPanel: JFrame is the window; JPanel is a surface inside it.
  • Graphics2D: "מכחול" של Java:Graphics2D: Java's "brush":
  • Timer של Swing קורא כל 16ms (בערך 60 פעמים בשנייה) ל-update ול-repaint.A Swing Timer calls update and repaint every 16ms (about 60 times a second).
  • Swing קורא ל-paintComponent, שמצייר את הכדור במקום החדש.Swing calls paintComponent, which draws the ball in its new place.
  • Graphics2D מצייר גם על BufferedImage.Graphics2D draws on a BufferedImage too.
  • התוכנית רצה באמת בזמן בניית האתר (headless), ושמרה את התמונה שאתם רואים מתחת לפלט.The program really ran while building the site (headless), and saved the picture you see below the output.
  • בלי חלון ובלי ציור: רק Ball.update.No window and no drawing: just Ball.update.
  • כך רואים בסימולציה בדיוק מה קורה בכל טיק: x עולה, עובר את הקיר, ו-vx מתהפך.That way the simulation shows exactly what happens on each tick: x grows, passes the wall, and vx flips.
  • משחק 1: כדורים קופציםGame 1: bouncing balls

מפגשSession 44: קלט מקלדת ועכברKeyboard & mouse input

  • KeyListener: מקבל אירועים:KeyListener: Receives events:
  • מצב מקשים: במקום להזיז בתוך keyPressed (שחוזר בקפיצות), שומרים אילו מקשים לחוצים, ובכל טיק זזים לפיהם.key state: Instead of moving inside keyPressed (which repeats in jumps), keep which keys are down, and move by them on every tick.
  • keyPressed ו-keyReleased רק מעדכנים את קבוצת המקשים הלחוצים.keyPressed and keyReleased only update the set of keys that are down.
  • ה-Timer מחשב dt ומזיז לפי המקשים.The Timer computes dt and moves by the keys.
  • הלוגיקה לבד: Input הוא מצב המקשים, ו-Ship.update(in, dt) זזה לפיו.The logic alone: Input is the key state, and Ship.update(in, dt) moves by it.
  • שלושה טיקים ימינה של חצי שנייה במהירות 120 הם 180 פיקסלים.Three half-second ticks to the right at speed 120 are 180 pixels.
  • שנייה אחת ב-30 פריימים או ב-144: עם speed * dt מגיעים לאותו מקום.One second at 30 frames or at 144: with speed * dt you end up in the same place.
  • משחק 2: חללית שיורהGame 2: a ship that shoots

מפגשSession 45: התנגשויות ו-spritesCollisions & sprites

  • AABB: התנגשות בין שני מלבנים ישרים:AABB: A collision between two upright rectangles:
  • sprite: תמונה קטנה של דמות או עצם במשחק.sprite: A small picture of a character or object in a game.
  • Rectangle.intersects בודק חפיפה.Rectangle.intersects checks for overlap.
  • הכוכב שנוגע במשוט מצויר באדום.The star touching the paddle is drawn in red.
  • שני מלבנים חופפים אם כל אחד מתחיל לפני שהשני נגמר, בשני הצירים.Two rectangles overlap if each starts before the other ends, on both axes.
  • בסימולציה רואים את ארבע ההשוואות.In the simulation you see the four comparisons.
  • 4 פריימים, כל אחד 0.1 שנייה.4 frames, each 0.1 seconds.
  • הזמן קובע את הפריים, לא מספר הסיבובים של הלולאה, כך שהאנימציה באותה מהירות בכל מחשב.The time decides the frame, not the number of loop rounds, so the animation runs at the same speed on every computer.
  • משחק 3: לתפוס כוכביםGame 3: catch the stars

מפגשSession 46: מצבי משחק: תפריט, משחק ו-Game OverGame states: menu, play & game over

  • מכונת מצבים: המשחק תמיד נמצא במצב אחד מתוך רשימה סגורה (enum State).state machine: The game is always in one state from a closed list (enum State).
  • מעבר: שינוי ממצב למצב בעקבות אירוע:transition: A change from state to state after an event:
  • Game.on(key) מחליט לפי state: בתפריט ENTER מתחיל, במשחק HIT מוריד חיים, וב-Game Over ENTER חוזר לתפריט.Game.on(key) decides by state: in the menu ENTER starts, in play HIT takes a life, and in game over ENTER returns to the menu.
  • מקש שלא מתאים למצב פשוט לא עושה כלום (ESC כאן).A key that doesn't fit the state just does nothing (ESC here).
  • switch שמחזיר ערך על enum חייב לכסות כל מצב.A value-returning switch on an enum must cover every state.
  • אם תוסיפו PAUSED ל-enum, javac יראה לכם כל מקום שצריך לעדכן.If you add PAUSED to the enum, javac shows you every place to update.
  • the switch expression does not cover all possible input values:the switch expression does not cover all possible input values:
  • משחק 4: משחק עם תפריט ושיאGame 4: a game with a menu and a high score

מפגשSession 47: Thread ללוגיקה ול-render, עם סנכרוןA thread for logic and rendering, with sync

  • תמונת מצב: עותק בלתי משתנה של העולם (record עם List.copyOf).snapshot: An immutable copy of the world (a record with List.copyOf).
  • צעד זמן קבוע: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק.fixed timestep: Accumulate frame time, and run an update of, say, 20ms each time enough has built up.
  • ה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile.The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable.
  • ה-render קורא את ההפניה פעם אחת ומצייר ממנה, ולכן אף פעם לא רואה עולם חצי מעודכן.The renderer reads the reference once and draws from it, so it never sees a half-updated world.
  • scheduleAtFixedRate מריץ טיק כל 10ms על thread אחד.scheduleAtFixedRate runs a tick every 10ms on one thread.
  • ב-Swing, javax.swing.Timer עושה אותו דבר על ה-EDT, ואז אין שני threads ואין מה לסנכרן.In Swing, javax.swing.Timer does the same on the EDT, so there aren't two threads and nothing to synchronize.
  • java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:
  • משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies

מפגשSession 48: משחק שלם ואריזה ל-jar ו-jpackageA full game, packed with jar & jpackage

  • seed: new Random(42) מייצר תמיד את אותה סדרה "אקראית".seed: new Random(42) always produces the same "random" sequence.
  • jar: קובץ zip עם המחלקות המהודרות וקבצי המשאבים (תמונות, צלילים).jar: A zip file with the compiled classes and resource files (images, sounds).
  • כל מה שבנינו: State, Input, משוט שזז עם dt ונשאר במסך, כוכבים שנופלים, התנגשות, ניקוד וחיים.Everything we built: State, Input, a paddle moving with dt and staying on screen, falling stars, collisions, score and lives.
  • עם seed קבוע (42) ו"שחקן" אוטומטי שזז הלוך ושוב, התוצאה זהה בכל הרצה, ולכן אפשר לבדוק אותה.With a fixed seed (42) and an automatic "player" moving back and forth, the result is the same every run, so it can be tested.
  • Properties קורא קובץ key=value ומדלג על הערות.Properties reads a key=value file and skips comments.
  • getProperty(key, default) נותן ברירת מחדל כשהמפתח חסר, כך שהמשחק עובד גם בלי קובץ.getProperty(key, default) gives a default when the key is missing, so the game works even without a file.
  • גרסאות נכתבות major.minor.patch ומשווים אותן כמספרים, לא כטקסט: 1.10.0 חדשה מ-1.2.0.Versions are written major.minor.patch and compared as numbers, not text: 1.10.0 is newer than 1.2.0.
  • את הגרסה שמים ב-manifest כ-Implementation-Version.The version goes in the manifest as Implementation-Version.
  • משחק 6: המשחק השלםGame 6: the full game

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