Slide 1

Slide 1 text

https://linktr.ee/jeanneboyarsky 1 Preparing for the Java 21 cert + Learning New Features Jeanne Boyarsky 3/18/25 JavaOne speakerdeck.com/boyarsky

Slide 2

Slide 2 text

https://linktr.ee/jeanneboyarsky At end of session 2 https://speakerdeck.com/boyarsky

Slide 3

Slide 3 text

https://linktr.ee/jeanneboyarsky Pause for a Commercial 3 Java certs: 8/11/17/21 Real World Java

Slide 4

Slide 4 text

https://linktr.ee/jeanneboyarsky Disclaimers 4 Some of the material in this presentation appears in our certification books.

Slide 5

Slide 5 text

https://linktr.ee/jeanneboyarsky Agenda 5 Module Topics 1 Intro, text blocks, sequenced collections, string api changes 2 Records and sealed classes 3 Instanceof/switch expressions/pattern matching 4 Virtual Threads

Slide 6

Slide 6 text

https://linktr.ee/jeanneboyarsky If new to the cert 6 808 809 815 + 816 819 829 Associate Professional Java 8 Java 11 Java 17 Java 21 830 Foundations 811

Slide 7

Slide 7 text

https://linktr.ee/jeanneboyarsky Features 7 Feature Preview Final Text Blocks 13, 14 15 Sequenced Collections 21 String APIs Misc

Slide 8

Slide 8 text

@jeanneboyarsky What’s wrong? String old = “javaone,Java One,"session" + "meetup,Various,lecture\n"; 8 Doesn’t compile: missing \ Missing quote on line 1 Missing line break 15

Slide 9

Slide 9 text

@jeanneboyarsky Compare String old = “javaone,Java One,\"session\"\n" + “meetup,Various,lecture\n"; String textBlock = """ javaone,Java One,"session" meetup,Various,lecture """; 9 Easier to read and code! 15

Slide 10

Slide 10 text

@jeanneboyarsky Text Block Syntax String textBlock = """ javaone,Java One,"session" meetup,Various,lecture """; incidental whitespace start block end block 15 10

Slide 11

Slide 11 text

@jeanneboyarsky Essential Whitespace String textBlock = """ Jeanne Boyarsky """; incidental whitespace essential whitespace 15 11

Slide 12

Slide 12 text

@jeanneboyarsky Ending lines String textBlock = """ Jeanne Boyarsky \s Becoming one of the first Java 21 \ certified programmers \ (and learning new features) """; continue on next line without a line break new escape character keeps trailing whitespace tab 15 12

Slide 13

Slide 13 text

@jeanneboyarsky New lines String textBlock = """ \n Jeanne\nBoyarsky """; no line break at end Two new lines (explicit and implicit) One new line (explicit) 15 13

Slide 14

Slide 14 text

@jeanneboyarsky Escaping Three Quotes String textBlock = """ better \""" but can do \"\"\" """; 15 14

Slide 15

Slide 15 text

@jeanneboyarsky More Index Of Overloads 21 15 public int indexOf(int ch) public int indexOf(int ch, int fromIndex) public int indexOf(int ch, int fromIndex, int endIndex) public int indexOf(String str) public int indexOf(String str, int fromIndex) public int indexOf(String str, int fromIndex, int endIndex) var name = "animals"; System.out.println(name.indexOf('a', 2, 4)); System.out.println(name.indexOf("al", 2, 5)); Outputs -1 4

Slide 16

Slide 16 text

https://linktr.ee/jeanneboyarsky Java 17 16 ArrayList, LinkedList, Deque, TreeSet, TreeMap became sequenced collections LinkedHashSet and LinkedHashMap too

Slide 17

Slide 17 text

https://linktr.ee/jeanneboyarsky What does this output? 17 HashSet set = new HashSet<>(); set.add("Donald"); set.add("Mickey"); set.add("Minnie"); System.out.println(set.iterator().next()); Encounter order undefined(but Mickey on my machine) 21

Slide 18

Slide 18 text

https://linktr.ee/jeanneboyarsky 18 21 Java 21

Slide 19

Slide 19 text

