Upgrade to Pro — share decks privately, control downloads, hide ads and more …

2024-java21.pdf

Jeanne Boyarsky
February 15, 2024
40

 2024-java21.pdf

Jeanne Boyarsky

February 15, 2024
Tweet

Transcript

  1. https://linktr.ee/jeanneboyarsky 1 Preparing for the Java 21 cert + Learning

    New Features Jeanne Boyarsky 2/15/24 NYJavaSIG speakerdeck.com/boyarsky
  2. https://linktr.ee/jeanneboyarsky Disclaimer 3 I do not work for Oracle so

    no safe harbor statement. However, I am not authorized to tell you any non public information or if I know any :) Some of the material in this presentation may appear in our upcoming certification books.
  3. https://linktr.ee/jeanneboyarsky Strategy 4 Option 1 - wait for Java 21

    study materials Option 2: 1. Study from a Java 17 study guide 2. Read about Java 18-21 features 3. Focus on edge cases 4. Do any practice questions you can find This talk helps with option 2. Or if you just want to learn
  4. https://linktr.ee/jeanneboyarsky Agenda 5 Topics Chances of being in objectives Virtual

    threads 95% or higher Pattern matching for switch 95% or higher Record patterns 95% or higher Sequenced Collections 10-30% Other topics + open Q&A less than 5%
  5. https://linktr.ee/jeanneboyarsky Why we need threads 8 Program Do calculation and

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

    and call REST API Proceed CPU Network Sill bored… Still waiting for a reply Thread 1 Thread n Do calculation and call REST API Send to threads
  7. https://linktr.ee/jeanneboyarsky Comparing 11 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
  8. https://linktr.ee/jeanneboyarsky Fill in the blank 12 try (ExecutorService service =

    Executors._________) { service.submit(() -> doStuff()); } Examples: • newSingleThreadExecutor() • newFixedThreadPool(5) • newCachedThreadPool() • newVirtualThreadPerTaskExecutor() 21
  9. https://linktr.ee/jeanneboyarsky Autocloseable 13 Method Java 21 shutdown() No more tasks,

    but finish ones have shutdownNow() Stop tasks in progress close() Calls shutdown by default 19
  10. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #1 16 How do you create

    a virtual thread? (more than one is correct) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread() 21
  11. https://linktr.ee/jeanneboyarsky Virtual Threads Mock 17 How do you create a

    virtual thread? (pick two) A. Executors.newVirtualThread() B. Executors.newVirtualThreadExecutor() C. Executors.newVirtualThreadPerTaskExecutor() D. new VirtualThread() E. Thread.ofVirtual() F. Thread.ofVirtualThread() 21 C, E
  12. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #2 18 How can you create

    a platform thread? (more than one is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform() 21
  13. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #2 19 How can you create

    a platform thread? (more than one is correct) A. Executors.newCachedThreadPool() B. Executors.newPlatformThreadPool() C. Executors.newPlatformThreadPerTaskExecutor() D. new Thread() E. new PlatformThread() F. Thread.ofPlatform() 21 A, D, F
  14. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #3 20 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
  15. https://linktr.ee/jeanneboyarsky Virtual Threads Mock #3 21 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
  16. https://linktr.ee/jeanneboyarsky Evolution 23 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 19, 20 21 Unnamed variables and patterns 21 22
  17. @jeanneboyarsky What does this print? 14 String place = "Vegas";

    switch(place) { case "Vegas" : System.out.println("Table games!"); case "Supermarket" : System.out.println("Lotto!"); default: System.out.println("Maybe?"); } Three lines (missing break) 24
  18. @jeanneboyarsky Switch Expressions 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 25 14
  19. @jeanneboyarsky Switch Expressions String place = "Vegas"; switch(place) { case

    "Vegas" -> System.out.println("Table Games!"); case "Supermarket", "Newsstand" -> System.out.println("Lotto!"); default -> System.out.println("anywhere"); } 26 14
  20. @jeanneboyarsky Switch Expressions String place = "Vegas"; var output =

    switch(place) { case "Vegas" -> "Table Games!"; case "Supermarket", "Newsstand" -> "Lotto!"; default -> "anywhere"; }; System.out.println(output); Switch returns values 27 14 Semicolon
  21. @jeanneboyarsky Adding Pattern Matching 28 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
  22. @jeanneboyarsky Order matters 29 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!
  23. @jeanneboyarsky Enums 30 21 enum Suit { HEART, DIAMOND, CLUB,

    SPADE; } String symbol(Suit suit) { return switch (suit) { case HEART -> "♥"; case Deck.DIAMOND -> "♦"; case CLUB -> "♣"; case Deck.SPADE -> "♠"; }; } Fails compilation if miss one since no default
  24. @jeanneboyarsky Switch statements 31 21 boolean idCheck(Integer age) { boolean

    check ; switch (age) { case Integer i when i <= 40 : check = true; break; default : check = false; break; } return check; }
  25. @jeanneboyarsky Pattern variable scope 32 21 boolean idCheck(Integer age) {

    boolean check ; switch (age) { case Integer i when i <= 21 : check = true; break; // DOES NOT COMPILE case Integer i when i <= 40 : check = true; break; default : check = false; break; } return check; } Can’t use pattern variable if fall thru
  26. https://linktr.ee/jeanneboyarsky What can’t you do? 33 • In switch(x), x

    still can’t be • boolean • float • double • long • _ as pattern (coming in Java 22) 21
  27. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #1 34 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 21 C. 2 D. 3
  28. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #1 35 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 21 C. 2 D. 3 C String s & Object o or default
  29. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #2 36 What are the

    results of odds(“slots”) and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game"); }; } A. IllegalArgumentException B. NullPointerException 21 C. .05 D. Does not compile
  30. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #2 37 What are the

    results of odds(“slots”) and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game"); }; } A. IllegalArgumentException B. NullPointerException 21 C. .05 D. Does not compile A, B
  31. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #3 38 What are the

    results of odds("slots") and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game”); case null -> 0.0; }; } A. IllegalArgumentException B. NullPointerException 21 C. 0.0 D. Does not compile
  32. https://linktr.ee/jeanneboyarsky Switch Pattern Matching Mock #3 39 What are the

    results of odds("slots") and odds(null)? double odds(String str) { return switch (str) { case String s when "blackjack".equals(s) -> .05; case String s when "baccarat".equals(s) -> .12; case String s -> throw new IllegalArgumentException("unknown game”); case null -> 0.0; }; } A. IllegalArgumentException B. NullPointerException 21 C. 0.0 D. Does not compile A, C
  33. https://linktr.ee/jeanneboyarsky Record Patterns 41 enum Suit { HEART, DIAMOND, CLUB,

    SPADE; } enum Rank { NUM_1, NUM_2, NUM_3, NUM_4, NUM_5, NUM_6, NUM_7, NUM_8, NUM_9, 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
  34. https://linktr.ee/jeanneboyarsky Nested Record Patterns 42 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
  35. https://linktr.ee/jeanneboyarsky Switch pattern matching 43 switch(card) { case Card(Suit suit,

    Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21
  36. https://linktr.ee/jeanneboyarsky Switch pattern matching 44 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”
  37. https://linktr.ee/jeanneboyarsky Record Patterns Mock #1 46 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) { } 21
  38. https://linktr.ee/jeanneboyarsky Record Patterns Mock #1 47 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) { } 21 A, B, C
  39. https://linktr.ee/jeanneboyarsky Record Patterns Mock #2 48 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); } A. Ace of Hearts B. Hearts 21 C. Null Pointer D. Does not compile
  40. https://linktr.ee/jeanneboyarsky Record Patterns Mock #2 49 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); } A. Ace of Hearts B. Hearts 21 C. Null Pointer D. Does not compile D (no case Card)
  41. https://linktr.ee/jeanneboyarsky Record Patterns Mock #3 50 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); case Card c -> System.out.println("other"); } 21 A. Ace of Hearts B. Hearts C. Null Pointer D. Does not compile
  42. https://linktr.ee/jeanneboyarsky Record Patterns Mock #3 51 What is the output

    of the following? Card card = new Card(Suit.HEART, Rank.NUM_2); switch (card) { case Card(var suit, var rank) when suit == Suit.HEART && rank == Rank.ACE -> System.out.println("Ace of Hearts"); case Card(var suit, var rank) when suit == Suit.HEART -> System.out.println("Hearts"); case Card c -> System.out.println("other"); } 21 A. Ace of Hearts B. Hearts C. Null Pointer D. Does not compile B
  43. https://linktr.ee/jeanneboyarsky What does this output? 53 HashSet<String> 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
  44. https://linktr.ee/jeanneboyarsky New APIs 56 SequencedCollection SequencedCollection <E> reversed(); void addFirst(E);

    void addLast(E); E getFirst(); E getLast(); E removeFirst(); E removeLast(); SequencedSet SequencedSet<E> reversed(); SequencedMap SequencedMap<K,V> reversed(); SequencedSet<K> sequencedKeySet(); SequencedCollection<V> sequencedValues(); SequencedSet<Entry<K,V>> sequencedEntrySet(); V putFirst(K, V); V putLast(K, V); Entry<K, V> fi rstEntry(); Entry<K, V> lastEntry(); Entry<K, V> pollFirstEntry(); Entry<K, V> pollLastEntry(); 21
  45. https://linktr.ee/jeanneboyarsky Now defined! 57 SequencedSet<String> set = new LinkedHashSet<>(); set.add("Donald");

    set.add("Mickey"); set.add("Minnie"); System.out.println(set.getFirst()); Donald Note: LInkedHashSet not new 21
  46. https://linktr.ee/jeanneboyarsky Sequenced Collection Mock 58 How many of these lines

    compile? SequencedCollection<Integer> seq1 = new HashSet<>(); SequencedSet<Integer> seq2 = new HashSet<>(); SequencedMap<Integer> seq3 = new HashSet<>(); SequencedCollection<Integer> seq4 = new TreeSet<>(); SequencedSet<Integer> seq5 = new TreeSet<>(); SequencedMap<Integer> seq6 = new TreeSet<>(); A. One B. Two C. Three D. Four 21
  47. https://linktr.ee/jeanneboyarsky Sequenced Collection Mock 59 How many of these lines

    compile? SequencedCollection<Integer> seq1 = new HashSet<>(); SequencedSet<Integer> seq2 = new HashSet<>(); SequencedMap<Integer> seq3 = new HashSet<>(); SequencedCollection<Integer> seq4 = new TreeSet<>(); SequencedSet<Integer> seq5 = new TreeSet<>(); SequencedMap<Integer> seq6 = new TreeSet<>(); A. One B. Two C. Three D. Four A (seq4 and seq 5) 21
  48. https://linktr.ee/jeanneboyarsky Good to know, but not likely on exam 60

    • UTF-8 is the default character set when reading a file • StringBuilder/StringBuffer have a repeat method • String has new indexOf and splitWithDelimitters methods • Code snippets in JavaDoc • Finalization deprecated for removal