דפי עזרCheatsheets
כל דוגמת Java כאן היא הגוף של main: היא קומפלה ורצה עם JDK 21 בזמן בניית האתר, והפלט שלה אמיתי. לכל דף יש עוגן לקישור ישיר. דפים נוספים נפתחים יחד עם המפגשים שלהם.
Every Java example here is the body of main: it was compiled and run with JDK 21 while the site was built, and its output is real. Each sheet has an anchor for a direct link. More sheets open along with their sessions.
יסודות JavaJava basics
מפגשSession 1התוכנית הכי קטנהThe smallest program
System.out.println("Hello, Java!");פלטOutput
Hello, Java!
println, print ו-printfprintln, print and printf
System.out.print("no new line, ");
System.out.println("then a new line");
System.out.printf("%s is %d years old%n", "Noa", 15);פלטOutput
no new line, then a new line Noa is 15 years old
חשבוןArithmetic
System.out.println(7 + 3 * 2);
System.out.println(7 / 2); // int / int = int
System.out.println(7 / 2.0); // a double joins in
System.out.println(7 % 2); // the remainderפלטOutput
13 3 3.5 1
טקסט ומספרים יחדText and numbers together
System.out.println("1 + 1 = " + 1 + 1);
System.out.println("1 + 1 = " + (1 + 1));פלטOutput
1 + 1 = 11 1 + 1 = 2
הערותComments
// a comment until the end of the line
/* a comment
over several lines */
System.out.println("comments are skipped");פלטOutput
comments are skipped
קומפילציה והרצהCompile and run
javac Main.java
java Main
java Main.java
jshellמחרוזות ו-StringBuilderStrings and StringBuilder
מפגשSession 3אורך, אות ותת-מחרוזתLength, a char and a substring
String s = "Java 21";
System.out.println(s.length());
System.out.println(s.charAt(0));
System.out.println(s.substring(5));
System.out.println(s.indexOf("21"));פלטOutput
7 J 21 5
השוואה: equals, לא ==Comparing: equals, not ==
String a = "hi";
String b = new String("hi");
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println("HI".equalsIgnoreCase(a));פלטOutput
false true true
ניקוי ופיצולCleaning and splitting
String line = " noa,avi , dana ";
for (String name : line.trim().split("\\s*,\\s*")) {
System.out.println("[" + name + "]");
}פלטOutput
[noa] [avi] [dana]
StringBuilder בלולאהStringBuilder in a loop
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(i < 5 ? "-" : "");
}
System.out.println(sb);
System.out.println(sb.reverse());פלטOutput
1-2-3-4-5 5-4-3-2-1
עיצובFormatting
System.out.println(String.format("%-6s|%5.2f|%03d", "tea", 3.5, 7));
System.out.println("total: %d".formatted(42));
System.out.println(String.join(" / ", "a", "b", "c"));פלטOutput
tea | 3.50|007 total: 42 a / b / c
text blockA text block
String json = """
{"name": "Noa", "age": 15}
""";
System.out.print(json);פלטOutput
{"name": "Noa", "age": 15}תנאים, switch ולולאותConditions, switch and loops
מפגשSession 5if / else if / elseif / else if / else
int t = 28;
if (t > 30) {
System.out.println("hot");
} else if (t > 20) {
System.out.println("nice");
} else {
System.out.println("cold");
}פלטOutput
nice
switch החדש מחזיר ערךThe new switch returns a value
String day = "SAT";
String kind = switch (day) {
case "FRI", "SAT" -> "weekend";
default -> "weekday";
};
System.out.println(kind);פלטOutput
weekend
for, while ו-do-whilefor, while and do-while
for (int i = 0; i < 3; i++) {
System.out.print(i + " ");
}
int n = 8;
while (n > 1) {
n /= 2;
}
System.out.println("| n=" + n);פלטOutput
0 1 2 | n=1
break ו-continuebreak and continue
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
if (i > 7) {
break;
}
System.out.print(i + " ");
}פלטOutput
1 3 5 7
אופרטור טרנרי ו-&&The ternary operator and &&
int age = 16;
boolean student = true;
System.out.println(age < 18 && student ? "half price" : "full price");פלטOutput
half price
מתודות ומערכיםMethods and arrays
מפגשSession 8מערך: יצירה, אורך ומעברAn array: creating, length and walking
int[] scores = {90, 75, 88};
int sum = 0;
for (int s : scores) {
sum += s;
}
System.out.println(scores.length + " scores, sum " + sum);פלטOutput
3 scores, sum 253
Arrays: הדפסה, מיון וחיפושArrays: print, sort and search
int[] a = {5, 2, 9, 1};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.binarySearch(a, 5));
System.out.println(Arrays.toString(Arrays.copyOf(a, 6)));פלטOutput
[1, 2, 5, 9] 2 [1, 2, 5, 9, 0, 0]
מערך דו-ממדיA 2D array
int[][] grid = new int[2][3];
grid[1][2] = 7;
System.out.println(Arrays.deepToString(grid));
System.out.println(grid.length + " rows, " + grid[0].length + " cols");פלטOutput
[[0, 0, 0], [0, 0, 7]] 2 rows, 3 cols
הפניה משותפתA shared reference
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
int[] c = a.clone();
c[1] = -1;
System.out.println(Arrays.toString(a));פלטOutput
[99, 2, 3]
מתודה: lambda במקום מתודה קטנהA method: a lambda for a tiny one
java.util.function.IntBinaryOperator max = (x, y) -> x > y ? x : y;
System.out.println(max.applyAsInt(3, 8));
System.out.println(Math.max(3, 8) + " " + Math.abs(-4) + " " + Math.pow(2, 10));פלטOutput
8 8 4 1024.0
מחלקות, records ו-enumsClasses, records and enums
מפגשSession 23record: מחלקת נתונים בשורהA record: a data class in one line
record Point(int x, int y) {
Point {
if (x < 0) throw new IllegalArgumentException("x < 0");
}
}
Point p = new Point(1, 2);
System.out.println(p + " " + p.x() + " " + p.equals(new Point(1, 2)));פלטOutput
Point[x=1, y=2] 1 true
enum עם שדותAn enum with fields
enum Size {
S(1), M(2), L(3);
final int cups;
Size(int cups) { this.cups = cups; }
}
for (Size s : Size.values()) {
System.out.print(s + "=" + s.cups + " ");
}פלטOutput
S=1 M=2 L=3
interface ו-lambdaAn interface and a lambda
interface Discount {
double apply(double price);
}
Discount half = p -> p / 2;
Discount none = p -> p;
System.out.println(half.apply(80) + " " + none.apply(80));פלטOutput
40.0 80.0
switch עם תבניות ו-whenA pattern switch with when
Object o = 3.5;
String d = switch (o) {
case Integer n -> "int " + n;
case Double x when x > 1 -> "big double " + x;
case String s -> "text " + s;
default -> "something else";
};
System.out.println(d);פלטOutput
big double 3.5
instanceof עם משתנהinstanceof with a variable
Object o = "hello";
if (o instanceof String str && str.length() > 3) {
System.out.println(str.toUpperCase());
}פלטOutput
HELLO
Collections ו-StreamsCollections and streams
מפגשSession 27ListList
List<String> names = new ArrayList<>(List.of("noa", "avi"));
names.add("dana");
names.remove("avi");
Collections.sort(names);
System.out.println(names + " " + names.size() + " " + names.contains("noa"));פלטOutput
[dana, noa] 2 true
Map: ספירה ומעברMap: counting and walking
Map<String, Integer> count = new TreeMap<>();
for (String w : "a b a c a".split(" ")) {
count.merge(w, 1, Integer::sum);
}
for (var e : count.entrySet()) {
System.out.print(e.getKey() + ":" + e.getValue() + " ");
}פלטOutput
a:3 b:1 c:1
Set ו-DequeSet and Deque
Set<Integer> seen = new LinkedHashSet<>(List.of(3, 1, 3, 2));
Deque<String> stack = new ArrayDeque<>();
stack.push("a");
stack.push("b");
System.out.println(seen + " " + stack.pop());פלטOutput
[3, 1, 2] b
filter, map, collectfilter, map, collect
List<Integer> nums = List.of(5, 12, 7, 20);
List<Integer> big = nums.stream().filter(n -> n > 6).map(n -> n * 10).toList();
System.out.println(big);
System.out.println(nums.stream().mapToInt(Integer::intValue).sum());פלטOutput
[120, 70, 200] 44
groupingBy ו-joininggroupingBy and joining
List<String> words = List.of("tea", "pie", "jam", "cake");
System.out.println(words.stream().collect(Collectors.groupingBy(String::length)));
System.out.println(words.stream().sorted().collect(Collectors.joining(", ")));פלטOutput
{3=[tea, pie, jam], 4=[cake]}
cake, jam, pie, teaOptionalOptional
Optional<String> first = Stream.of("kiwi", "fig").filter(s -> s.startsWith("z")).findFirst();
System.out.println(first.orElse("none") + " " + first.isPresent());פלטOutput
none false
חריגות וקבציםExceptions and files
מפגשSession 29try / catch / finallytry / catch / finally
try {
int x = Integer.parseInt("12a");
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("bad number: " + e.getMessage());
} finally {
System.out.println("always runs");
}פלטOutput
bad number: For input string: "12a" always runs
לזרוק בעצמכםThrowing your own
int age = -3;
try {
if (age < 0) {
throw new IllegalArgumentException("age must be >= 0");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}פלטOutput
age must be >= 0
כתיבה וקריאה של קובץWriting and reading a file
Path p = Path.of("notes.txt");
Files.writeString(p, "first\nsecond\n");
List<String> lines = Files.readAllLines(p);
System.out.println(lines.size() + " lines, last: " + lines.get(1));
Files.deleteIfExists(p);פלטOutput
2 lines, last: second
try-with-resourcestry-with-resources
Path p = Path.of("log.txt");
try (var out = Files.newBufferedWriter(p)) {
out.write("saved");
}
System.out.println(Files.readString(p) + " " + Files.exists(p));
Files.delete(p);פלטOutput
saved true
קובץ שלא קייםA file that doesn't exist
try {
Files.readString(Path.of("nope.txt"));
} catch (NoSuchFileException e) {
System.out.println("missing: " + e.getMessage());
}פלטOutput
missing: nope.txt
Threads ומקביליותThreads and concurrency
מפגשSession 37start ו-joinstart and join
Thread t = new Thread(() -> System.out.println("worker on " + Thread.currentThread().getName()));
t.start();
t.join();
System.out.println("main continues after join");פלטOutput
worker on Thread-0 main continues after join
synchronizedsynchronized
int[] count = {0};
Object lock = new Object();
Runnable inc = () -> {
for (int i = 0; i < 10000; i++) {
synchronized (lock) { count[0]++; }
}
};
Thread a = new Thread(inc), b = new Thread(inc);
a.start(); b.start(); a.join(); b.join();
System.out.println(count[0]);פלטOutput
20000
Atomic ו-ConcurrentHashMapAtomics and ConcurrentHashMap
AtomicInteger hits = new AtomicInteger();
Map<String, Integer> m = new ConcurrentHashMap<>();
hits.incrementAndGet();
m.merge("red", 1, Integer::sum);
m.merge("red", 1, Integer::sum);
System.out.println(hits.get() + " " + m);פלטOutput
1 {red=2}ExecutorService ו-FutureExecutorService and Future
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> f = pool.submit(() -> 6 * 7);
System.out.println(f.get());
pool.shutdown();פלטOutput
42
BlockingQueueBlockingQueue
BlockingQueue<String> q = new ArrayBlockingQueue<>(2);
Thread producer = new Thread(() -> {
try { q.put("job1"); q.put("job2"); } catch (InterruptedException e) { }
});
producer.start();
System.out.println(q.take() + " " + q.take());פלטOutput
job1 job2
CompletableFuture ו-virtual threadsCompletableFuture and virtual threads
String r = CompletableFuture.supplyAsync(() -> "data").thenApply(String::toUpperCase).join();
Thread v = Thread.ofVirtual().start(() -> { });
v.join();
System.out.println(r + " " + v.isVirtual());פלטOutput
DATA true
Git, Maven ו-GradleGit, Maven and Gradle
מפגשSession 30מאגר חדש ושמירה ראשונהA new repo and a first commit
git init
git add .
git commit -m "first version"
git log --onelineענף ומיזוגA branch and a merge
git switch -c feature
git commit -am "add feature"
git switch main
git merge featureGitHubGitHub
git remote add origin https://github.com/you/shelf.git
git push -u origin main
git pullMavenMaven
mvn -q archetype:generate -DgroupId=dev.shelf -DartifactId=shelf -DinteractiveMode=false
mvn test
mvn packageGradleGradle
gradle init --type java-application
./gradlew test
./gradlew runSwing ומשחקיםSwing and games
מפגשSession 48התנגשות AABBAABB collision
Rectangle player = new Rectangle(10, 10, 20, 20);
Rectangle coin = new Rectangle(25, 25, 8, 8);
System.out.println(player.intersects(coin));
System.out.println(player.contains(new Point(15, 15)));פלטOutput
true true
delta timeDelta time
double x = 0, speed = 120; // pixels per second
long last = 0;
for (long now : new long[]{16_000_000L, 33_000_000L, 50_000_000L}) {
double dt = (now - last) / 1e9;
x += speed * dt;
last = now;
}
System.out.printf("x = %.1f%n", x);פלטOutput
x = 6.0
ציור על תמונה, בלי חלוןDrawing on an image, no window
BufferedImage img = new BufferedImage(40, 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(Color.ORANGE);
g.fillRect(0, 0, 20, 20);
g.dispose();
System.out.println(Integer.toHexString(img.getRGB(5, 5)) + " " + Integer.toHexString(img.getRGB(30, 5)));פלטOutput
ffffc800 ff000000
מצבי משחקGame states
enum State { MENU, PLAYING, GAME_OVER }
State s = State.MENU;
for (String ev : new String[]{"start", "die"}) {
s = switch (s) {
case MENU -> ev.equals("start") ? State.PLAYING : s;
case PLAYING -> ev.equals("die") ? State.GAME_OVER : s;
case GAME_OVER -> s;
};
}
System.out.println(s);פלטOutput
GAME_OVER
חלון ולולאת משחק (במחשב שלכם)A window and a game loop (on your computer)
javac Game.java
java Game
jar --create --file game.jar --main-class Game -C out .
jpackage --input . --main-jar game.jar --name MyGame