https://linktr.ee/jeanneboyarsky New APIs 19 SequencedCollection SequencedCollection reversed(); void addFirst(E); void addLast(E); E getFirst(); E getLast(); E removeFirst(); E removeLast(); SequencedSet SequencedSet reversed(); SequencedMap SequencedMap reversed(); SequencedSet sequencedKeySet(); SequencedCollection sequencedValues(); SequencedSet> sequencedEntrySet(); V putFirst(K, V); V putLast(K, V); Entry fi rstEntry(); Entry lastEntry(); Entry pollFirstEntry(); Entry pollLastEntry(); 21

Slide 20

Slide 20 text

https://linktr.ee/jeanneboyarsky Now defined! 20 SequencedSet set = new LinkedHashSet<>(); set.add("Donald"); set.add("Mickey"); set.add("Minnie"); System.out.println(set.getFirst()); Donald Note: LInkedHashSet not new 21

Slide 21

Slide 21 text

@jeanneboyarsky Module 1 - Question 1 Which is true about this text block? String sql = """ select * from mytable where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 21

Slide 22

Slide 22 text

@jeanneboyarsky Module 1 - Question 1 Which is true about this text block? String sql = """ select * from mytable where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 22 A

Slide 23

Slide 23 text

@jeanneboyarsky Module 1 - Question 2 Which is true about this text block? String sql = """select * from mytable \ where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 23

Slide 24

Slide 24 text

@jeanneboyarsky Module 1 - Question 2 Which is true about this text block? String sql = """select * from mytable \ where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 24 D (missing opening line break)

Slide 25

Slide 25 text

@jeanneboyarsky Module 1 - Question 3 Which is true about this text block? String sql = """ select * \s from mytable \s where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 25

Slide 26

Slide 26 text

@jeanneboyarsky Module 1 - Question 3 Which is true about this text block? String sql = """ select * \s from mytable \s where weather = 'snow'; """; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 26 B

Slide 27

Slide 27 text

@jeanneboyarsky Module 1 - Question 4 Which is true about this text block? String sql = """select * from mytable;"""; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 27

Slide 28

Slide 28 text

@jeanneboyarsky Module 1 - Question 4 Which is true about this text block? String sql = """select * from mytable;"""; A. Has incidental whitespace B. Has essential whitespace C. Both A and B D. Does not compile 28 D (one line)

Slide 29

Slide 29 text

@jeanneboyarsky Module 1 - Question 5 How many lines does this print out? String sql = """ select * \n from mytable; """; System.out.print(sql); A. 2 B. 3 C. 4 D. Does not compile 29

Slide 30

Slide 30 text

@jeanneboyarsky Module 1 - Question 5 How many lines does this print out? String sql = """ select * \n from mytable; """; System.out.print(sql); A. 2 B. 3 C. 4 D. Does not compile 30 C

Slide 31

Slide 31 text

@jeanneboyarsky Module 1 - Question 6 How many escapes can be removed without changing the behavior? String sql = """ select \"name\" from mytable \ where value = '\"\""' """; A. 2 B. 3 C. 4 D. Does not compile 31

Slide 32

Slide 32 text

@jeanneboyarsky Module 1 - Question 6 How many escapes can be removed without changing the behavior? String sql = """ select \"name\" from mytable \ where value = '\"\""' """; A. 2 B. 3 C. 4 D. Does not compile 32 B (around name and second on value)

Slide 33

Slide 33 text

https://linktr.ee/jeanneboyarsky Agenda 33 Module Topics 1 Intro, text blocks, sequenced collections, string api changes 2 Records and sealed classes 3 Instanceof/switch expressions/pattern matching 4 Virtual Threads

Slide 34

Slide 34 text

https://linktr.ee/jeanneboyarsky Features 34 Feature Preview Final Records 14, 15 16 Sealed Classes 15, 16 17

Slide 35

Slide 35 text

@jeanneboyarsky Now allowed 16 public class Kangaroo { class Joey { static int numJoeys = 0; } void hop() { interface Hopper {} enum Size { EXTRA_SMALL, SMALL }; } } Static field in inner classes and method local enums/interfaces 35

Slide 36

Slide 36 text

@jeanneboyarsky Immutable class 1. Make fields final and private 2. Don’t provide setters 3. No subclasses (ex: make class final) 4. Write constructor taking all fields 36 16

