Slide 1

Slide 1 text

@JeanneBoyarsky @ScottSelikoff Wednesday, April 13, 2022 DevNexus speakerdeck.com/boyarsky Preparing for the Java cert and learning new features (part 2 - Java 12 to 17) Jeanne Boyarsky & Scott Selikoff

Slide 2

Slide 2 text

@JeanneBoyarsky @ScottSelikoff About Us 2 • Java Developer • CodeRanch Mod • JUG Leader • Java Champion • Java Developer • CodeRanch Mod • JUG Leader • Software Engineer

Slide 3

Slide 3 text

@JeanneBoyarsky @ScottSelikoff Jeanne & Scott’s Java 8/11 Cert Books 3 • OCA: Java 8 Programmer I Study Guide • OCP: Java 8 Programmer II Study Guide • OCA / OCP Java 8 Practice Tests • OCP Java 11 Programmer I Study Guide • OCP Java 11 Programmer II Study Guide • OCP Java 11 Developer Complete Study Guide • OCP Java 11 Practice Tests Win a book at the end!

Slide 4

Slide 4 text

@JeanneBoyarsky @ScottSelikoff Pre-order Java 17 Cert Books 4 May 2022 Sept 2022

Slide 5

Slide 5 text

@JeanneBoyarsky @ScottSelikoff 5 808 809 815 + 816 819 829 Associate Professional Java 8 Java 11 Java 17 Available exams Also 1Z0-811 (Foundations)

Slide 6

Slide 6 text

@JeanneBoyarsky @ScottSelikoff Agenda 6 • Text blocks • Switch Expressions & Pattern Matching • Records & Sealed classes • Also on the exam – other new features like compact number formatting and helpful null pointers

Slide 7

Slide 7 text

@JeanneBoyarsky @ScottSelikoff Text Blocks 7

Slide 8

Slide 8 text

@JeanneBoyarsky @ScottSelikoff What’s wrong? String old = "devnexus,Atlanta,"session,workshop" + "meetup,Various,lecture\n"; 8 Doesn’t compile: missing \ Missing quote on line 1 Missing line break

Slide 9

Slide 9 text

@JeanneBoyarsky @ScottSelikoff Compare String old = "devnexus,Atlanta ,\"session,workshop\"\n" + “meetup,Various,lecture\n"; String textBlock = """ devnexus,Atlanta,"session,workshop" meetup,Various,lecture """; 9 Easier to read and code!

Slide 10

Slide 10 text

@JeanneBoyarsky @ScottSelikoff Text Block Syntax String textBlock = """ devnexus,Atlanta,"session,workshop" meetup,Various,lecture """; start block 10 end block

Slide 11

Slide 11 text

@JeanneBoyarsky @ScottSelikoff Essential Whitespace String textBlock = """ Jeanne Boyarsky """; 1 1 incidental whitespace 11 essential whitespace

Slide 12

Slide 12 text

@JeanneBoyarsky @ScottSelikoff Ending lines String textBlock = """ Jeanne Boyarsky \s 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 12

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

@JeanneBoyarsky @ScottSelikoff Escaping Three Quotes String textBlock = """ better \""" but can do \"\"\" """; 14

Slide 15

Slide 15 text

@JeanneBoyarsky @ScottSelikoff Indent String option1 = " a\n b\n c\n"; String option2 = "a\nb\nc\n".indent(3); String option3 = """ a b c """.indent(3); Which do you like best? Also normalizes (bye \r) 15

Slide 16

Slide 16 text

@JeanneBoyarsky @ScottSelikoff 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 16

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

@JeanneBoyarsky @ScottSelikoff Question 2 How many lines does this print out? String sql = """ select * \ from mytable;""".stripIndent(); System.out.print(sql); A. 1 C. 3 B. 2 D. Does not compile 19

Slide 20

Slide 20 text

@JeanneBoyarsky @ScottSelikoff Question 2 How many lines does this print out? String sql = """ select * \ from mytable;""".stripIndent(); System.out.print(sql); A. 1 C. 3 B. 2 D. Does not compile 20 A

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

