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

Become one of the first Java 17 developers in the world

Become one of the first Java 17 developers in the world

The key to being certified early is to learn the material before the objectives are even announced. Here's a guide to the new topics based on my guesses of what will be on an exam

Jeanne Boyarsky

September 15, 2021
Tweet

More Decks by Jeanne Boyarsky

Other Decks in Programming

Transcript

  1. @jeanneboyarsky 1
    Becoming one of the first Java 17
    certified programmers


    (and learning new features)
    Jeanne Boyarsky


    Sept 15, 2021


    KCDC


    speakerdeck.com/boyarsky


    View Slide

  2. @jeanneboyarsky
    At end of session
    1. https://speakerdeck.com/boyarsky
    2. https://github.com/boyarsky/2021-
    kcdc-java17
    2

    View Slide

  3. @jeanneboyarsky
    About Me
    • Java Champion


    • Author


    • Developer at NYC
    bank for 19+
    years


    • FIRST Robotics
    Mentor
    3

    View Slide

  4. @jeanneboyarsky
    Pause for a Commercial
    4
    Java certs


    •Java 8


    •Java 11


    •Java 17 next


    Book giveaway at end!

    View Slide

  5. @jeanneboyarsky
    Another Commercial
    5

    View Slide

  6. @jeanneboyarsky
    Disclaimer
    • A bit of the material is from my
    books.


    • Some of the material in this
    presentation may appear in
    our upcoming certification
    books.
    • Oracle can announce anything (I
    don’t work for Oracle.)


    6

    View Slide

  7. @jeanneboyarsky
    Introductions
    7

    View Slide

  8. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    8

    View Slide

  9. @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.
    9

    View Slide

  10. @jeanneboyarsky
    Required Software for Lab
    Option 1


    •Java 17 - http://jdk.java.net/17/


    •Text editor of your choice


    •No IDE!


    or…
    10

    View Slide

  11. @jeanneboyarsky
    Required Software for Lab
    Option 2


    •https://www.compilejava.net


    System.out.println(System.getProperty(“java.version"));


    •17-ea (on Sunday night)


    • Can only do some labs


    • Module 3 - sealed classes preview (in 16)


    • Module 5 and 6 - no IO


    • Module 7 - no JPMS


    11

    View Slide

  12. @jeanneboyarsky
    Optional aliases
    alias javac17=/Library/Java/
    JavaVirtualMachines/jdk-17.X.jdk/
    Contents/Home/bin/javac
    alias java17=/Library/Java/
    JavaVirtualMachines/jdk-17.X.jdk/
    Contents/Home/bin/java
    alias jshell17=/Library/Java/
    JavaVirtualMachines/jdk-17.X.jdk/
    Contents/Home/bin/jshell
    12

    View Slide

  13. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    13

    View Slide

  14. @jeanneboyarsky
    If new to the cert
    14
    808
    809 815


    +


    816
    819 ???
    Associate
    Professional
    Java 8 Java 11 Java 17

    View Slide

  15. @jeanneboyarsky
    813


    (from


    Java <6)
    810


    (from


    Java 7)
    If hold a cert
    15
    817


    (from Java
    6/7/8)
    ???
    Professional
    Java 8 Java 11 Java 17
    Retires 11/30

    View Slide

  16. @jeanneboyarsky
    Features
    Feature Preview Final
    Text Blocks 13, 14 15
    APIs various
    16

    View Slide

  17. @jeanneboyarsky
    What’s wrong?
    String old = "kcdc,Kansas City,"session,workshop
    "

    + "meetup,Various,lecture\n"
    ;

    17
    Doesn’t compile: missing \
    Missing quote on line 1
    Missing line break
    15

    View Slide

  18. @jeanneboyarsky
    Compare
    String old = "kcdc,Kansas City,\"session,workshop\"\n
    "

    + “meetup,Various,lecture\n"
    ;

    String textBlock = ""
    "

    kcdc,Kansas City,"session,workshop
    "

    meetup,Various,lectur
    e

    """
    ;

    18
    Easier to read and code!
    15

    View Slide

  19. @jeanneboyarsky
    Text Block Syntax
    String textBlock = ""
    "

    kcdc,Kansas City,"session,workshop
    "

    meetup,Various,lectur
    e

    """;
    incidental
    whitespace
    start block
    end block
    15
    19

    View Slide

  20. @jeanneboyarsky
    Essential Whitespace
    String textBlock = ""
    "

    >

    >

    Jeanne Boyarsk
    y

    >

    >

    """
    ;

    incidental
    whitespace
    essential whitespace
    15
    20

    View Slide

  21. @jeanneboyarsky
    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
    15
    21

    View Slide

  22. @jeanneboyarsky
    New lines
    String textBlock = ""
    "

    \n
    >

    Jeanne\nBoyarsk
    y

    >

    """
    ;

    no line break at end
    Two new lines


    (explicit and implicit)
    One new line (explicit)
    15
    22

    View Slide

  23. @jeanneboyarsky
    Escaping Three Quotes
    String textBlock = ""
    "

    better \""
    "

    but can do \"\"\"
    """
    ;

    15
    23

    View Slide

  24. @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

    b

    c

    """
    ;

    Which do
    you like
    best?
    Also normalizes (bye \r)
    12
    24

    View Slide

  25. @jeanneboyarsky
    Transform
    String option1 = “chiefs".transform
    (

    s -> s.toUpperCase())
    ;

    String option2 = ""
    "

    chief
    s

    """.transform(s -> s.toUpperCase())
    ;

    Which do
    you like
    best?
    12
    25

    View Slide

  26. @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
    26

    View Slide

  27. @jeanneboyarsky
    Module 1 - Question 1
    Which is true about this text block?


    String sql = ""
    "

    select
    *

    from mytabl
    e

    where weather = 'snow'
    ;

    """
    ;

    A. Has incidental whitespace


    B. Has essential whitespace


    C. Both A and B


    D. Does not compile
    27

    View Slide

  28. @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
    28

    View Slide

  29. @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
    29

    View Slide

  30. @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
    30

    View Slide

  31. @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
    31

    View Slide

  32. @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
    32

    View Slide

  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
    33

    View Slide

  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
    34

    View Slide

  35. @jeanneboyarsky
    Module 1 - Question 9
    How many whitespace characters are
    removed by stripIndent()?


    String sql = ""
    "

    select "name
    "

    from mytable
    ;

    """
    ;

    A. 0


    B. 1


    C. 2


    D. 3
    35

    View Slide

  36. @jeanneboyarsky
    Module 1 - Question 10
    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
    36

    View Slide

  37. @jeanneboyarsky
    Lab & Break
    37
    See handout

    View Slide

  38. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    38

    View Slide

  39. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    39

    View Slide

  40. @jeanneboyarsky
    Features
    Feature Preview Final
    Switch Expressions 12, 13 14
    Pattern Matching for instanceof 14, 15 16
    Pattern Matching for switch 17 ?
    40

    View Slide

  41. @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)
    41

    View Slide

  42. @jeanneboyarsky
    Switch Expressions 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
    42

    View Slide

  43. @jeanneboyarsky
    Switch Expressions 14
    String store = "Hallmark"
    ;

    String output = switch(store)
    {

    case "Hallmark" -> "KC"
    ;

    case "Crayola" -> "PA"
    ;

    default -> "anywhere"
    ;

    }
    ;

    System.out.println(output)
    ;

    Switch returns values
    43

    View Slide

  44. @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
    44

    View Slide

  45. @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
    45

    View Slide

  46. @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
    46

    View Slide

  47. @jeanneboyarsky
    Yield with Switch Stmt 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!
    47

    View Slide

  48. @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)
    48

    View Slide

  49. @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
    49

    View Slide

  50. @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
    50

    View Slide

  51. @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
    51

    View Slide

  52. @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
    52

    View Slide

  53. @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
    53

    View Slide

  54. @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
    54

    View Slide

  55. @jeanneboyarsky
    Reusing a variable 16
    if (num instanceof Integer numAsInt)
    {

    numAsInt = 6
    ;

    System.out.println(numAsInt)
    ;

    }

    Legal. please don’t.
    55

    View Slide

  56. @jeanneboyarsky
    Pattern matching for switch 17


    preview
    static int toInt(Object obj)
    {

    return switch (obj)
    {

    case Integer i -> i
    ;

    case Double d -> d.intValue()
    ;

    case String s -> Integer.parseInt(s)
    ;

    default -> throw new


    IllegalArgumentException("unknown type")
    ;

    }
    ;

    }

    Reminder: Syntax can change
    56

    View Slide

  57. @jeanneboyarsky
    But wait, there’s more 17


    preview
    static void printOddOrEven(Object obj)
    {

    switch (obj)
    {

    case Integer i && i % 2 == 1 ->


    System.out.println("odd")
    ;

    case Integer i && i % 2 == 0 ->


    System.out.println(“even")
    ;

    default -> System.out.println("not an int")
    ;

    }
    ;

    }

    Reminder: Feature can still change
    57

    View Slide

  58. @jeanneboyarsky
    Module 2 - Question 1
    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)
    ;

    58
    C. 5


    D. Does not compile
    A. 1


    B. 2

    View Slide

  59. @jeanneboyarsky
    Module 2 - Question 2
    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)
    ;

    59
    C. 3


    D. 4
    A. 1


    B. 2

    View Slide

  60. @jeanneboyarsky
    Module 2 - Question 3
    How many lines need changing to make
    this code compile?


    char ch = 'b'
    ;

    int value = switch (ch)
    {

    case 'a' : yield 1
    ;

    case 'b' : { yield 2;
    }

    case 'c' -> yield 3
    ;

    default -> 4
    ;

    }
    ;

    System.out.println(value)
    ;

    60
    C. 3


    D. 4
    A. 1


    B. 2

    View Slide

  61. @jeanneboyarsky
    Module 2 - Question 4
    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)
    ;

    61
    C. Either A or B


    D. None of the above
    A. int


    B. Object

    View Slide

  62. @jeanneboyarsky
    Module 2 - Question 5
    What does the following output?


    char ch = 'b'
    ;

    switch (ch)
    {

    case 'a' -> System.out.println(1)
    ;

    case 'b' -> System.out.println(2)
    ;

    case 'c' -> { System.out.println(3);
    }

    }
    ;

    A. 1


    B. 2


    C. 3


    D. Does not compile
    62

    View Slide

  63. @jeanneboyarsky
    Module 2 - Question 6
    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)
    ;

    63
    C. y694


    D. Does not compile
    A. x694


    B. xy694

    View Slide

  64. @jeanneboyarsky
    Module 2 - Question 7
    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

    64
    C. 1, 2 and 3


    D. Does not compile
    A. 1


    B. 1 and 3

    View Slide

  65. @jeanneboyarsky
    Module 2 - Question 8
    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 implemente
    d

    }

    65
    C. equals() does


    not compile


    A. equals() is correct


    B. equals() is incorrect

    View Slide

  66. @jeanneboyarsky
    Module 2 - Question 9
    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()) {
    }

    66
    C. 2


    D. 3


    A. 0


    B. 1

    View Slide

  67. @jeanneboyarsky
    Module 2 - Question 10
    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)
    ;

    }

    }

    67
    C. 8


    D. Does not compile


    A. 2


    B. 3

    View Slide

  68. @jeanneboyarsky
    Lab & Break
    68
    See handout

    View Slide

  69. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    69

    View Slide

  70. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    70

    View Slide

  71. @jeanneboyarsky
    Features
    Feature Preview Final
    Records 14, 15 16
    Sealed classes 15, 16 17
    71

    View Slide

  72. @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
    72

    View Slide

  73. @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
    73
    16

    View Slide

  74. @jeanneboyarsky
    POJO
    • constructor


    • toString()


    • hashCode() - more rules


    • equals() - still more rules
    74
    16

    View Slide

  75. @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


    75

    View Slide

  76. @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]
    76

    View Slide

  77. @jeanneboyarsky
    Add/change methods 16
    public record Book (String title, int numPages)
    {

    @Overrid
    e

    public String title()
    {

    return '"' + title + '"'
    ;

    }

    public boolean isLong()
    {

    return numPages > 300
    ;

    }

    }

    Custom


    method
    Change


    behavior
    77

    View Slide

  78. @jeanneboyarsky
    Not really immutable 16
    public record Book (String title, int numPages,


    List chapters)
    {

    }

    Book book = new Book("Breaking and entering", 289,


    chapters)
    ;

    chapters.add("2")
    ;

    book.chapters().add("3")
    ;

    System.out.println(book.chapters())
    ;

    Prints [1,2,3] because shallow immutability
    78

    View Slide

  79. @jeanneboyarsky
    Now immutable 16
    public record Book (String title, int numPages,


    List chapters)
    {

    public Book
    {

    chapters = List.copyOf(chapters)
    ;

    }

    }

    Must match record


    access modifier
    Compact constructor
    79

    View Slide

  80. @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
    80

    View Slide

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

    View Slide

  82. @jeanneboyarsky
    Subclass reference
    82
    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

    View Slide

  83. @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
    83

    View Slide

  84. @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); // fals
    e

    System.out.println("" instanceof List); // erro
    r

    System.out.println(boolWrapper instanceof List); // erro
    r

    }

    84

    View Slide

  85. @jeanneboyarsky
    Module 3 - 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))
    ;

    }

    85
    C. 2


    D. None of the above
    A. 0


    B. 1

    View Slide

  86. @jeanneboyarsky
    Module 3 - 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())
    ;

    }

    86
    C. Does not compile


    D. None of the above
    A. chicken


    B. CHICKEN

    View Slide

  87. @jeanneboyarsky
    Module 3 - 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())
    ;

    }

    87
    C. Does not compile


    D. None of the above
    A. chicken


    B. CHICKEN

    View Slide

  88. @jeanneboyarsky
    Module 3 - 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 "";
    }

    }

    88
    C. 3


    D. 4
    A. 1


    B. 2

    View Slide

  89. @jeanneboyarsky
    Module 3 - Question 5
    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))
    ;

    }

    89
    C. 0


    D. Does not compile
    A. Negative #


    B. Positive #

    View Slide

  90. @jeanneboyarsky
    Module 3 - 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())
    ;

    }

    90
    C. Does not compile


    D. None of the above
    A. true


    B. false

    View Slide

  91. @jeanneboyarsky
    Module 3 - 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


    91

    View Slide

  92. @jeanneboyarsky
    Module 3 - 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


    92

    View Slide

  93. @jeanneboyarsky
    Module 3 - 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


    93

    View Slide

  94. @jeanneboyarsky
    Module 3 - Question 10
    How many compiler errors are in this
    code?


    public sealed class Phone
    {

    class IPhone extends Phone
    {

    }

    class Android extends Phone
    {

    }

    }

    94
    C. 2


    D. 3
    A. 0


    B. 1

    View Slide

  95. @jeanneboyarsky
    Lab & Break
    95
    See handout

    View Slide

  96. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    96

    View Slide

  97. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    97

    View Slide

  98. @jeanneboyarsky
    Optional
    98
    Optional.empty() Optional.of(95)
    95

    View Slide

  99. @jeanneboyarsky
    Stream Flow
    99
    Intermediate
    Operations
    Source Terminal Operation

    View Slide

  100. @jeanneboyarsky
    Painting Example
    100
    1 2 3
    4 5
    6
    Take sign
    out of box
    Put sign
    in pile
    Intermediate
    Operations
    Paint sign

    View Slide

  101. @jeanneboyarsky
    Painting Example
    101
    Take sign
    out of box
    Put sign
    in pile
    Intermediate
    Operations
    Only do 2 signs
    Paint sign

    View Slide

  102. @jeanneboyarsky
    Painting Example
    102
    stream() forEach()
    Intermediate
    Operations
    filter() limit()
    sorted()

    View Slide

  103. @jeanneboyarsky
    Basic Stream
    list.stream(
    )

    .map(String::strip
    )

    .filter(s -> ! s.isBlank()
    )

    .map(String::length
    )

    .collect(Collectors.toList())
    ;

    Terminal op
    Source
    Intermediate


    ops
    103

    View Slide

  104. @jeanneboyarsky
    Find Max
    public OptionalInt max(List list)
    {

    if (list.isEmpty())
    {

    return OptionalInt.empty()
    ;

    }

    Collections.sort(list)
    ;

    int max = list.get(list.size() - 1)
    ;

    return OptionalInt.of(max)
    ;

    }

    public OptionalInt maxStream(List list)
    {

    list.stream().mapToInt(x -> x).max()
    ;

    }

    104

    View Slide

  105. @jeanneboyarsky
    Join a String
    public String join(List list)
    {

    String result = ""
    ;

    for (Integer num : list)
    {

    if (! result.isBlank())
    {

    result += " "
    ;

    }

    result += num
    ;

    }

    return result
    ;

    }
    public String joinStream(List list)
    {

    return list.stream(
    )

    .map(Object::toString
    )

    .collect(Collectors.joining(" "))
    ;

    }

    105

    View Slide

  106. @jeanneboyarsky
    Get First Failures
    public List firstFailures
    (

    List builds)
    {

    List result = new ArrayList<>()
    ;

    for (Build build : builds
    )

    if (!build.isPassed()
    )

    result.add(build.getNum())
    ;

    else
    return result
    ;

    return Collections.emptyList()
    ;

    }
    public List firstFailuresAsStream
    (

    List builds)
    {

    return builds.stream(
    )

    .takeWhile(b -> ! b.isPassed()
    )

    .map(Build::getNum
    )

    .collect(Collectors.toList())
    ;

    }

    106

    View Slide

  107. @jeanneboyarsky
    Get First Pass
    public OptionalInt firstPass(List builds)
    {

    List result = new ArrayList<>()
    ;

    for (Build build : builds)
    {

    if (build.isPassed())
    {

    return OptionalInt.of(build.getNum())
    ;

    }

    }

    return OptionalInt.empty()
    ;

    }

    public OptionalInt firsrtPassAsStream
    (

    List builds)
    {

    return builds.stream(
    )

    .dropWhile(b -> ! b.isPassed()
    )

    .mapToInt(Build::getNum
    )

    .findFirst()
    ;

    }

    107

    View Slide

  108. @jeanneboyarsky
    Strings
    public long countLinesWithQuestionMark(String text)
    {

    return text.lines(
    )

    .filter(s -> s.contains("?")
    )

    .count()
    ;

    }
    public long countQuestionMark(String text)
    {

    return text.chars(
    )

    .filter(c -> c == '?'
    )

    .count()
    ;

    }

    108

    View Slide

  109. @jeanneboyarsky
    Common Terminal Ops
    • count()


    • collect() - more on this shortly


    • allMatch(), anyMatch(), noneMatch()


    • findFirst(), findAny()


    • min()/max()


    • forEach()
    109
    109

    View Slide

  110. @jeanneboyarsky
    Common Intermediate Ops
    • filter()


    • map()


    • distinct()


    • limit(), skip()


    • sorted()


    • peek()
    110

    View Slide

  111. @jeanneboyarsky
    Generating Infinite Stream
    public String tenStars()
    {

    return Stream.generate(() -> "*"
    )

    .limit(10
    )

    .collect(Collectors.joining())
    ;

    }

    111

    View Slide

  112. @jeanneboyarsky
    Iterative Infinite Stream
    public String counting()
    {

    return Stream.iterate(1, i -> i+1
    )

    .limit(10
    )

    .map(Object::toString
    )

    .collect(Collectors.joining(" "))
    ;

    }

    public String countingWithLimit()
    {

    return Stream.iterate(1, i -> i <=10, i -> i+1
    )

    .map(Object::toString
    )

    .collect(Collectors.joining(" "))
    ;

    }

    112

    View Slide

  113. @jeanneboyarsky
    FlatMap
    public List flatten()
    {

    var first = List.of("a", "b")
    ;

    List second = List.of()
    ;

    var listOfLists = List.of(first, second)
    ;

    return listOfLists.stream(
    )

    .flatMap(Collection::stream
    )

    .collect(Collectors.toList())
    ;

    }

    var! Why List?
    113

    View Slide

  114. @jeanneboyarsky
    Creating a Map
    public Map mapByName
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.toMap
    (

    Function.identity(),


    String::length))
    ;

    }

    public Map mapBySize
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.toMap
    (

    String::length,


    Function.identity(),


    (a, b) -> a))
    ;

    }

    114

    View Slide

  115. @jeanneboyarsky
    Adding a level
    public Map grouping
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.groupingBy
    (

    String::length
    ,

    Collectors.counting()))
    ;

    }

    public Map partitioning
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.partitioningBy
    (

    String::isEmpty,


    Collectors.counting()))
    ;

    }

    115

    View Slide

  116. @jeanneboyarsky
    Grouping vs Partitioning
    public Map> grouping
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.groupingBy
    (

    String::length))
    ;

    }

    public Map> partitioning
    (

    List list)
    {

    return list.stream(
    )

    .collect(Collectors.partitioningBy
    (

    String::isEmpty))
    ;

    }

    116

    View Slide

  117. @jeanneboyarsky
    Reducing
    public Integer sum(List list)
    {

    return list.stream(
    )

    .reduce(0, (x,y) -> x + y)
    ;

    }

    public Optional min(List list)
    {

    return list.stream(
    )

    .reduce((x, y) -> x < y ? x : y)
    ;

    }

    117

    View Slide

  118. @jeanneboyarsky
    Advanced Ops
    • Sources


    • generate()


    • iterate()


    • ofNullable()


    • Intermediate


    • flatMap()


    • Terminal


    • reduce()


    • Collectors


    • toMap()


    • groupingBy()


    • partitioningBy()
    118

    View Slide

  119. @jeanneboyarsky
    Teeing Collector
    119
    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)
    ;

    View Slide

  120. @jeanneboyarsky
    Module 4 - Question 1
    What does this output?


    public static void main(String[] args)
    {

    long count = Strea
    m

    .iterate(1; i-> i< 10;


    i-> i+2).count()
    ;

    System.out.println(count)
    ;

    }

    A. 0


    B. 5


    C. Does not compile


    D. None of the above


    120

    View Slide

  121. @jeanneboyarsky
    Module 4 - Question 2
    What does this output?


    Stream.iterate(1, i-> i< 10, i-> i++
    )

    .takeWhile(i -> i < 5
    )

    .forEach(System.out::println)
    ;

    A. The numbers 1-4


    B. The numbers 5-10


    C. Does not compile


    D. None of the above


    121

    View Slide

  122. @jeanneboyarsky
    Module 4 - Question 3
    What does this output?


    var map = Stream.generate(() -> 1
    )

    .limit(5
    )

    .collect(Collectors.partitioningBy
    (

    x -> x % 2 ==0))
    ;

    System.out.println(map)
    ;

    A. {false=[1, 1, 1, 1, 1]}


    B. {false=[1, 1, 1, 1, 1], true=[]}


    C. Does not compile


    D. None of the above


    122

    View Slide

  123. @jeanneboyarsky
    Module 4 - Question 4
    What does this output?


    long count = Stream.of(null).count()
    ;

    System.out.println(count)
    ;

    A. 0


    B. 1


    C. null


    D. Does not compile


    E. None of the above


    123

    View Slide

  124. @jeanneboyarsky
    Module 4 - Question 5
    What does this output?


    long count = Stream.ofNullable(null).count()
    ;

    System.out.println(count)
    ;

    A. 0


    B. 1


    C. null


    D. Does not compile


    E. None of the above


    124

    View Slide

  125. @jeanneboyarsky
    Module 4 - Question 6
    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


    125

    View Slide

  126. @jeanneboyarsky
    Module 4 - Question 7
    Which can fill in the blank to print false?
    (Choose all that apply)


    var s = Stream.generate(() -> "meow")
    ;

    var match = ________________(String::isEmpty)
    ;

    System.out.println(match)
    ;

    A. anyMatch


    B. allMatch


    C. noneMatch


    D. findFirst


    126

    View Slide

  127. @jeanneboyarsky
    Module 4 - Question 8
    Which fill in the blank to compile but
    cause the program to hang?(Choose all
    that apply)


    var s = Stream.generate(() -> "meow")
    ;

    var match = ________________(String::isEmpty)
    ;

    System.out.println(match)
    ;

    A. anyMatch


    B. allMatch


    C. noneMatch


    D. findFirst


    127

    View Slide

  128. @jeanneboyarsky
    Module 4 - Question 9
    What is the output of the following?


    var x = Stream.of("a", "b", "c"
    )

    .filter(c -> c != "b")
    ;

    System.out.println(x)
    ;

    A. [b]


    B. [a, c]


    C. [a, b, c]


    D. Does not compile


    E. None of the above


    128

    View Slide

  129. @jeanneboyarsky
    Module 4 - Question 10
    If ____ fills in the blank, then the output
    is_____ (Choose two)


    var x = Stream.of("a", "bb", "_________"
    )

    .collect(Collectors.toMap
    (

    String::length,


    Function.identity()))
    ;

    System.out.println(x)
    ;

    A. cc, {1=a, 2=bb, 3=cc}


    B. cc, a stack trace


    C. ccc, {1=a, 2=bb, 3=ccc}


    D. ccc, a stack trace


    129

    View Slide

  130. @jeanneboyarsky
    Lab & Break
    130
    See handout

    View Slide

  131. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    131

    View Slide

  132. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    132

    View Slide

  133. @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
    133

    View Slide

  134. @jeanneboyarsky
    Common Conversions
    Conversion What it does
    %s Formattable


    as String
    %d Decimal


    integer


    (no dot)
    %c Char
    %f Float


    (decimal)
    %n New line
    Many more out of
    scope. Examples:


    • %e - scientific
    notation


    • %t - time


    • %S - converts to all
    uppercase
    134

    View Slide

  135. @jeanneboyarsky
    Conversion Examples
    Code Output
    "%d%%".formatted(1.2) exception
    "%d%%".formatted(1
    )

    1%
    "%s%%".formatted(1
    )

    1%
    "%s%%".formatted(1.2
    )

    1.2%
    “%f%%".formatted(1.2) 1.200000f
    12
    135

    View Slide

  136. @jeanneboyarsky
    Formatting a Number
    Char What it does
    - Left justified
    + Always


    include


    +/-
    space Leading


    space if


    positive
    Char What it does
    0 Zero padded
    , Group


    numbers
    ( Negative # in


    parens
    136

    View Slide

  137. @jeanneboyarsky
    Flag Examples
    Code Output
    "%,d".formatted(1234) 1,234
    "%+d".formatted(1234
    )

    1234
    “% d".formatted(1234
    )

    1234
    “%,(d”.formatted(-1234
    )

    (1,234)
    “%,f”.formatted
    (

    1.23456789)
    1.234568
    12
    137

    View Slide

  138. @jeanneboyarsky
    Compact Number
    NumberFormat defaultFormat =
    NumberFormat.getCompactNumberInstance()
    ;

    NumberFormat shortFormat = NumberForma
    t

    .getCompactNumberInstance
    (

    Locale.US, NumberFormat.Style.SHORT)
    ;

    NumberFormat longFormat = NumberForma
    t

    .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
    138

    View Slide

  139. @jeanneboyarsky
    Date Formatting
    Letter What it does
    M Month
    d Day
    Y Year
    Letter What it does
    h/H Hour (12 or


    24 hours)
    m Minute
    s Second
    S Millisecond
    Z Timezone
    139

    View Slide

  140. @jeanneboyarsky
    Advanced Examples
    Code Output
    MM-dd 09-15
    MM/dd/yyyy Sep/15/2021
    MMMM dd, yyy
    y

    September 15, 2021
    hh:mm:s
    s

    13:23:00
    h 'o''clock' 1 o’clock
    LocalDate date = LocalDate.of(2021, Month.SEPTEMBER, 15)
    ;

    LocalTime time = LocalTime.of(13, 23)
    ;

    LocalDateTime dateTime = LocalDateTime.of(date, time)
    ;

    System.out.println(dateTime.format
    (

    DateTimeFormatter.ofPattern(“_______”)))
    ;

    140

    View Slide

  141. @jeanneboyarsky
    Create a Locale
    Locale loc = Locale.getDefault()
    ;

    Locale constant = Locale.JAPANESE
    ;

    Locale lang = new Locale("en")
    ;

    Locale country = new Locale("en", "US")
    ;

    Locale invalid = new Locale("US")
    ;

    Invalid locales don’t throw an
    exception, but don’t match
    141

    View Slide

  142. @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
    142

    View Slide

  143. @jeanneboyarsky
    Reading a Resource Bundle
    # Zoo_en.propertie
    s

    hello=Hell
    o

    open=The zoo is ope
    n

    // in main metho
    d

    Locale french = new Locale("fr", "FR")
    ;

    ResourceBundle rb =


    ResourceBundle.getBundle("Zoo", french)
    ;

    System.out.println(rb.getString("open"))
    ;

    Le zoo est ouvert
    # Zoo_fr.propertie
    s

    hello=Bonjou
    r

    open=Le zoo est ouver
    t

    143

    View Slide

  144. @jeanneboyarsky
    Picking the right bundle
    Looks for file Reason
    Zoo_fr_FR.properties Requested locale
    Zoo_fr.properties Requested language
    Zoo_en_US.properties Default locale
    Zoo_en.properties Default language
    Zoo.properties Default bundle
    throws exception No matches
    Once finds bundle, can only get
    values from it or parent
    144

    View Slide

  145. @jeanneboyarsky
    Message Format
    # Zoo_en.propertie
    s

    hello=Hello {0
    }

    open=The zoo is ope
    n

    // in main metho
    d

    ResourceBundle rb =


    ResourceBundle.getBundle("Zoo")
    ;

    String format = rb.getString("hello")
    ;

    System.out.println(MessageFormat.format
    (

    format, "Jeanne"))
    ;

    Hello Jeanne
    # Zoo_fr.propertie
    s

    hello=Bonjour {0
    }

    open=Le zoo est ouver
    t

    145

    View Slide

  146. @jeanneboyarsky
    Module 5 - Question 1
    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


    146

    View Slide

  147. @jeanneboyarsky
    Module 5 - Question 2
    What does this output?


    System.out.println("%s +%05d".formatted
    (

    "KCDC", 2021))
    ;

    A. KCDC 2021


    B. KCDC +2021


    C. KCDC +02021


    D. KCDC +002021


    E. None of the above


    147

    View Slide

  148. @jeanneboyarsky
    Module 5 - Question 3
    How many things need to be changed to
    print: 2K 3.14?


    CompactNumberFormat fmt =


    new CompactNumberFormat()
    ;

    System.out.println(fmt.format(2000) +


    " %.2d".formatted(3.14))
    ;

    A. 1


    B. 2


    C. 3


    D. 4


    148

    View Slide

  149. @jeanneboyarsky
    Module 5 - Question 4
    What does this print?


    LocalDateTime dateTime = LocalDateTime.of(2021,


    Month.SEPTEMBER, 14, 6, 15, 44)
    ;

    DateTimeFormatter fmt =


    DateTimeFormatter.ofPattern("M HH")
    ;

    System.out.println(dateTime.format(fmt))
    ;

    A. 9 6


    B. 9 06


    C. 15 6


    D. 15 06


    E. None of the above


    149

    View Slide

  150. @jeanneboyarsky
    Module 5 - Question 5
    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


    150

    View Slide

  151. @jeanneboyarsky
    Module 5 - Question 6
    Given the answers, which will be the first
    bundle to match?


    Locale.setDefault(Locale.US)
    ;

    ResourceBundle rb
    =

    new ResourceBundle("Zoo"
    ,

    new Locale("fr"))
    ;

    A. Zoo_en.properties


    B. Zoo_fr_FR.properties


    C. Zoo.properties


    D. None of the above


    151

    View Slide

  152. @jeanneboyarsky
    Module 5 - Question 7
    Given the answers, which will be the first
    bundle to match?


    Locale.setDefault(Locale.US)
    ;

    ResourceBundle rb
    =

    ResourceBundle.getBundle("Zoo"
    ,

    new Locale("fr"))
    ;

    A. Zoo_en.properties


    B. Zoo_US.properties


    C. Zoo.properties


    D. None of the above


    152

    View Slide

  153. @jeanneboyarsky
    Module 5 - Question 8
    Suppose rb is Locale_en.properties in this
    example. Which file will Java look at first
    if there is no match in that file?


    ResourceBundle rb
    =

    ResourceBundle.getBundle("Zoo"
    ,

    new Locale("fr"))
    ;

    A. Zoo_en_US.properties


    B. Zoo_fr_FR.properties


    C. Zoo.properties


    D. None of the above


    153

    View Slide

  154. @jeanneboyarsky
    Module 5 - Question 9
    What does the following output?


    String format = "{2} < {1}"
    ;

    System.out.println(format.formatted(3, 5))
    ;

    A. 3 < 5


    B. 5 < 3


    C. {2} < 3


    D. {2} < 5


    E. None of the above


    154

    View Slide

  155. @jeanneboyarsky
    Module 5 - Question 10
    What does the following output?


    String format = "{1} < {0}”
    ;

    System.out.println
    (

    MessageFormat.format(3, 5))
    ;

    A. 3 < 5


    B. 5 < 3


    C. {2} < 3


    D. {2} < 5


    E. None of the above


    155

    View Slide

  156. @jeanneboyarsky
    Lab & Break
    156
    See handout

    View Slide

  157. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    157

    View Slide

  158. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    158

    View Slide

  159. @jeanneboyarsky
    Getting started
    File Class I/O
    Path Interface NIO.2
    Paths Class NIO.2
    Files Class NIO.2
    159

    View Slide

  160. @jeanneboyarsky
    Common ways to create a Path
    Path path1 = Paths.get("files","kcdc.txt")
    ;

    Path path2 = Paths.get("files/kcdc.txt")
    ;

    Path path3 = Path.of("files/kcdc.txt")
    ;

    Path path4 = new File("files/kcdc.txt").toPath()
    ;

    / vs \
    160

    View Slide

  161. @jeanneboyarsky
    Side note - NullPointer
    Path path = null
    ;

    // lots of code her
    e

    System.out.println(path.toAbsolutePath())
    ;

    % java11 HelpfulNullPointer.java


    Exception in thread "main" java.lang.NullPointerExceptio
    n

    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 nul
    l

    at HelpfulNullPointer.main(HelpfulNullPointer.java:9
    )

    14
    161

    View Slide

  162. @jeanneboyarsky
    Reading a File - Originally
    File file = new File("files/kcdc.txt")
    ;

    BufferedReader reader = null
    ;

    try
    {

    reader = new BufferedReader(new FileReader(file))
    ;

    String line = null
    ;

    while ((line = reader.readLine()) != null)
    {

    System.out.println(line)
    ;

    }

    } finally
    {

    if (reader != null)
    {

    reader.close()
    ;

    }

    }

    162

    View Slide

  163. @jeanneboyarsky
    Try with Resources
    File file = new File("files/kcdc.txt")
    ;

    try (BufferedReader reader = new BufferedReader
    (

    new FileReader(file)))
    {

    String line = null
    ;

    while ((line = reader.readLine()) != null)
    {

    System.out.println(line)
    ;

    }

    }

    163

    View Slide

  164. @jeanneboyarsky
    3 ways with NIO.2
    Path path = Path.of(“files/kcdc.txt")
    ;

    String str = Files.readString(path)
    ;

    List list = Files.readAllLines(path)
    ;

    String strOld = new String(Files.readAllBytes(path),


    Charset.defaultCharset())
    ;

    System.out.println(str)
    ;

    list.forEach(System.out::println)
    ;

    System.out.println(strOld)
    ;

    164

    View Slide

  165. @jeanneboyarsky
    Fixed with UncheckedIOException
    public String readCombinedValues() throws IOException
    {

    Path path = Path.of("files")
    ;

    return Files.list(path
    )

    .map(this::readAsString
    )

    .collect(Collectors.joining(","))
    ;

    }

    private String readAsString(Path path)
    {

    try
    {

    return Files.readString(path)
    ;

    } catch(IOException e)
    {

    throw new UncheckedIOException(e)
    ;

    }

    }

    165

    View Slide

  166. @jeanneboyarsky
    What’s wrong?
    Files.lines(path).forEach(System.out::println)
    ;

    Resource leak :(
    try (Stream stream = Files.lines(path))
    {

    stream.forEach(System.out::println)
    ;

    }

    166

    View Slide

  167. @jeanneboyarsky
    What’s wrong?
    public String readCombinedValues()
    {

    Path path = Path.of(“files")
    ;

    return Files.list(path
    )

    .map(this::readAsString
    )

    .collect(Collectors.joining(","))
    ;

    }

    private String readAsString(Path path)
    {

    return Files.readString(path)
    ;

    }

    Files list() and readString() throw
    checked IOException
    167

    View Slide

  168. @jeanneboyarsky
    Writing a File - IO
    File file = new File("kcdc.txt")
    ;

    try (BufferedWriter writer = new BufferedWriter
    (

    new FileWriter(file)))
    {

    writer.write("Hello\n")
    ;

    }

    try (PrintWriter writer = new PrintWriter
    (

    new FileWriter(file)))
    {

    writer.println("Hello\n")
    ;

    }

    try (BufferedOutputStream stream =


    new BufferedOutputStream
    (

    new FileOutputStream(file)))
    {

    stream.write(“Hello\n".getBytes
    (

    Charset.defaultCharset()))
    ;

    }

    168

    View Slide

  169. @jeanneboyarsky
    Writing a File - NIO.2
    Path path = Path.of(“kcdc.txt”)
    ;

    Files.write(path, “hello".getBytes
    (

    Charset.defaultCharset()))
    ;

    Files.writeString(path, "hello")
    ;

    Files.write(path, List.of("hello"))
    ;

    169

    View Slide

  170. @jeanneboyarsky
    Writing a File - Common Options
    Files.writeString(path, "hello",


    StandardOpenOption.________)
    ;

    APPEND Adds to file
    CREATE Creates new


    file if doesn’t


    exist
    CREATE_NEW Creates new


    file if exists.


    Otherwise fails
    Defaults to
    creating if doesn’t
    exist and
    overwriting if does
    170

    View Slide

  171. @jeanneboyarsky
    New Files.mismatch()
    Path kcdc = Path.of("files/kcdc.txt")
    ;

    Path kc = Path.of("files/kc.txt")
    ;

    System.out.println(Files.mismatch(kcdc, kc))
    ;

    System.out.println(Files.mismatch(kcdc, kcdc))
    ;

    12
    11 (index of first character different)


    -1 (same file contents regardless of whether exists)
    171

    View Slide

  172. @jeanneboyarsky
    Other Useful Files methods
    isSameFile() Resolve to same file
    createDirectory()


    createDirectories()
    The later adds


    interm folders
    copy() Copy path/input


    stream to file/directory
    move() Move between paths
    delete()


    deleteIfExists()
    The former throws
    exception
    newBufferedReader()


    newBufferedWriter()
    Interact with legacy I/O
    walk() Visit all files in tree
    A number of these take optional varargs to customize
    172

    View Slide

  173. @jeanneboyarsky
    Useful Path methods
    toFile() Legacy file
    toAbsolutePath() / or c: or …
    getParent() One level up
    getRoot() Top level
    normalize() Simplifies . and ..
    relativize(Path) Relative path from


    object to parameter


    (both must be absolute or relative)
    resolve(Path) Add parameter to path of object


    (if absolute path passed in,


    object ignored)
    173

    View Slide

  174. @jeanneboyarsky
    Types of I/O
    • Byte vs character


    • Input vs output


    • Low level vs high level


    Examples


    • ByteArrayInputStream


    • FileWriter


    • ObjectOutputStream
    174

    View Slide

  175. @jeanneboyarsky
    Console
    Console c = System.console()
    ;

    String line = c.readLine("Name?")
    ;

    String formatting = c.readLine("%s?", "Name")
    ;

    char[] password = c.readPassword()
    ;

    char[] pwd = c.readPassword("%s?", “Secrets")
    ;

    c.printf("%d", 1)
    ;

    c.format("%b", true)
    ;

    reader() and writer()
    for direct access
    Console can be null!
    175

    View Slide

  176. @jeanneboyarsky
    Module 6 - Question 1
    What does the following output?


    Path clock = new Path("time/device/../clock")
    ;

    Path phone = new Path("time/phone")
    ;

    System.out.println(clock.relativize(phone))
    ;

    A. phone


    B. ../phone


    C. time/device/phone


    D. time/device/../clock/..phone


    E. None of the above


    176

    View Slide

  177. @jeanneboyarsky
    Module 6 - Question 2
    What does the following output?


    Path clock = Paths.get(“time/device/../clock”)
    ;

    Path phone = Path.of(“time/phone")
    ;

    System.out.println(clock.relativize(phone))
    ;

    A. phone


    B. ../phone


    C. time/device/phone


    D. time/device/../clock/..phone


    E. None of the above


    177

    View Slide

  178. @jeanneboyarsky
    Module 6 - Question 3
    Which are true?


    Path path = Path.of("file")
    ;

    System.out.println(Files.mismatch(path, path))
    ;

    A. If the file exists, prints -1


    B. If the file exists, throws exception


    C. If the file does not exist, prints -1


    D. If the file does not exist, throws exception


    E. Does not compile


    178

    View Slide

  179. @jeanneboyarsky
    Module 6 - Question 4
    Which are true if file1 contains “howdy”?


    Path path1 = Path.of("file1")
    ;

    Path path2 = Path.of("file2")
    ;

    System.out.println(Files.mismatch(path1, path2))
    ;

    A. If file2 contains “howdy”, prints -1


    B. If file2 contains “howdy”, prints 0


    C. If file2 does not exist, prints -1


    D. If file2 does not exist, throws exception


    E. Does not compile


    179

    View Slide

  180. @jeanneboyarsky
    Module 6 - Question 5
    Which are true if file1 contains “howdy”?


    Path path1 = Path.of("file1")
    ;

    Path path2 = Path.of("file2")
    ;

    System.out.println(Files.mismatch(path1, path2))
    ;

    A. If file2 contains “hello”, prints -1


    B. If file2 contains “hello”, prints 0


    C. If file2 contains “hello”, prints 1


    D. If file2 contains “uh”, prints -1


    E. If file2 contains “uh”, prints 0


    180

    View Slide

  181. @jeanneboyarsky
    Module 6 - Question 6
    How many problems are in this code?


    public static void main(String[] args)
    {

    Files.lines(Path.of("lamp")
    )

    .filter(String::isEmpty
    )

    .collect(Collectors.toSet()
    )

    .forEach(System.out::println)
    ;

    }

    A. 0


    B. 1


    C. 2


    D. 3


    181

    View Slide

  182. @jeanneboyarsky
    Module 6 - Question 7
    What is true of this code?


    Console console = System.console()
    ;

    char[] secret = console.readPassword()
    ;

    System.out.println(secret)
    ;

    A. Guaranteed to print password


    B. Guaranteed not to print password


    C. Guaranteed to complete successfully


    D. Does not compile


    E. May throw an unchecked exception


    182

    View Slide

  183. @jeanneboyarsky
    Module 6 - Question 8
    Which of these are meant for binary data?


    A. FileInputStream


    B. FileReader


    C. InputStreamReader


    D. ObjectOutputStream


    E. PrintWriter


    183

    View Slide

  184. @jeanneboyarsky
    Module 6 - Question 9
    Which of these are meant for output?


    A. FileInputStream


    B. FileReader


    C. InputStreamReader


    D. ObjectOutputStream


    E. PrintWriter


    184

    View Slide

  185. @jeanneboyarsky
    Module 6 - Question 10
    Which of these are low level?


    A. FileInputStream


    B. FileReader


    C. InputStreamReader


    D. ObjectOutputStream


    E. PrintWriter


    185

    View Slide

  186. @jeanneboyarsky
    Lab & Break
    186
    See handout

    View Slide

  187. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    187

    View Slide

  188. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    188

    View Slide

  189. @jeanneboyarsky
    Background
    •Code replies on dependencies


    •Open source jar


    •Commercial jar


    •Internal jar


    •JDK APIs


    •JAR Hell
    189

    View Slide

  190. @jeanneboyarsky
    Benefits
    •Specify what use


    •No circular dependencies


    •Unique package enforcement


    •Custom Java builds/packages


    •Better access control


    (“Private packages’)
    190

    View Slide

  191. @jeanneboyarsky
    Designing with Modules
    191
    No cycles

    View Slide

  192. @jeanneboyarsky
    What is a module?
    •One or more packages


    •module-info.java file
    192

    View Slide

  193. @jeanneboyarsky
    Small module
    •One package


    •module-info.java file
    193

    View Slide

  194. @jeanneboyarsky
    Simplest module
    •module-info.java file in module
    root directory
    194
    module zoo.animal.feeding
    {

    }

    Module name


    (periods common


    like packages)
    “module” keyword
    Technically no
    packages required

    View Slide

  195. @jeanneboyarsky
    Adding a class
    195
    package zoo.animal.feeding
    ;

    public class Task
    {

    public static void main(String... args)
    {

    System.out.println("All fed!")
    ;

    }

    }

    View Slide

  196. @jeanneboyarsky
    Directory Structure
    196

    View Slide

  197. @jeanneboyarsky
    Running and Packaging
    197
    javac --module-path mods -d feeding


    feeding/zoo/animal/feeding/*.java


    feeding/module-info.jav
    a

    java --module-path feeding --module


    zoo.animal.feeding/zoo.animal.feeding.Tas
    k

    jar -cvf mods/zoo.animal.feeding.jar -C feeding/
    .

    module name fully qualified class name
    -p is module path


    -m is module

    View Slide

  198. @jeanneboyarsky
    Directory Structure
    198

    View Slide

  199. @jeanneboyarsky
    Exports Directive
    199
    module zoo.animal.feeding
    {

    exports zoo.animal.feeding
    ;

    }

    Now package available outside of module

    View Slide

  200. @jeanneboyarsky
    Adding a second module
    200
    module zoo.animal.care
    {

    exports zoo.animal.care.medical
    ;

    requires zoo.animal.feeding
    ;

    }

    Declares dependency on feeding

    View Slide

  201. @jeanneboyarsky
    Now we can use the class
    201
    package zoo.animal.care.details
    ;

    import zoo.animal.feeding.*
    ;

    public class HippoBirthday
    {

    private Task task
    ;

    }

    Sub-package

    View Slide

  202. @jeanneboyarsky
    Levels of access control
    202
    Level Within module Outside module
    private Accessible only


    within class
    No access
    default (package/


    package-private)
    Accessible only


    within package
    No access
    protected Accessible only


    within package or


    to subclasses
    Accessible to


    subclasses only if


    exported
    public Accessible to all


    classes
    Accessible only if


    package exported

    View Slide

  203. @jeanneboyarsky
    Requires Transitive
    • Superset of requires


    • Adds all modules the target exports


    • Cannot have duplicate requires
    statements (or requires and requires
    transitive)


    • Can require something that is in the
    other modules exports list
    203

    View Slide

  204. @jeanneboyarsky
    Reviewing Directives
    204
    exports Make package available
    requires Depends on this module
    requires


    transitive
    Depends on this module and


    everything it requires

    View Slide

  205. @jeanneboyarsky
    More Directives
    205
    provides Provides an implementation


    of a service


    provides zoo.staff.ZooApi with


    zoo.staff.ZooImpl
    uses Uses a service


    uses zoo.staff.ZooImpl
    opens Allows reflection


    opens zoo.animal.talks.schedule;


    opens zoo.animal.talks.media


    to zoo.staff;

    View Slide

  206. @jeanneboyarsky
    Module 7 - Question 1
    Is this is a valid module?


    zoo.staf
    f

    |---zo
    o

    |-- staf
    f

    |-- Vet.jav
    a

    A. Yes if module-info was added under
    zoo.staff


    B. Yes if module-info was added under zoo


    C. Yes if module-info was added under staff


    D. None of these make it valid


    206

    View Slide

  207. @jeanneboyarsky
    Module 7 - Question 2
    Which fills in the blank if animal.behavior is a
    package?


    module animal
    {

    ______ animal.behavior
    ;

    }

    A. export


    B. exports


    C. require


    D. requires


    207

    View Slide

  208. @jeanneboyarsky
    Module 7 - Question 3
    Which fills in the blank if animal.behavior is a
    module?


    module animal
    {

    ______ animal.behavior
    ;

    }

    A. export


    B. exports


    C. require


    D. requires


    208

    View Slide

  209. @jeanneboyarsky
    Module 7 - Question 4
    Fill in the blanks to compile


    jav
    a

    ____ zoo.animal.talks/zoo/animal/talks/Peacock
    s

    ____ module
    s

    A. -d and -m


    B. -d and -p


    C. -m and -d


    D. -m and -p


    E. None of the above


    209

    View Slide

  210. @jeanneboyarsky
    Module 7 - Question 5
    Which are true of this module? (Choose two)


    module com.food.supplier {
    }

    A. All packages are automatically exported


    B. No packages are automatically exported


    C. A main method can be run


    D. A main method cannot be run


    210

    View Slide

  211. @jeanneboyarsky
    Module 7 - Question 6
    Which is a legal command to run a program


    in a module? (Choose all)


    A. java -p x -m x/x


    B. java -p x-x -m x/x


    C. java -p x -m x-x/x


    D. java -p x -m x/x-x


    E. java -p x -m x.x


    F. java -p x.x -m x.x


    211

    View Slide

  212. @jeanneboyarsky
    Module 7 - Question 7
    Which best fills in the blank?


    module __________
    {

    exports com.unicorn.horn
    ;

    exports com.unicorn.magic
    ;

    }

    A. com


    B. com.unicorn


    C. com.unicorn.horn


    D. The code does not compile


    E. None of these is a good choice


    212

    View Slide

  213. @jeanneboyarsky
    Module 7 - Question 8
    Which is the first to have a compiler error?


    1: module snake
    {

    2: exports com.snake.tail
    ;

    3: exports com.snake.fangs to bird
    ;

    4: requires skin
    ;

    5: requires transitive skin
    ;

    6:
    }

    A. 1


    B. 3


    C. 5


    D. None of the above


    213

    View Slide

  214. @jeanneboyarsky
    Module 7 - Question 9
    Which of the following would be a legal
    module name? (Choose all that apply)


    A. com.book


    B. com-book


    C. com.book$


    D. com-book$


    E. 4com.book


    F. 4com-book
    214

    View Slide

  215. @jeanneboyarsky
    Lab & Break
    215
    See handout

    View Slide

  216. @jeanneboyarsky
    Agenda
    Module Topics
    1 Intro & Changes to Strings
    2 Switch expressions & Pattern matching
    3 Records and Sealed classes
    4 Streams including Collectors.teeing
    5 Localization/Formatting including
    CompactNumberFormatting
    6 I/O including Helpful NullPointers
    7 Modules
    8 Other topics + open Q&A
    216

    View Slide

  217. @jeanneboyarsky
    Lab Review
    • Any questions?


    • Solution review
    217

    View Slide

  218. @jeanneboyarsky
    Using var (Local Variable


    Type Inference)
    218
    String name1 = "Jeanne"
    ;

    var name2 = "Jeanne"
    ;

    List list1 = List.of(1, 2, 3)
    ;

    var list2 = List.of(1, 2, 3)
    ;

    Syntactic sugar/less boilerplate

    View Slide

  219. @jeanneboyarsky
    Can’t change type
    219
    String name = "Jeanne"
    ;

    name = 1; // DOES NOT COMPIL
    E

    View Slide

  220. @jeanneboyarsky
    Not immutable
    220
    String name = "Jeanne"
    ;

    name = "Boyarsky";

    View Slide

  221. @jeanneboyarsky
    Readablity
    221
    List headers =


    thead.findElements(By.tagName("th"))
    ;

    VolunteerDashboardRow headerRow =


    new VolunteerDashboardRow(headers)
    ;

    vs


    var headers = thead.findElements(By.tagName("th"))
    ;

    var headerRow = new VolunteerDashboardRow(headers)
    ;

    View Slide

  222. @jeanneboyarsky
    What types are these?
    222
    var csvPath = createAndGetFile(CSV_DATA)
    ;

    try (var csvWriter = Files.newBufferedWriter(csvPath)
    ;

    var csvPrinter = new CSVPrinter
    (

    csvWriter, CSVFormat.DEFAULT))
    {

    }

    View Slide

  223. @jeanneboyarsky
    Evolution
    223
    Map productMap1 =


    new HashMap()
    ;

    Map productMap2 = new HashMap<>()
    ;

    var productMap3 = new HashMap()
    ;

    View Slide

  224. @jeanneboyarsky
    Where can we use?
    224
    var name = "Jeanne"
    ;

    var other = name + 2
    ;

    var list = List.of(1, 2, 3)
    ;

    for (var num : list) {
    }

    View Slide

  225. @jeanneboyarsky
    Where can’t we use?
    225
    var instance = 1
    ;

    class Inner { var bad = "abc";
    }

    public static void main(String[] args)
    {

    var noGood
    ;

    noGood = 4
    ;

    }

    What’s wrong?

    View Slide

  226. @jeanneboyarsky
    Does this work?
    226
    var var = "var"
    ;

    Yes, but please don’t!

    View Slide

  227. @jeanneboyarsky
    Tradeoffs
    227
    Pros Cons
    Less typing Loss of information
    Less redundancy Variable names


    matter more
    Can scan variable names Be careful!
    http://openjdk.java.net/projects/amber/LVTIstyle.html

    View Slide

  228. @jeanneboyarsky
    Lambdas
    228
    Predicate pred1 = p -> true
    ;

    Predicate pred2 = (String p) -> true
    ;

    Predicate pred3 = (var p) -> true
    ;

    View Slide

  229. @jeanneboyarsky
    Annotations
    229
    BiPredicate, List> func
    =

    (@NotNull var map, var list) -> true
    ;

    View Slide

  230. @jeanneboyarsky
    All or nothing
    230
    // goo
    d

    BiPredicate, Boolean> bi1
    =

    (var map, var list) -> true
    ;

    // ba
    d

    BiPredicate, Boolean> bi2
    =

    (var map, list) -> true
    ;

    BiPredicate, Boolean> bi3
    =

    (var map, List list) -> true
    ;

    View Slide

  231. @jeanneboyarsky
    Effectively final
    If typed final before param/local
    variable, would it still compile?
    231

    View Slide

  232. @jeanneboyarsky
    Which are effectively final?
    232
    int numChairs = 4
    ;

    int numLegs = numChairs * 4
    ;

    numChairs++
    ;

    System.out.println(numChairs)
    ;

    Just numLegs

    View Slide

  233. @jeanneboyarsky
    Original code
    233
    Path path = Paths.get("file")
    ;

    try (BufferedReader reader
    =

    Files.newBufferedReader(path))
    {

    // read fil
    e

    }

    View Slide

  234. @jeanneboyarsky
    With var
    234
    var path = Paths.get("file")
    ;

    try (var reader = Files.newBufferedReader(path))
    {

    // read fil
    e

    }

    View Slide

  235. @jeanneboyarsky
    Before try
    235
    var path = Paths.get("file")
    ;

    var reader = Files.newBufferedReader(path)
    ;

    try (reader)
    {

    // read fil
    e

    }

    Works because path is effectively final

    View Slide

  236. @jeanneboyarsky
    What’s wrong here?
    236
    Connection con
    =

    DriverManager.getConnection(url)
    ;

    PreparedStatement ps
    =

    con.prepareStatement(sql)
    ;

    ps.setInt(1, id)
    ;

    ResultSet rs = ps.executeQuery()
    ;

    try (con; ps; rs)
    {

    while (rs.next())
    {

    // process result se
    t

    }

    }

    Resource leak!

    View Slide

  237. @jeanneboyarsky
    Module 8 - Question 1
    Which are true if the resources are
    ResultSets?


    try (rs1, rs2)
    {

    }

    A. rs1 is closed before rs2


    B. rs2 is closed before rs1


    C. Neither is closed since declared before try


    D. The code does not compile


    237

    View Slide

  238. @jeanneboyarsky
    Module 8 - Question 2
    Which are true if the resources are
    ResultSets?


    try (rs1; rs2)
    {

    }

    A. rs1 is closed before rs2


    B. rs2 is closed before rs1


    C. Neither is closed since declared before try


    D. The code does not compile


    238

    View Slide

  239. @jeanneboyarsky
    Module 8 - Question 3
    What is the result of the following?


    var a = 1
    ;

    var b = a
    ;

    int c = b
    ;

    System.out.println(c)
    ;

    A. a does not compile


    B. b does not compile


    C. c does not compile


    D. 1


    E. None of the above


    239

    View Slide

  240. @jeanneboyarsky
    Module 8 - Question 4
    What is the result of the following?


    var a = 1
    ;

    var b = a
    ;

    double c = b
    ;

    System.out.println(c)
    ;

    A. a does not compile


    B. b does not compile


    C. c does not compile


    D. 1.0


    E. None of the above


    240

    View Slide

  241. @jeanneboyarsky
    Module 8 - Question 5
    What is the result of the following?


    var path = Paths.get("file")
    ;

    var reader = Files.newBufferedReader(path)
    ;

    reader = Files.newBufferedReader(path)
    ;

    try(reader)
    {

    // read fil
    e

    }

    A. reader is closed


    B. reader remains open


    C. None; the code does not compile
    241

    View Slide

  242. @jeanneboyarsky
    Module 8 - Question 6
    What is the result of the following?


    var a = 1
    ;

    var b = a
    ;

    String c = b
    ;

    System.out.println(c)
    ;

    A. a does not compile


    B. b does not compile


    C. c does not compile


    D. 1


    E. None of the above


    242

    View Slide

  243. @jeanneboyarsky
    Module 8 - 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


    243

    View Slide

  244. @jeanneboyarsky
    Module 8 - 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


    244

    View Slide

  245. @jeanneboyarsky
    Module 8 - Question 9
    Which allow using var?


    A. Instance variables


    B. Lambda variables


    C. Static variables


    D. Try with resources
    245

    View Slide

  246. @jeanneboyarsky
    Module 8 - Question 10
    I learned a lot today


    A. True


    B. False
    246

    View Slide

  247. @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""")
    ;

    }

    }

    247
    java17 Fun.java


    Wear 🥽 and 🥼 when using a 🧪

    View Slide

  248. @jeanneboyarsky
    Book Giveaway
    248

    View Slide