Slide 37

Slide 37 text

@jeanneboyarsky POJO • constructor • toString() • hashCode() - more rules • equals() - still more rules 37 16

Slide 38

Slide 38 text

@jeanneboyarsky Simple Record 16 public record Book (String title, int numPages) { } New type Automatically get * final record * private final instance variables * public accessors * constructor taking both fields * equals * hashCode * no instance initializers 38

Slide 39

Slide 39 text

@jeanneboyarsky Using the Record 16 Book book = new Book("Breaking and entering", 289); System.out.println(book.title()); System.out.println(book.toString()); No “get” Outputs: Breaking and entering Book[title=Breaking and entering, numPages=289] 39

Slide 40

Slide 40 text

@jeanneboyarsky Add/change methods 16 public record Book (String title, int numPages) { @Override public String title() { return '"' + title + '"'; } public boolean isLong() { return numPages > 300; } } Custom method Change behavior 40

Slide 41

Slide 41 text

@jeanneboyarsky Not really immutable 16 public record Book (String title, int numPages, List chapters) { } Book book = new Book("Breaking and entering", 289, chapters); chapters.add("2"); book.chapters().add("3"); System.out.println(book.chapters()); Prints [1,2,3] because shallow immutability 41

Slide 42

Slide 42 text

@jeanneboyarsky Now immutable 16 public record Book (String title, int numPages, List chapters) { public Book { chapters = List.copyOf(chapters); } } Must match record access modifier Compact constructor 42

Slide 43

Slide 43 text

@jeanneboyarsky Sealed classes 17 public abstract sealed class Seasons permits Fall, Spring, Summer, Winter { } final class Fall extends Seasons {} final class Spring extends Seasons {} final class Summer extends Seasons {} final class Winter extends Seasons {} Seasons Fall Spring Summer Winter 43

Slide 44

Slide 44 text

@jeanneboyarsky Subclass modifiers 44 17 Modifer Meaning final Hierarchy ends here non-sealed Others can subclass sealed Another layer

Slide 45

Slide 45 text

@jeanneboyarsky Sealed interface 17 public sealed interface TimeOfDay permits Morning, Afternoon, Evening { boolean early(); } public non-sealed class Morning implements TimeOfDay { public boolean early() { return true; } } public non-sealed class Afternoon implements TimeOfDay { public boolean early() { return false; } } public record Evening(int hour) implements TimeOfDay { public boolean early() { return false; } } Records are implicitly final 45

Slide 46

Slide 46 text

@jeanneboyarsky instanceof 17 public class InstanceOf { static sealed class BoolWrapper permits TrueWrapper, FalseWrapper { } static final class TrueWrapper extends BoolWrapper {} static final class FalseWrapper extends BoolWrapper {} public static void main(String[] args) { Map map = new HashMap<>(); String string = ""; BoolWrapper boolWrapper = new TrueWrapper(); System.out.println(map instanceof List); // false System.out.println("" instanceof List); // error System.out.println(boolWrapper instanceof List); // error } 46

Slide 47

Slide 47 text

@jeanneboyarsky Module 2 - Question 1 How many lines need to be removed for this code to compile? public record BBQ(String type) {} public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.setType("pork")); System.out.println(bbq.getType()); System.out.println(bbq.equals(bbq)); } 47 C. 2 D. None of the above A. 0 B. 1

Slide 48

Slide 48 text

@jeanneboyarsky Module 2 - Question 1 How many lines need to be removed for this code to compile? public record BBQ(String type) {} public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.setType("pork")); System.out.println(bbq.getType()); System.out.println(bbq.equals(bbq)); } 48 C. 2 D. None of the above A. 0 B. 1 C (no setters and getter should be type())

Slide 49

Slide 49 text

@jeanneboyarsky Module 2 - Question 2 What does this output? public record BBQ(String type) { BBQ { type = type.toUpperCase(); } } public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.type()); } 49 C. Does not compile D. None of the above A. chicken B. CHICKEN

Slide 50

Slide 50 text

@jeanneboyarsky Module 2 - Question 2 What does this output? public record BBQ(String type) { BBQ { type = type.toUpperCase(); } } public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.type()); } 50 C. Does not compile D. None of the above A. chicken B. CHICKEN C (compact constructor needs to be public because record is)