@JeanneBoyarsky @ScottSelikoff Question 4 How many whitespace characters are removed by strip()? String sql = """ select "name" from mytable; """; A. 1 C. 3 B. 2 D. Does not compile 23

Slide 24

Slide 24 text

@JeanneBoyarsky @ScottSelikoff Question 4 How many whitespace characters are removed by strip()? String sql = """ select "name" from mytable; """; A. 1 C. 3 B. 2 D. Does not compile 24 C

Slide 25

Slide 25 text

@JeanneBoyarsky @ScottSelikoff Question 5 How many escapes can be removed without changing the behavior? String sql = """ select \"name\" from mytable \ where value = '\"\""' """; A. 2 C. 4 B. 3 D. Does not compile 25

Slide 26

Slide 26 text

@JeanneBoyarsky @ScottSelikoff Question 5 How many escapes can be removed without changing the behavior? String sql = """ select \"name\" from mytable \ where value = '\"\""' """; A. 2 C. 4 B. 3 D. Does not compile 26 B

Slide 27

Slide 27 text

@JeanneBoyarsky @ScottSelikoff Switch Expressions and Pattern Matching 27

Slide 28

Slide 28 text

@JeanneBoyarsky @ScottSelikoff What does this print? String store = "Ponce City"; switch(store) { case "Ponce City" : System.out.println("GA"); case "Crayola" : System.out.println("PA"); default: System.out.println("anywhere"); } Three lines (missing break) 28

Slide 29

Slide 29 text

@JeanneBoyarsky @ScottSelikoff Switch Expressions String store = "Ponce City"; switch(store) { case "Ponce City" -> System.out.println("GA"); case "Crayola", "H&R" -> System.out.println("PA"); default -> System.out.println("anywhere"); } Arrow labels No break keyword Multiple values 29

Slide 30

Slide 30 text

@JeanneBoyarsky @ScottSelikoff Switch Expressions String store = "Ponce City"; String output = switch(store) { case "Ponce City" -> "GA"; case "Crayola" -> "PA"; default -> "anywhere"; }; System.out.println(output); Switch returns values 30

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

@JeanneBoyarsky @ScottSelikoff Is this legal? String store = "Legoland"; String output = switch(store) { case "NYC" -> 0; case "Legoland" -> { yield "Carlsbad"; } default -> "PA"; }; System.out.println(output); No, return types must be compatible 32

Slide 33

Slide 33 text

@JeanneBoyarsky @ScottSelikoff Yield with Switch Stmt enum Position { TOP, BOTTOM }; 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! 33

Slide 34

Slide 34 text

@JeanneBoyarsky @ScottSelikoff Missing value 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 and not all values covered 34

Slide 35

Slide 35 text

@JeanneBoyarsky @ScottSelikoff Missing values int greeting = 10; String output = switch(greeting) { case 1 -> "Welcome!"; case 10 -> "Goodbye"; }; System.out.println(output); Does not compile. Requires default branch 35

Slide 36

Slide 36 text

@JeanneBoyarsky @ScottSelikoff Pattern matching for if 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 36

Slide 37

Slide 37 text

@JeanneBoyarsky @ScottSelikoff Flow Scope 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 37

Slide 38

Slide 38 text

@JeanneBoyarsky @ScottSelikoff Does this compile? 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 38

Slide 39

Slide 39 text

@JeanneBoyarsky @ScottSelikoff Does this compile? if (num instanceof Double n) System.out.println(n.intValue()); System.out.println(n.intValue()); No. If statement is over 39

Slide 40

Slide 40 text

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

Slide 41

Slide 41 text

@JeanneBoyarsky @ScottSelikoff Does this compile? 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 41

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

@JeanneBoyarsky @ScottSelikoff Question 6 What is output? char ch = 'b'; int count = 0; switch (ch) { case 'a' -> count++; case 'b' -> count+=2; case 'c' -> count+=3; } System.out.println(count); 43 C. 5 D. Does not compile A. 1 B. 2

Slide 44

Slide 44 text

@JeanneBoyarsky @ScottSelikoff Question 6 What is output? char ch = 'b'; int count = 0; switch (ch) { case 'a' -> count++; case 'b' -> count+=2; case 'c' -> count+=3; } System.out.println(count); 44 C. 5 D. Does not compile A. 1 B. 2 B

