Share
Embed
Transcript
119 slides
-
https://linktr.ee/jeanneboyarsky 1 Preparing for the Java 21 cert + Learning
New Features Jeanne Boyarsky 3/18/25 JavaOne speakerdeck.com/boyarsky -
https://linktr.ee/jeanneboyarsky Disclaimers 4 Some of the material in this presentation
appears in our certification books. -
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 -
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 -
https://linktr.ee/jeanneboyarsky Features 7 Feature Preview Final Text Blocks 13, 14
15 Sequenced Collections 21 String APIs Misc -
@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 -
@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 -
@jeanneboyarsky Text Block Syntax String textBlock = """ javaone,Java One,"session"
meetup,Various,lecture """; incidental whitespace start block end block 15 10 -
@jeanneboyarsky Essential Whitespace String textBlock = """ <session> <speaker> Jeanne
Boyarsky </speaker> </session> """; incidental whitespace essential whitespace 15 11 -
@jeanneboyarsky Ending lines String textBlock = """ <session> <speaker> Jeanne
Boyarsky \s </speaker> <title> Becoming one of the first Java 21 \ certified programmers \ (and learning new features) </title> </session> """; continue on next line without a line break new escape character keeps trailing whitespace tab 15 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 13 -
@jeanneboyarsky Escaping Three Quotes String textBlock = """ better \"""
but can do \"\"\" """; 15 14 -
@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 -
https://linktr.ee/jeanneboyarsky Java 17 16 ArrayList, LinkedList, Deque, TreeSet, TreeMap became
sequenced collections LinkedHashSet and LinkedHashMap too -
https://linktr.ee/jeanneboyarsky What does this output? 17 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 -
https://linktr.ee/jeanneboyarsky New APIs 19 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 -
https://linktr.ee/jeanneboyarsky Now defined! 20 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 -
@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 -
@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 -
@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 -
@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) -
@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 -
@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 -
@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 -
@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) -
@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 -
@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 -
@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 -
@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) -
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 -
https://linktr.ee/jeanneboyarsky Features 34 Feature Preview Final Records 14, 15 16
Sealed Classes 15, 16 17 -
@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 -
@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 -
@jeanneboyarsky POJO • constructor • toString() • hashCode() - more
rules • equals() - still more rules 37 16 -
@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 -
@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 -
@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 -
@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 41 -
@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 42 -
@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 -
@jeanneboyarsky Subclass modifiers 44 17 Modifer Meaning final Hierarchy ends
here non-sealed Others can subclass sealed Another layer -
@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 -
@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 -
@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 -
@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()) -
@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 -
@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) -
@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 -
@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 -
@jeanneboyarsky Module 2 - Question 4 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)); } 53 C. 0 D. Does not compile A. Negative # B. Positive # -
@jeanneboyarsky Module 2 - Question 4 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)); } 54 C. 0 D. Does not compile A. Negative # B. Positive # B -
@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 -
@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) -
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 -
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 -
@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 -
@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 -
@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 -
@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 -
@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 -
@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 -
@jeanneboyarsky Reusing a variable 16 if (num instanceof Integer numAsInt)
{ numAsInt = 6; System.out.println(numAsInt); } Legal. please don’t. 65 -
@jeanneboyarsky Behavior change 21 Integer num = 123; if (num
instanceof Integer num) { } Compiles in Java 21, but not 17 66 -
@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 -
@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 -
@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 -
@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 -
@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! -
@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 -
@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 -
@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 -
@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 -
@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 -
@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 -
@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 -
@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 -
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 -
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 -
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 -
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” -
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 -
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 -
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 -
@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 -
@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 -
@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 -
@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 -
@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 -
@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) -
@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 -
@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 -
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) { } -
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 -
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 -
https://linktr.ee/jeanneboyarsky Leaps in Concurrency 99 Threads + Executors + Virtual
Threads Plus many APIs… 21 -
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 -
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 -
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 -
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 -
https://linktr.ee/jeanneboyarsky Fill in the blank 105 try (ExecutorService service =
Executors._________) { service.submit(() -> doStuff()); } Examples: • newSingleThreadExecutor() • newFixedThreadPool(5) • newCachedThreadPool() • newVirtualThreadPerTaskExecutor() 21 -
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 -
https://linktr.ee/jeanneboyarsky If need directly 107 Platform Thread Virtual Thread Thread.ofPlatform()
Thread.ofVirtual() new Thread(…) Not via constructor 21 -
@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 -
@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 -
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() -
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 -
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() -
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 -
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 -
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 -
@jeanneboyarsky Module 4 - Question 4 I learned a lot
today A. True B. False 117 -
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 -
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"