Slide 51

Slide 51 text

@jeanneboyarsky Module 2 - Question 3 What does this output? record BBQ(String type) { BBQ { type = type.toUpperCase(); } } public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.type()); } 51 C. Does not compile D. None of the above A. chicken B. CHICKEN

Slide 52

Slide 52 text

@jeanneboyarsky Module 2 - Question 3 What does this output? record BBQ(String type) { BBQ { type = type.toUpperCase(); } } public static void main(String[] args) { BBQ bbq = new BBQ("chicken"); System.out.println(bbq.type()); } 52 C. Does not compile D. None of the above A. chicken B. CHICKEN B

Slide 53

Slide 53 text

@jeanneboyarsky Module 2 - Question 4 What does this output? public record BBQ(String type) implements Comparable { public int compareTo(BBQ bbq) { return type.compareTo(bbq.type); } } public static void main(String[] args) { BBQ beef = new BBQ("beef"); BBQ pork = new BBQ("pork"); System.out.println(pork.compareTo(beef)); } 53 C. 0 D. Does not compile A. Negative # B. Positive #

Slide 54

Slide 54 text

@jeanneboyarsky Module 2 - Question 4 What does this output? public record BBQ(String type) implements Comparable { public int compareTo(BBQ bbq) { return type.compareTo(bbq.type); } } public static void main(String[] args) { BBQ beef = new BBQ("beef"); BBQ pork = new BBQ("pork"); System.out.println(pork.compareTo(beef)); } 54 C. 0 D. Does not compile A. Negative # B. Positive # B

Slide 55

Slide 55 text

@jeanneboyarsky Module 2 - Question 5 How many compiler errors are in this code? public sealed class Phone { class IPhone extends Phone { } class Android extends Phone { } } 55 C. 2 D. 3 A. 0 B. 1

Slide 56

Slide 56 text

@jeanneboyarsky Module 2 - Question 5 How many compiler errors are in this code? public sealed class Phone { class IPhone extends Phone { } class Android extends Phone { } } 56 C. 2 D. 3 A. 0 B. 1 C (extending classes needed to be sealed or final)

Slide 57

Slide 57 text

https://linktr.ee/jeanneboyarsky Agenda 57 Module Topics 1 Intro, text blocks, sequenced collections, string api changes 2 Records and sealed classes 3 Instanceof/switch expressions/pattern matching 4 Virtual Threads

Slide 58

Slide 58 text

https://linktr.ee/jeanneboyarsky Features 58 Feature Preview Final Switch Expressions 12, 13 14 Pattern Matching for InstanceOf 14, 15 16 Pattern Matching for Switch 17, 18, 19, 20 21 Record Patterns 21 Unnamed Variables & Patterns 21 22

Slide 59

Slide 59 text

@jeanneboyarsky Pattern matching for if 16 if (num instanceof Integer) { Integer numAsInt = (Integer) num; System.out.println(numAsInt); } if (num instanceof Double) { Double numAsDouble = (Double) num; System.out.println(numAsDouble.intValue()); } if (num instanceof Integer numAsInt) { System.out.println(numAsInt); } if (num instanceof Double numAsDouble) { System.out.println(numAsDouble.intValue()); } Pattern variable 59

Slide 60

Slide 60 text

@jeanneboyarsky Flow Scope 16 if (num instanceof Double d1 && d1.intValue() % 2 == 0) { System.out.println(d1.intValue()); } if (num instanceof Double d2 || d2.intValue() % 2 == 0) { System.out.println(d2.intValue()); } Does not compile because d2 might not be double Compiles 60

Slide 61

Slide 61 text

@jeanneboyarsky Does this compile? 16 if (num instanceof Double n) System.out.println(n.intValue()); if (num instanceof Integer n) System.out.println(n); Yes. Only in scope for if statement 61

Slide 62

Slide 62 text

@jeanneboyarsky Does this compile? 16 if (num instanceof Double n) System.out.println(n.intValue()); System.out.println(n.intValue()); No. If statement is over 62

Slide 63

Slide 63 text

@jeanneboyarsky Does this compile? 16 if (!(num instanceof Double n)) { return; } System.out.println(n.intValue()); Yes. Returns early so rest is like an else 63

