String ו-StringBuilderString & StringBuilder
מחרוזות הן עצמים שלא משתנים, מתודות שימושיות, השוואה עם equals, String.format ו-StringBuilder לבנייה יעילה.
Strings are immutable objects, useful methods, comparing with equals, String.format, and StringBuilder for efficient building.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- לא משתנה (immutable): עצם שאי אפשר לשנות אחרי שנוצר. String כזה:
toUpperCase()לא משנה את המחרוזת, אלא מחזירה חדשה.immutable: An object that can't change once created. A String is like that:toUpperCase()doesn't change the string, it returns a new one. - מאגר המחרוזות (String pool): אזור שבו Java שומרת מחרוזות שנכתבו בקוד (ליטרלים). שני ליטרלים זהים מצביעים לאותו עצם.
new String(...)יוצר עצם חדש מחוץ למאגר.string pool: An area where Java keeps strings written in the code (literals). Two equal literals point to the same object.new String(...)makes a new object outside the pool. - אינדקס: המספר של מקום במחרוזת (או במערך). מתחילים מ-0: ב-
"java"התו באינדקס 0 הואj.index: The number of a position in a string (or an array). It starts at 0: in"java"the character at index 0 isj. - תו בריחה: לוכסן הפוך ואחריו תו, שיחד הם תו מיוחד:
\nשורה חדשה,\tטאב,\"מירכאות,\\לוכסן.escape sequence: A backslash plus a character that together mean a special character:\nnew line,\ttab,\"a quote,\\a backslash. - תבנית עיצוב: החלקים שמתחילים ב-
%ב-printfוב-String.format:%sטקסט,%dשלם,%.2fעשרוני,%5dרוחב 5,%-10sצמוד לשמאל.format specifier: The%parts inprintfandString.format:%stext,%dwhole number,%.2fdecimal,%5dwidth 5,%-10sleft-aligned. - StringBuilder: "מחרוזת שמשתנה": מוסיפים לה עם
appendבלי ליצור עצם חדש כל פעם, ובסוףtoString().StringBuilder: A "string you can change": add to it withappendwithout making a new object each time, thentoString()at the end. - הפניה: מה שיושב בקופסה של משתנה מסוג עצם: לא העצם עצמו, אלא "כתובת" שמצביעה עליו ב-heap.reference: What sits in the box of an object-type variable: not the object itself, but an "address" pointing to it on the heap.
02מתודות של StringString methods
String הוא עצם, ויש לו מתודות. האינדקס מתחיל מ-0. substring(a, b) לוקח מ-a ועד לפני b.
A String is an object with methods. The index starts at 0. substring(a, b) takes from a up to before b.
public class Main {
public static void main(String[] args) {
String s = "Java Course";
System.out.println(s.length());
System.out.println(s.charAt(0));
System.out.println(s.indexOf("C"));
System.out.println(s.substring(0, 4));
System.out.println(s.toUpperCase());
System.out.println(s.replace("Course", "Rocks"));
System.out.println(s.contains("va"));
}
}11 J 5 Java JAVA COURSE Java Rocks true
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03String לא משתנהA String never changes
המתודות מחזירות מחרוזת חדשה, והמקורית נשארת כמו שהיא. רוצים לשמור את השינוי? שמים את התוצאה בחזרה במשתנה.
The methods return a new string, and the original stays as it is. Want to keep the change? Put the result back in the variable.
public class Main {
public static void main(String[] args) {
String name = "noa";
name.toUpperCase();
System.out.println(name);
name = name.toUpperCase();
System.out.println(name);
}
}noa NOA
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04== מול equals, ומאגר המחרוזות== vs equals, and the string pool
== בודק אם שתי הפניות מצביעות לאותו עצם. equals בודק אם התוכן זהה. שני ליטרלים זהים חולקים עצם אחד במאגר, אבל new String יוצר עצם חדש. בזיכרון למטה רואים את זה: החצים של a ו-b מגיעים לאותו עצם.
== checks whether two references point to the same object. equals checks whether the contents match. Two equal literals share one object in the pool, but new String makes a new object. The memory view below shows it: the arrows from a and b reach the same object.
public class Main {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c));
}
}true false true
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
05עיצוב עם printf ו-String.formatFormatting with printf and String.format
בתבנית כל % מתמלא בערך הבא. מספר אחרי ה-% הוא רוחב, ומינוס צמוד לשמאל. String.format מחזיר את הטקסט במקום להדפיס.
In a template every % is filled by the next value. A number after % is a width, and a minus aligns left. String.format returns the text instead of printing it.
public class Main {
public static void main(String[] args) {
System.out.printf("%-8s|%6.2f|%n", "Coffee", 12.5);
System.out.printf("%-8s|%6.2f|%n", "Cake", 18.9);
String line = String.format("%s has %d books", "Noa", 7);
System.out.println(line);
}
}Coffee | 12.50| Cake | 18.90| Noa has 7 books
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06StringBuilder ותווי בריחהStringBuilder and escape sequences
StringBuilder הוא מחרוזת שאפשר לשנות: append מוסיף, reverse הופך, ו-toString מחזיר String. תווי בריחה: \n שורה חדשה, \t טאב, \" מירכאות.
A StringBuilder is a string you can change: append adds, reverse flips, and toString gives back a String. Escapes: \n new line, \t tab, \" a quote.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Ja");
sb.append("va");
sb.append(21);
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println("She said \"hi\"\tthen left");
}
}Java21 12avaJ She said "hi" then left
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07הצעד של היום בפרויקט מדףToday's step in the Shelf project
שמרו ספר במשתנים (title, author, year, stars מסוג int בין 1 ל-5). בנו עם String.format שורה בפורמט <title> | <author> | <year>, והדפיסו אותה ואחריה שורת כוכבים: * כפול stars (רמז: "*".repeat(stars)).
Keep a book in variables (title, author, year, stars as an int 1–5). Build with String.format a line like <title> | <author> | <year>, print it, and then a line of stars: * times stars (hint: "*".repeat(stars)).
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.