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

Java 21 Certification (or learning new features)

Java 21 Certification (or learning new features)

Avatar for Jeanne Boyarsky

Jeanne Boyarsky

August 13, 2025
Tweet

More Decks by Jeanne Boyarsky

Other Decks in Technology

Transcript

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

    New Features Jeanne Boyarsky 8/13/25 KCDC speakerdeck.com/boyarsky
  2. https://linktr.ee/jeanneboyarsky Disclaimers 5 I do not work for Oracle. I’m

    still not authorized to tell you any non public information of if I know any :) Some of the material in this presentation appears in our certification books.
  3. https://linktr.ee/jeanneboyarsky Agenda 7 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 + miscellaneous topics
  4. https://linktr.ee/jeanneboyarsky Module Flow •Review lab from previous module •Lecture/review •Hands

    on exercises •10 minute break This means if a colleague needs to call you, the last 15-20 minutes of each hour is best. 8
  5. https://linktr.ee/jeanneboyarsky Required Software for Lab Option 1 •Java 21+ -

    https://jdk.java.net/24/ •IDE of your choice or… 9
  6. https://linktr.ee/jeanneboyarsky If new to the cert 11 808 809 815

    + 816 819 829 Associate Professional Java 8 Java 11 Java 17 Java 21 830 Foundations 811
  7. @jeanneboyarsky What’s wrong? String old = "kcdc,Kansas City,"session,workshop" + "meetup,Various,lecture\n";

    13 Doesn’t compile: missing \ Missing quote on line 1 Missing line break 15
  8. @jeanneboyarsky Compare String old = "kcdc,Kansas City,\"session,workshop\"\n" + “meetup,Various,lecture\n"; String

    textBlock = """ kcdc,Kansas City,"session,workshop" meetup,Various,lecture """; 14 Easier to read and code! 15
  9. @jeanneboyarsky Text Block Syntax String textBlock = """ kcdc,Kansas City,"session,workshop"

    meetup,Various,lecture """; incidental whitespace start block end block 15 15
  10. @jeanneboyarsky Essential Whitespace String textBlock = """ <session> <speaker> Jeanne

    Boyarsky </speaker> </session> """; incidental whitespace essential whitespace 15 16
  11. @jeanneboyarsky Ending lines String textBlock = """ <session> <speaker> Jeanne

    Boyarsky \s </speaker> <title> Becoming one of the first Java 17 \ certified programmers \ (and learning new features) continue on next line without a line break new escape character keeps trailing whitespace tab 15 17
  12. @jeanneboyarsky New lines String textBlock = """ <session>\n <speaker> Jeanne\nBoyarsky

    </speaker> </session>"""; no line break at end Two new lines (explicit and implicit) One new line (explicit) 15 18
  13. @jeanneboyarsky Indent String option1 = " a\n b\n c\n"; String

    option2 = "a\nb\nc\n".indent(3); String option3 = """ a b c """.indent(3); String option4 = """ a Which do you like best? Also normalizes (bye \r) 12 20
  14. @jeanneboyarsky Transform String option1 = “chiefs".transform( s -> s.toUpperCase()); String

    option2 = """ chiefs """.transform(s -> s.toUpperCase()); Which do you like best? 12 21
  15. @jeanneboyarsky Strip Indent Method From beginning From end Per line

    strip() Leading Trailing No stripIndent() Incidental Incidental Yes stripLeading() Leading n/a No stripTrailing() n/a Trailing No 15 22
  16. @jeanneboyarsky More Index Of Overloads 21 23 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
  17. https://linktr.ee/jeanneboyarsky What does this output? 25 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
  18. https://linktr.ee/jeanneboyarsky New APIs 27 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
  19. https://linktr.ee/jeanneboyarsky Now defined! 28 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
  20. @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 29
  21. @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 30 A
  22. @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 31
  23. @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 32 D (missing opening line break)
  24. @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 33
  25. @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 34 B
  26. @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 35
  27. @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 36 D (one line)
  28. @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 37
  29. @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 38 C
  30. @jeanneboyarsky Module 1 - Question 6 How many lines does

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

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

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

    this print out? String sql = """ select * \s from mytable; ".stripIndent(); System.out.print(sql); A. 1 B. 2 C. 3 D. Does not compile 42 D (missing 2 closing quotes)
  34. @jeanneboyarsky Module 1 - Question 8 How many whitespace characters

    are removed by strip()? String sql = """ select "name" from mytable; """; A. 1 B. 2 C. 3 D. Does not compile 43
  35. @jeanneboyarsky Module 1 - Question 8 How many whitespace characters

    are removed by strip()? String sql = """ select "name" from mytable; """; A. 1 B. 2 C. 3 D. Does not compile 44 C (2 leading whitespace + trailing new line)
  36. @jeanneboyarsky Module 1 - Question 9 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 45
  37. @jeanneboyarsky Module 1 - Question 9 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 46 B (around name and second on value)
  38. https://linktr.ee/jeanneboyarsky Module 1 - Question 10 47 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
  39. https://linktr.ee/jeanneboyarsky Module 1 - Question 10 48 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 B (seq4 and seq 5)
  40. https://linktr.ee/jeanneboyarsky Agenda 51 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 + miscellaneous topics
  41. @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 54
  42. @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 55 16
  43. @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 * toString 57
  44. @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] 58
  45. @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 59
  46. @jeanneboyarsky Not really immutable 16 public record Book (String title,

    int numPages, List<String> 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 60
  47. @jeanneboyarsky Now immutable 16 public record Book (String title, int

    numPages, List<String> chapters) { public Book { chapters = List.copyOf(chapters); } } Must match record access modifier Compact constructor 61
  48. @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 62
  49. @jeanneboyarsky Subclass modifiers 63 17 Modifer Meaning final Hierarchy ends

    here non-sealed Others can subclass sealed Another layer
  50. @jeanneboyarsky Subclass reference 64 17 Location How reference in permits

    clause same file Package name optional Permits clause optional same package in named/ unnamed module Package name optional different package in named module Package name required different package in unnamed module Not allowed
  51. @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 65
  52. @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 } 66
  53. @jeanneboyarsky Brainstorm 67 When would you use sealed classes? •

    Limited set of options • Good in library code • Security roles • Expanded enum
  54. @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)); } 68 C. 2 D. None of the above A. 0 B. 1
  55. @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)); } 69 C. 2 D. None of the above A. 0 B. 1 C (no setters and getter should be type())
  56. @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()); } 70 C. Does not compile D. None of the above A. chicken B. CHICKEN
  57. @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()); } 71 C. Does not compile D. None of the above A. chicken B. CHICKEN C (compact constructor needs to be public because record is)
  58. @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()); } 72 C. Does not compile D. None of the above A. chicken B. CHICKEN
  59. @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()); } 73 C. Does not compile D. None of the above A. chicken B. CHICKEN B
  60. @jeanneboyarsky Module 2 - Question 4 How many compiler errors

    are in the following code? public final record BBQ(String type) { { type = ""; } public BBQ(String type) { type = type.toUpperCase(); } public void type() { return ""; } public String toString() { return ""; } } 74 C. 3 D. 4 A. 1 B. 2
  61. @jeanneboyarsky Module 2 - Question 4 How many compiler errors

    are in the following code? public final record BBQ(String type) { { type = ""; } public BBQ(String type) { type = type.toUpperCase(); } public void type() { return ""; } public String toString() { return ""; } } 75 C. 3 D. 4 A. 1 B. 2 C (can’t have instance initializer, compact constructor syntax, type() return type)
  62. @jeanneboyarsky Module 2 - Question 5 What does this output?

    public record BBQ(String type) implements Comparable<BBQ> { 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)); } 76 C. 0 D. Does not compile A. Negative # B. Positive #
  63. @jeanneboyarsky Module 2 - Question 5 What does this output?

    public record BBQ(String type) implements Comparable<BBQ> { 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)); } 77 C. 0 D. Does not compile A. Negative # B. Positive # B
  64. @jeanneboyarsky Module 2 - Question 6 What does this output?

    static sealed interface Weather permits Wet, Dry{ boolean needUmbrella(); } static non-sealed class Wet implements Weather { public boolean needUmbrella() { return true; } } static record Dry(boolean needUmbrella) implements Weather {} public static void main(String[] args) { Weather weather = new Dry(false); System.out.println(weather.needUmbrella()); } 78 C. Does not compile D. None of the above A. true B. false
  65. @jeanneboyarsky Module 2 - Question 6 What does this output?

    static sealed interface Weather permits Wet, Dry{ boolean needUmbrella(); } static non-sealed class Wet implements Weather { public boolean needUmbrella() { return true; } } static record Dry(boolean needUmbrella) implements Weather {} public static void main(String[] args) { Weather weather = new Dry(false); System.out.println(weather.needUmbrella()); } 79 C. Does not compile D. None of the above A. true B. false B
  66. @jeanneboyarsky Module 2 - Question 7 Which of the following

    are true? (Choose all that apply) A. There is only one hyphenated modifier in Java (non-sealed) B. A sealed interface may permit another interface. C. Sealed records are allowed D. Sealed enums are allowed 80
  67. @jeanneboyarsky Module 2 - Question 7 Which of the following

    are true? (Choose all that apply) A. There is only one hyphenated modifier in Java (non-sealed) B. A sealed interface may permit another interface. C. Sealed records are allowed D. Sealed enums are allowed 81 A, B
  68. @jeanneboyarsky Module 2 - Question 8 Given the following, where

    could Android be? (Choose all that apply) package general; static sealed class Phone permits IPhone, Android { } A. In the same file as Phone B. In the same package as Phone within a module C. In a different package from Phone, but in the same module D. In a different module 82
  69. @jeanneboyarsky Module 2 - Question 8 Given the following, where

    could Android be? (Choose all that apply) package general; static sealed class Phone permits IPhone, Android { } A. In the same file as Phone B. In the same package as Phone within a module C. In a different package from Phone, but in the same module D. In a different module 83 A, B
  70. @jeanneboyarsky Module 2 - Question 9 Given the following, where

    could Android be? (Choose all that apply) package general; static sealed class Phone permits mac.IPhone, google.Android { } A. In the same file as Phone B. In the same package as Phone within a module C. In a different package from Phone, but in the same module D. In a different module 84
  71. @jeanneboyarsky Module 2 - Question 9 Given the following, where

    could Android be? (Choose all that apply) package general; static sealed class Phone permits mac.IPhone, google.Android { } A. In the same file as Phone B. In the same package as Phone within a module C. In a different package from Phone, but in the same module D. In a different module 85 C, D
  72. @jeanneboyarsky Module 2 - Question 10 How many compiler errors

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

    are in this code? public sealed class Phone { class IPhone extends Phone { } class Android extends Phone { } } 87 C. 2 D. 3 A. 0 B. 1 C (extending classes needed to be sealed or final)
  74. https://linktr.ee/jeanneboyarsky Agenda 90 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 + miscellaneous topics
  75. https://linktr.ee/jeanneboyarsky Features 92 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
  76. @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 93
  77. @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 94
  78. @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 95
  79. @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 96
  80. @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 97
  81. @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 98
  82. @jeanneboyarsky Reusing a variable 16 if (num instanceof Integer numAsInt)

    { numAsInt = 6; System.out.println(numAsInt); } Legal. please don’t. 99
  83. @jeanneboyarsky Behavior change 21 Integer num = 123; if (num

    instanceof Integer num) { } Compiles in Java 21, but not 17 100
  84. @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) 101
  85. @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 102
  86. @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 103
  87. @jeanneboyarsky Using Pattern Matching 104 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
  88. @jeanneboyarsky Order matters 105 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!
  89. @jeanneboyarsky Enums 106 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
  90. @jeanneboyarsky Even Here 107 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
  91. @jeanneboyarsky Pattern variable scope 108 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
  92. @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 109
  93. @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 110
  94. @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 111
  95. @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! 112
  96. @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) 113
  97. https://linktr.ee/jeanneboyarsky Record Patterns 114 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
  98. https://linktr.ee/jeanneboyarsky Nested Record Patterns 115 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
  99. https://linktr.ee/jeanneboyarsky Switch pattern matching 116 switch(card) { case Card(Suit suit,

    Rank rank) when suit == Suit.HEART -> System.out.println("Heart"); case Card c -> System.out.println("other"); } 21
  100. https://linktr.ee/jeanneboyarsky Switch pattern matching 117 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”
  101. https://linktr.ee/jeanneboyarsky What can’t you do? 118 • In switch(x), x

    still can’t be • boolean • float • double • long • _ as pattern (coming in Java 22) • Expanding non-records (coming ?) 21
  102. https://linktr.ee/jeanneboyarsky Module 3 - Question 1 119 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
  103. https://linktr.ee/jeanneboyarsky Module 3 - Question 1 120 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
  104. https://linktr.ee/jeanneboyarsky Module 3 - Question 2 121 What are the

    results of odds(“slots”) and odds(null) run separately? 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 C. .05 D. Does not compile
  105. https://linktr.ee/jeanneboyarsky Module 3 - Question 2 122 What are the

    results of odds(“slots”) and odds(null) run separately? 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 C. .05 D. Does not compile A, B
  106. @jeanneboyarsky Module 3 - Question 3 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); 123 C. y694 D. Does not compile A. x694 B. xy694
  107. @jeanneboyarsky Module 3 - Question 3 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); 124 C. y694 D. Does not compile A. x694 B. xy694 A
  108. @jeanneboyarsky Module 3 - Question 4 Which lines have s

    in scope? Object robot = "694"; if (robot instanceof String s) { // line 1 } if (robot instanceof int i) { // line 2 } // line 3 125 C. 1, 2 and 3 D. Does not compile A. 1 B. 1 and 3
  109. @jeanneboyarsky Module 3 - Question 4 Which lines have s

    in scope? Object robot = "694"; if (robot instanceof String s) { // line 1 } if (robot instanceof int i) { // line 2 } // line 3 126 C. 1, 2 and 3 D. Does not compile A. 1 B. 1 and 3 D (int needs to be Integer)
  110. @jeanneboyarsky Module 3 - Question 5 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 } 127 C. equals() does not compile A. equals() is correct B. equals() is incorrect
  111. @jeanneboyarsky Module 3 - Question 5 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 } 128 C. equals() does not compile A. equals() is correct B. equals() is incorrect A
  112. @jeanneboyarsky Module 3 - Question 6 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()) {} 129 C. 2 D. 3 A. 0 B. 1
  113. @jeanneboyarsky Module 3 - Question 6 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()) {} 130 C. 2 D. 3 A. 0 B. 1 C (last 2 could be null)
  114. @jeanneboyarsky Module 3 - Question 7 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); } } 131 C. 8 D. Does not compile A. 2 B. 3
  115. @jeanneboyarsky Module 3 - Question 7 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); } } 132 C. 8 D. Does not compile A. 2 B. 3 C
  116. https://linktr.ee/jeanneboyarsky Module 3 - Question 8 133 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) { }
  117. https://linktr.ee/jeanneboyarsky Module 3 - Question 8 134 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
  118. https://linktr.ee/jeanneboyarsky Module 3 - Question 9 135 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 C. Null Pointer D. Does not compile
  119. https://linktr.ee/jeanneboyarsky Module 3 - Question 9 136 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 C. Null Pointer D. Does not compile D (no case Card)
  120. https://linktr.ee/jeanneboyarsky Module 3 - Question 10 137 Given record Card

    (Suit suit, Rank rank), how many of these compile? case Card(var rank, var suit) when suit == Suit.HEART case Card(Rank rank, Suit suit) when suit == Suit.HEART case Card(Rank rank, var suit) when suit == Suit.HEART case Card(var suit, var rank) when suit == Suit.HEART case Card(Suit suit, Rank rank) when suit == Suit.HEART case Card(var suit, Rank rank) when suit == Suit.HEART A. 0 B. 1 C. 2 D. 3 E. 4 F. 5
  121. https://linktr.ee/jeanneboyarsky Module 3 - Question 10 138 Given record Card

    (Suit suit, Rank rank), how many of these compile? case Card(var rank, var suit) when suit == Suit.HEART case Card(Rank rank, Suit suit) when suit == Suit.HEART case Card(Rank rank, var suit) when suit == Suit.HEART case Card(var suit, var rank) when suit == Suit.HEART case Card(Suit suit, Rank rank) when suit == Suit.HEART case Card(var suit, Rank rank) when suit == Suit.HEART A. 0 B. 1 C. 2 D. 3 E. 4 F. 5 D (last three)
  122. https://linktr.ee/jeanneboyarsky Agenda 140 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 + miscellaneous topics
  123. https://linktr.ee/jeanneboyarsky Why we need threads 144 Program Do calculation and

    call REST API Do calculation and call REST API CPU Network I’m bored… I’m waiting for a reply
  124. https://linktr.ee/jeanneboyarsky Why we need virtual threads 145 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
  125. https://linktr.ee/jeanneboyarsky Virtual Thread 1 With virtual threads 146 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 21
  126. https://linktr.ee/jeanneboyarsky Comparing 148 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
  127. https://linktr.ee/jeanneboyarsky Fill in the blank 149 try (ExecutorService service =

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

    but finish ones have shutdownNow() Stop tasks in progress close() Calls shutdown by default 19
  129. https://linktr.ee/jeanneboyarsky Teeing 153 12 record Separations(String spaceSeparated, String commaSeparated) {}

    var list = List.of("x", "y", "z"); Separations result = list.stream() .collect(Collectors.teeing( Collectors.joining(" "), Collectors.joining(","), (s, c) -> new Separations(s, c))); System.out.println(result);
  130. @jeanneboyarsky Formatting a String String firstName = "Jeanne"; String lastName

    = "Boyarsky"; String str = String.format( "Hi %s %s!", firstName, lastName); System.out.println(str); System.out.println("Hi %s %s!".formatted( firstName, lastName)); Outputs: Hi Jeanne Boyarsky! Hi Jeanne Boyarsky! 12 154
  131. @jeanneboyarsky Compact Number NumberFormat defaultFormat = NumberFormat.getCompactNumberInstance(); NumberFormat shortFormat =

    NumberFormat .getCompactNumberInstance( Locale.US, NumberFormat.Style.SHORT); NumberFormat longFormat = NumberFormat .getCompactNumberInstance( Locale.US, NumberFormat.Style.LONG); System.out.println(defaultFormat.format(1_000_000)); System.out.println(shortFormat.format(1_000_000)); System.out.println(longFormat.format(1_000_000)); 1M 1M 1 million 12 155
  132. @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"); 156 19
  133. @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 157
  134. @jeanneboyarsky Side note - NullPointer Path path = null; //

    lots of code here System.out.println(path.toAbsolutePath()); % java11 HelpfulNullPointer.java Exception in thread "main" java.lang.NullPointerException at HelpfulNullPointer.main(HelpfulNullPointer.java:9) % java17 HelpfulNullPointer.java Exception in thread "main" java.lang.NullPointerException: Cannot invoke “java.nio.file.Path.toAbsolutePath()" because “path" is null at HelpfulNullPointer.main(HelpfulNullPointer.java:9) 14 158
  135. @jeanneboyarsky Using var (Local Variable Type Inference) 159 String name1

    = "Jeanne"; var name2 = "Jeanne"; List list1 = List.of(1, 2, 3); var list2 = List.of(1, 2, 3); Syntactic sugar/less boilerplate 10
  136. @jeanneboyarsky Readablity 162 List<WebElement> headers = thead.findElements(By.tagName("th")); VolunteerDashboardRow headerRow =

    new VolunteerDashboardRow(headers); vs var headers = thead.findElements(By.tagName("th")); var headerRow = new VolunteerDashboardRow(headers); 10
  137. @jeanneboyarsky What types are these? 163 var csvPath = createAndGetFile(CSV_DATA);

    try (var csvWriter = Files.newBufferedWriter(csvPath); var csvPrinter = new CSVPrinter( csvWriter, CSVFormat.DEFAULT)) { } 10
  138. @jeanneboyarsky Evolution 164 Map<Integer, String> productMap1 = new HashMap<Integer, String>();

    Map<Integer, String> productMap2 = new HashMap<>(); var productMap3 = new HashMap<Integer, String>(); 10
  139. @jeanneboyarsky Where can we use? 165 var name = "Jeanne";

    var other = name + 2; var list = List.of(1, 2, 3); for (var num : list) {} 10
  140. @jeanneboyarsky Where can’t we use? 166 var instance = 1;

    class Inner { var bad = "abc"; } public static void main(String[] args) { var noGood; noGood = 4; } What’s wrong? 10
  141. @jeanneboyarsky Tradeoffs 168 https://openjdk.org/projects/amber/guides/lvti-style-guide Pros Cons Less typing Loss of

    information Less redundancy Variable names matter more Can scan variable names Be careful 10
  142. @jeanneboyarsky Lambdas 169 Predicate<String> pred1 = p -> true; Predicate<String>

    pred2 = (String p) -> true; Predicate<String> pred3 = (var p) -> true; 11
  143. @jeanneboyarsky All or nothing 171 // good BiPredicate<Map<Integer, String>, Boolean>

    bi1 = (var map, var list) -> true; // bad BiPredicate<Map<Integer, String>, Boolean> bi2 = (var map, list) -> true; BiPredicate<Map<Integer, String>, Boolean> bi3 = (var map, List list) -> true; 11
  144. https://linktr.ee/jeanneboyarsky Module 4 - Question 1 172 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()
  145. https://linktr.ee/jeanneboyarsky Module 4 - Question 1 173 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
  146. https://linktr.ee/jeanneboyarsky Module 4 - Question 2 174 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()
  147. https://linktr.ee/jeanneboyarsky Module 4 - Question 2 175 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
  148. https://linktr.ee/jeanneboyarsky Module 4 - Question 3 176 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
  149. https://linktr.ee/jeanneboyarsky Module 4 - Question 3 177 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
  150. @jeanneboyarsky Module 4 - Question 4 What does this output?

    List.of(1,2,3).stream() .collect(Collectors.teeing( Collectors.toSet(), System::forEach)); A. 1,2,3 B. {1,2,3} C. Both A and B D. Does not compile E. None of the above 178
  151. @jeanneboyarsky Module 4 - Question 4 What does this output?

    List.of(1,2,3).stream() .collect(Collectors.teeing( Collectors.toSet(), System::forEach)); A. 1,2,3 B. {1,2,3} C. Both A and B D. Does not compile E. None of the above 179 D (teeing takes 2 collectors and a combiner)
  152. @jeanneboyarsky Module 4 - Question 5 What does this output?

    System.out.println("%s %d".formatted( "KCDC", "2021")); A. KCDC2021 B. KCDC2021.0 C. KCDC 2021 D. KCDC 2021.0 E. None of the above 180
  153. @jeanneboyarsky Module 4 - Question 5 What does this output?

    System.out.println("%s %d".formatted( "KCDC", "2021")); A. KCDC2021 B. KCDC2021.0 C. KCDC 2021 D. KCDC 2021.0 E. None of the above 181 E (exception because 2021 is a string)
  154. @jeanneboyarsky Module 4 - Question 6 How many of these

    are valid locales? Locale a = new Locale("en"); Locale b = new Locale("US"); Locale c = Locale.of("en"); Locale d = Locale.of("US"); A. 0 B. 1 C. 2 D. 3 E. 4 182
  155. @jeanneboyarsky Module 4 - Question 6 How many of these

    are valid locales? Locale a = new Locale("en"); Locale b = new Locale("US"); Locale c = Locale.of("US"); Locale d = Locale.of("US"); A. 0 B. 1 C. 2 D. 3 E. 4 183 C (first and third “US” needs language)
  156. @jeanneboyarsky Module 4 - Question 7 Which variables do not

    compile? (Choose all) var a = null; var b = 1; var c; var var = 3; A. a B. b C. c D. All compile 184
  157. @jeanneboyarsky Module 4 - Question 7 Which variables do not

    compile? (Choose all) var a = null; var b = 1; var c; var var = 3; A. a B. b C. c D. All compile 185 A, C a=null and c (no value)
  158. @jeanneboyarsky Module 4 - Question 8 Which do not compile?

    (Choose all) A. var a; a = 1; B. static var b = 1; C. int x=1, var y=1; D. var VAR = 1; E. All compile 186
  159. @jeanneboyarsky Module 4 - Question 8 Which do not compile?

    (Choose all) A. var a; a = 1; B. static var b = 1; C. int x=1, var y=1; D. var VAR = 1; E. All compile 187 A, B, C, A (no value), B (static), C
  160. @jeanneboyarsky Fun (not on exam) •Java 11 - Unicode 11

    •Java 17 - Unicode 17 public class Fun { public static void main(String[] args) { System.out.println(""" Wear \uD83E\uDD7D \ and \uD83E\uDD7C \ when using a \uD83E\uDDEA"""); } } 189 java17 Fun.java Wear 🥽 and 🥼 when using a 🧪
  161. https://linktr.ee/jeanneboyarsky Good to know, but not on exam 190 •

    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
  162. https://linktr.ee/jeanneboyarsky Good to know, but not on exam 191 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"