Slide 64

Slide 64 text

@jeanneboyarsky Does this compile? 16 if (!(num instanceof Double n)) { return; } System.out.println(n.intValue()); if (num instanceof Double n) System.out.println(n.intValue()); No. n is still in scope 64

Slide 65

Slide 65 text

@jeanneboyarsky Reusing a variable 16 if (num instanceof Integer numAsInt) { numAsInt = 6; System.out.println(numAsInt); } Legal. please don’t. 65

Slide 66

Slide 66 text

@jeanneboyarsky Behavior change 21 Integer num = 123; if (num instanceof Integer num) { } Compiles in Java 21, but not 17 66

Slide 67

Slide 67 text

@jeanneboyarsky What does this print? 1? String store = "Hallmark"; switch(store) { case "Hallmark" : System.out.println("KC"); case "Crayola" : System.out.println("PA"); default: System.out.println("anywhere"); } Three lines (missing break) 67

Slide 68

Slide 68 text

@jeanneboyarsky Newer Switch Syntax 14 String store = "Hallmark"; switch(store) { case "Hallmark" -> System.out.println("KC"); case "Crayola", "H&R" -> System.out.println("PA"); default -> System.out.println("anywhere"); } Arrow labels No break keyword Multiple values 68

Slide 69

Slide 69 text

@jeanneboyarsky Switch Expressions 14 String store = "Hallmark"; String output = switch(store) { case "Hallmark" -> "KC"; case "Crayola" -> "PA"; default -> "anywhere"; }; System.out.println(output); Returns values 69

Slide 70

Slide 70 text

@jeanneboyarsky Using Pattern Matching 70 21 return switch (obj) { case null -> ""; case Integer i when i >= 21 -> "can gamble"; case Integer i -> "too young to gamble"; case String s when "poker".equals(s) -> "table game"; case String s when "craps".equals(s) -> "table game"; case String s -> "other game"; default -> throw new IllegalArgumentException("unexpected type"); }; guard clause pattern variable null allowed Still Null Pointer if don’t specify case null

Slide 71

Slide 71 text