Slide 45

Slide 45 text

@JeanneBoyarsky @ScottSelikoff Question 7 What can fill in the blank to have the code print 2? char ch = 'b'; ______ value = switch (ch) { case 'a' -> 1; case 'b' -> 2L; case 'c' -> 3.0; default -> 4; }; System.out.println(value); 45 C. Either A or B D. None of the above A. int B. Object

Slide 46

Slide 46 text

@JeanneBoyarsky @ScottSelikoff Question 7 What can fill in the blank to have the code print 2? char ch = 'b'; ______ value = switch (ch) { case 'a' -> 1; case 'b' -> 2L; case 'c' -> 3.0; default -> 4; }; System.out.println(value); 46 C. Either A or B D. None of the above A. int B. Object B

Slide 47

Slide 47 text

@JeanneBoyarsky @ScottSelikoff Question 8 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); 47 C. y694 D. Does not compile A. x694 B. xy694

Slide 48

Slide 48 text

@JeanneBoyarsky @ScottSelikoff Question 8 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); 48 C. y694 D. Does not compile A. x694 B. xy694 A

Slide 49

Slide 49 text

@JeanneBoyarsky @ScottSelikoff Question 9 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 49 C. 1, 2 and 3 D. Does not compile A. 1 B. 1 and 3

Slide 50

Slide 50 text

@JeanneBoyarsky @ScottSelikoff Question 9 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 50 C. 1, 2 and 3 D. Does not compile A. 1 B. 1 and 3 D

Slide 51

Slide 51 text

@JeanneBoyarsky @ScottSelikoff Question 10 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 51 C. equals() does not compile A. equals() is correct B. equals() is incorrect

Slide 52

Slide 52 text

@JeanneBoyarsky @ScottSelikoff Question 10 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 52 C. equals() does not compile A. equals() is correct B. equals() is incorrect A

Slide 53

Slide 53 text

@JeanneBoyarsky @ScottSelikoff Records and Sealed Classes 53

Slide 54

Slide 54 text

@JeanneBoyarsky @ScottSelikoff 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 54

Slide 55

Slide 55 text

@JeanneBoyarsky @ScottSelikoff POJO • constructor • toString() • hashCode() - more rules • equals() - still more rules 55

Slide 56

Slide 56 text

@JeanneBoyarsky @ScottSelikoff Simple Record public record Book (String title, int numPages) { } New type Automatically get * final record * private final instance variables * public accessors/getters * constructor taking both fields * equals(), hashCode() and toString() 56

Slide 57

Slide 57 text

@JeanneBoyarsky @ScottSelikoff Using the Record 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] 57

Slide 58

Slide 58 text

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

Slide 59

Slide 59 text

@JeanneBoyarsky @ScottSelikoff Immutability public record Book (String title, int numPages, List chapters) { } Book book = new Book("Breaking and entering", 289, chapters); chapters.add("2"); book.chapters().add("3"); System.out.println(book.chapters()); Prints [1,2,3] because shallow immutability 59

Slide 60

Slide 60 text

@JeanneBoyarsky @ScottSelikoff Now immutable public record Book (String title, int numPages, List chapters) { public Book { chapters = List.copyOf(chapters); } } Must match record access modifier Compact constructor 60 Make immutable copy

Slide 61

Slide 61 text

@JeanneBoyarsky @ScottSelikoff Sealed classes 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 61

Slide 62

Slide 62 text

@JeanneBoyarsky @ScottSelikoff Subclass modifiers 62 Modifier Meaning final Hierarchy ends here non-sealed Others can subclass sealed Another layer

Slide 63

Slide 63 text

@JeanneBoyarsky @ScottSelikoff Sealed interface public sealed interface TimeOfDay permits Morning, Hour, Evening { boolean early(); } public non-sealed class Morning implements TimeOfDay { public boolean early() { return true; } } public non-sealed interface Hour extends TimeOfDay {} public record Evening(int hour) implements TimeOfDay { public boolean early() { return false; } } Records are implicitly final 63

Slide 64

Slide 64 text

@JeanneBoyarsky @ScottSelikoff Does this compile? public abstract sealed class Seasons { } final class Fall extends Seasons {} final class Spring extends Seasons {} final class Summer extends Seasons {} final class Winter extends Seasons {} 64 Yes, but only when they are in the same file.

Slide 65

Slide 65 text

@JeanneBoyarsky @ScottSelikoff Question 11 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)); } 65 C. 2 D. None of the above A. 0 B. 1

Slide 66

Slide 66 text

@JeanneBoyarsky @ScottSelikoff Question 11 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)); } 66 C. 2 D. None of the above A. 0 B. 1 C

Slide 67

Slide 67 text

@JeanneBoyarsky @ScottSelikoff Question 12 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()); } 67 C. Does not compile D. None of the above A. chicken B. CHICKEN

Slide 68

Slide 68 text

@JeanneBoyarsky @ScottSelikoff Question 12 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()); } 68 C. Does not compile D. None of the above A. chicken B. CHICKEN C

Slide 69

Slide 69 text

@JeanneBoyarsky @ScottSelikoff Question 13 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 ""; } } 69 C. 3 D. 4 A. 1 B. 2

Slide 70

Slide 70 text

@JeanneBoyarsky @ScottSelikoff Question 13 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 ""; } } 70 C. 3 D. 4 A. 1 B. 2 C

Slide 71

Slide 71 text

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

Slide 72

Slide 72 text

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

Slide 73

Slide 73 text

@JeanneBoyarsky @ScottSelikoff Question 15 How many compiler errors are in this code? public sealed class Phone { class IPhone extends Phone { } class Android extends Phone { } } 73 C. 2 D. 3 A. 0 B. 1

Slide 74

Slide 74 text

@JeanneBoyarsky @ScottSelikoff Question 15 How many compiler errors are in this code? public sealed class Phone { class IPhone extends Phone { } class Android extends Phone { } } 74 C. 2 D. 3 A. 0 B. 1 C

Slide 75

Slide 75 text

@JeanneBoyarsky @ScottSelikoff 75 Book Giveaway

Slide 76

Slide 76 text

@JeanneBoyarsky @ScottSelikoff Question 16 Which is true about this text block? String sql = """select * from mytable \ where weather = 'snow'; """; A. Has incidental whitespace C. Both A and B B. Has essential whitespace D. Doesn’t compile 76

Slide 77

Slide 77 text

@JeanneBoyarsky @ScottSelikoff Question 16 Which is true about this text block? String sql = """select * from mytable \ where weather = 'snow'; """; A. Has incidental whitespace C. Both A and B B. Has essential whitespace D. Doesn’t compile 77 D

Slide 78

Slide 78 text

@JeanneBoyarsky @ScottSelikoff Question 17 How many changes are needed to have this code print 2? char ch = 'b'; int value = switch (ch) { case 'a' -> 1; case 'b' -> yield 2; case 'c' -> 3; } System.out.println(value); 78 C. 3 D. 4 A. 1 B. 2

Slide 79

Slide 79 text

@JeanneBoyarsky @ScottSelikoff Question 17 How many changes are needed to have this code print 2? char ch = 'b'; int value = switch (ch) { case 'a' -> 1; case 'b' -> yield 2; case 'c' -> 3; } System.out.println(value); 79 C. 3 D. 4 A. 1 B. 2 C

Slide 80

Slide 80 text

@JeanneBoyarsky @ScottSelikoff Question 18 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); } } 80 C. 8 D. Does not compile A. 2 B. 3

Slide 81

Slide 81 text

@JeanneBoyarsky @ScottSelikoff Question 18 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); } } 81 C. 8 D. Does not compile A. 2 B. 3 C

Slide 82

Slide 82 text

@JeanneBoyarsky @ScottSelikoff Question 19 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()); } 82 C. Does not compile D. None of the above A. chicken B. CHICKEN

Slide 83

Slide 83 text

@JeanneBoyarsky @ScottSelikoff Question 19 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()); } 83 C. Does not compile D. None of the above A. chicken B. CHICKEN B