@jeanneboyarsky Order matters 71 21 return switch (obj) { case null -> ""; case Integer i -> "too young to gamble"; case Integer i when i >= 21 -> "can gamble”; // DOES NOT COMPILE case String s -> "other game"; default -> throw new IllegalArgumentException("unexpected type"); }; Order like catching exceptions!

Slide 72

Slide 72 text

@jeanneboyarsky Enums 72 21 enum Suit { HEART, DIAMOND, CLUB, SPADE; } String symbol(Suit suit) { return switch (suit) { case HEART -> "♥"; case Suit.DIAMOND -> "♦"; case CLUB -> "♣"; case Suit.SPADE -> "♠"; }; } Fails compilation if miss one since no default

Slide 73

Slide 73 text

@jeanneboyarsky Even Here 73 21 boolean idCheck(Integer age) { boolean check ; switch (age) { case Integer i when i <= 40 : check = true; break; default : check = false; break; } return check; } Yes, classic switch

Slide 74

Slide 74 text

@jeanneboyarsky Pattern variable scope 74 21 boolean idCheck(Integer age) { boolean check ; switch (age) { case Integer i when i <= 21 : check = true; // DOES NOT COMPILE case Integer i when i <= 40 : check = true; default : check = false; } return check; } Can’t use pattern variable if fall thru

Slide 75

Slide 75 text

@jeanneboyarsky More features 14 String output = switch(store) { case "Hallmark" -> "KC"; case "Legoland" -> { int random = new Random().nextInt(); String city = random % 2 == 0 ? "KC" : "Carlsbad"; yield city; } default -> throw new IllegalArgumentException("Unknown"); }; System.out.println(output); Block yield throws exception so no return value needed 75

Slide 76

Slide 76 text

@jeanneboyarsky Is this legal? 14 private void confusing() { this.yield(); } private void yield() { String store = "Legoland"; String output = switch(store) { case "Legoland" -> { yield "Carlsbad"; } default -> "other"; }; System.out.println(output); } Yes. yield is like var 76

Slide 77

Slide 77 text

@jeanneboyarsky How about now? 14 private void confusing() { yield(); } private void yield() { String store = "Legoland"; String output = switch(store) { case "Legoland" -> { yield "Carlsbad"; } default -> "other"; }; System.out.println(output); } No to invoke a method called yield, qualify the yield with a receiver or type name 77

Slide 78

Slide 78 text

@jeanneboyarsky Yield with Switch 14 Position pos = Position.TOP; int stmt = switch(pos) { case TOP: yield 1; case BOTTOM: yield 0; }; int expr = switch(pos) { case TOP -> 1; case BOTTOM -> 0; }; Same! 78

Slide 79

Slide 79 text

@jeanneboyarsky Missing value 14 enum Position { TOP, BOTTOM }; Position pos = Position.TOP; int stmt = switch(pos) { case TOP: yield 1; }; int expr = switch(pos) { case BOTTOM -> 0; }; Does not compile because assigning value (poly expression) 79

Slide 80

Slide 80 text

https://linktr.ee/jeanneboyarsky Record Patterns 80 enum Suit { HEART, DIAMOND, CLUB, SPADE; } enum Rank { NUM_2, NUM_3, NUM_4, NUM_5, NUM_6, NUM_7 NUM_8, NUM_9, NUM_10, JACK, QUEEN, KING, ACE; } record Card(Suit suit, Rank rank) { } if (card instanceof Card c) { System.out.println(c.suit()); System.out.println(c.rank()); } if (card instanceof Card(Suit suit, Rank rank)) { System.out.println(suit); System.out.println(rank); } 21 Deconstructed

Slide 81

Slide 81 text

https://linktr.ee/jeanneboyarsky Nested Record Patterns 81 record MultiDeck(int deckNum, Card card) { } if (multi instanceof MultiDeck(int deckNum, Card(Suit suit, Rank rank))) { System.out.println(deckNum); System.out.println(suit); System.out.println(rank); } 21

Slide 82

Slide 82 text

https://linktr.ee/jeanneboyarsky Switch pattern matching 82 switch(card) { case Card(Suit suit, Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21

Slide 83

Slide 83 text

https://linktr.ee/jeanneboyarsky Switch pattern matching 83 String str = ""; switch (str) { case "heart" -> System.out.println("heart"); } Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(Suit suit, Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21 Must be exhaustive if using “when”

Slide 84

Slide 84 text

https://linktr.ee/jeanneboyarsky What can’t you do? 84 • In switch(x), x still can’t be • boolean • float • double • long • _ as pattern (coming in Java 22) • Expanding non-records (coming ?) 21

Slide 85

Slide 85 text

https://linktr.ee/jeanneboyarsky Module 3 - Question 1 85 How many lines do you need to remove to make this code compile? double odds(Object obj) { return switch (obj) { case String s -> throw new IllegalArgumentException("unknown game"); case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case Object o -> throw new IllegalArgumentException("unknown game"); default -> throw new IllegalArgumentException("known game"); }; } A. 0 B. 1 C. 2 D. 3

Slide 86

Slide 86 text

https://linktr.ee/jeanneboyarsky Module 3 - Question 1 86 How many lines do you need to remove to make this code compile? double odds(Object obj) { return switch (obj) { case String s -> throw new IllegalArgumentException("unknown game"); case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case Object o -> throw new IllegalArgumentException("unknown game"); default -> throw new IllegalArgumentException("known game"); }; } A. 0 B. 1 C. 2 D. 3 C String s & Object o or default

Slide 87

Slide 87 text

@jeanneboyarsky Module 3 - Question 2 What does the following print? Object robot = "694"; if (robot instanceof String s) { System.out.print("x"); } if (robot instanceof Integer s) { System.out.print("y"); } System.out.println(robot); 87 C. y694 D. Does not compile A. x694 B. xy694

Slide 88

Slide 88 text

@jeanneboyarsky Module 3 - Question 2 What does the following print? Object robot = "694"; if (robot instanceof String s) { System.out.print("x"); } if (robot instanceof Integer s) { System.out.print("y"); } System.out.println(robot); 88 C. y694 D. Does not compile A. x694 B. xy694 A

Slide 89

Slide 89 text

@jeanneboyarsky Module 3 - Question 3 What is true about this class? class Sword { int length; public boolean equals(Object o) { if (o instanceof Sword sword) { return length == sword.length; } return false; } // assume hashCode properly implemented } 89 C. equals() does not compile A. equals() is correct B. equals() is incorrect

Slide 90

Slide 90 text

@jeanneboyarsky Module 3 - Question 3 What is true about this class? class Sword { int length; public boolean equals(Object o) { if (o instanceof Sword sword) { return length == sword.length; } return false; } // assume hashCode properly implemented } 90 C. equals() does not compile A. equals() is correct B. equals() is incorrect A

Slide 91

Slide 91 text

@jeanneboyarsky Module 3 - Question 4 How many if statements fail to compile? Number n = 4; if (n instanceof Integer x) {} if (n instanceof Integer x && x.intValue() > 1) {} if (n instanceof Integer x || x.intValue() > 1) {} if (n instanceof Integer x || x.toString().isEmpty()) {} 91 C. 2 D. 3 A. 0 B. 1

Slide 92

Slide 92 text

@jeanneboyarsky Module 3 - Question 4 How many if statements fail to compile? Number n = 4; if (n instanceof Integer x) {} if (n instanceof Integer x && x.intValue() > 1) {} if (n instanceof Integer x || x.intValue() > 1) {} if (n instanceof Integer x || x.toString().isEmpty()) {} 92 C. 2 D. 3 A. 0 B. 1 C (last 2 could be null)

Slide 93

Slide 93 text

@jeanneboyarsky Module 3 - Question 5 What does printLength(3) print? class Sword { int length = 8; public void printLength(Object x) { if (x instanceof Integer length) { length = 2; } System.out.println(length); } } 93 C. 8 D. Does not compile A. 2 B. 3

Slide 94

Slide 94 text

@jeanneboyarsky Module 3 - Question 5 What does printLength(3) print? class Sword { int length = 8; public void printLength(Object x) { if (x instanceof Integer length) { length = 2; } System.out.println(length); } } 94 C. 8 D. Does not compile A. 2 B. 3 C

Slide 95

Slide 95 text

https://linktr.ee/jeanneboyarsky Module 3 - Question 6 95 Which of these compile? (more than one) A. if (card instanceof Card (Suit suit, Rank rank)) { } B. if (card instanceof Card (var suit, var rank)) { } C. if (card instanceof Card c) { } D. if (card instanceof Card c.suit, c.rank) { }

Slide 96

Slide 96 text

https://linktr.ee/jeanneboyarsky Module 3 - Question 6 96 Which of these compile? (more than one) A. if (card instanceof Card (Suit suit, Rank rank)) { } B. if (card instanceof Card (var suit, var rank)) { } C. if (card instanceof Card c) { } D. if (card instanceof Card c.suit, c.rank) { } A, B, C

Slide 97

Slide 97 text

https://linktr.ee/jeanneboyarsky Agenda 97 Module Topics 1 Intro, text blocks, sequenced collections, string api changes 2 Records and sealed classes 3 Instanceof/switch expressions/pattern matching 4 Virtual Threads

Slide 98

Slide 98 text

https://linktr.ee/jeanneboyarsky Features 98 Feature Preview Final Virtual Threads 19, 20 21

Slide 99

Slide 99 text

https://linktr.ee/jeanneboyarsky Leaps in Concurrency 99 Threads + Executors + Virtual Threads Plus many APIs… 21

Slide 100

Slide 100 text

https://linktr.ee/jeanneboyarsky Why we need threads 100 Program Do calculation and call REST API Do calculation and call REST API CPU Network I’m bored… I’m waiting for a reply

Slide 101

Slide 101 text

https://linktr.ee/jeanneboyarsky Why we need virtual threads 101 Program Do calculation and call REST API Proceed CPU Network Still bored… Still waiting for a reply Platform Thread 1 Platform Thread n Do calculation and call REST API Send to threads

Slide 102

Slide 102 text

https://linktr.ee/jeanneboyarsky Virtual Thread 1 With virtual threads 102 Program Do calculation and call REST API Proceed CPU Network Thanks for the work! Me too! Platform Thread 1 Platform Thread n Send to threads Virtual Thread t Do calculation and call REST API Virtual Thread t+1 Do calculation and call REST API Virtual Thread x Do calculation and call REST API

Slide 103

Slide 103 text

https://linktr.ee/jeanneboyarsky When most helpful? 103 • Thousands of threads • Not CPU bound 21

Slide 104

Slide 104 text

https://linktr.ee/jeanneboyarsky Comparing 104 Platform (Traditional) Thread Virtual Thread Heavyweight Lightweight Tied to OS threads Runs on OS thread but doesn’t monopolize Often pooled Often shortlived Instance of java.lang.Thread Instance of java.lang.Thread 21

Slide 105

Slide 105 text

https://linktr.ee/jeanneboyarsky Fill in the blank 105 try (ExecutorService service = Executors._________) { service.submit(() -> doStuff()); } Examples: • newSingleThreadExecutor() • newFixedThreadPool(5) • newCachedThreadPool() • newVirtualThreadPerTaskExecutor() 21

Slide 106

Slide 106 text

https://linktr.ee/jeanneboyarsky Autocloseable 106 Method Java 21 shutdown() No more tasks, but finish ones have shutdownNow() Stop tasks in progress close() Calls shutdown by default 19

Slide 107

Slide 107 text

https://linktr.ee/jeanneboyarsky If need directly 107 Platform Thread Virtual Thread Thread.ofPlatform() Thread.ofVirtual() new Thread(…) Not via constructor 21

Slide 108

Slide 108 text

https://linktr.ee/jeanneboyarsky What about Scoped Values 108 Preview feature in Java 21 so not on exam 21

Slide 109

Slide 109 text

@jeanneboyarsky Create a Locale Locale loc = Locale.getDefault(); Locale constant = Locale.JAPANESE; Locale lang = Locale.of(“en”); Locale country = Locale.of(“en", "US"); Locale invalid = Locale.of(“US"); 109 19

Slide 110

Slide 110 text

@jeanneboyarsky Formatting with Locales NumberFormat shortFormat = NumberFormat. getCompactNumberInstance( Locale.CANADA_FRENCH, NumberFormat.Style.SHORT); NumberFormat longFormat = NumberFormat. getCompactNumberInstance( Locale.CANADA_FRENCH, NumberFormat.Style.LONG); System.out.println(shortFormat.format(3_000)); System.out.println(longFormat.format(3_000)); 3 k 3 mille 110

Slide 111

Slide 111 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 1 111 Which is used to create/with a virtual thread? (more than 1 is correct) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread()

Slide 112

Slide 112 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 1 112 Which is used to create/with a virtual thread? (more than 1 is correct) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread() C, E

Slide 113

Slide 113 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 2 113 Which is used to create/with a platform thread? (more than 1 is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform()

Slide 114

Slide 114 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 2 114 Which is used to create/with a platform thread? (more than 1 is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform() A, D, F

Slide 115

Slide 115 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 3 115 What is true doStuff() at line v1? try (var service = Executors.newVirtualThreadPerTaskExecutor()) { service.submit(() -> doStuff()); } // line v1 A. doStuff() may be running B. doStuff() was killed C. doStuff() completed D. None of the above 21

Slide 116

Slide 116 text

https://linktr.ee/jeanneboyarsky Module 4 - Question 3 116 What is true doStuff() at line v1? try (var service = Executors.newVirtualThreadPerTaskExecutor()) { service.submit(() -> doStuff()); } // line v1 A. doStuff() may be running B. doStuff() was killed C. doStuff() completed D. None of the above 21 C

Slide 117

Slide 117 text

@jeanneboyarsky Module 4 - Question 4 I learned a lot today A. True B. False 117

Slide 118

Slide 118 text

https://linktr.ee/jeanneboyarsky Good to know, but not on exam 118 • UTF-8 is the default character set when reading a file • StringBuilder/StringBuffer have a repeat method • String.splitWithDelimitters(regex, limit) • Finalization deprecated for removal

Slide 119

Slide 119 text

https://linktr.ee/jeanneboyarsky Good to know, but not on exam 119 Code Snippets in JavaDoc Inline * {@snippet : * if (v.isPresent()) { * System.out.println("v: " + v.get()); * } * } External {@snippet fi le="ShowOptional.java" region=“example"} Example transformation System.out.println("Hello World!"); // @highlight substring="println"