├── CNAME ├── LICENSE.txt ├── assets ├── img │ └── cover.jpg ├── js │ └── common-sections.js └── css │ ├── code2.css │ └── style.css ├── .gitignore ├── index.md ├── _includes ├── buy-info.html ├── footer.html ├── head.html ├── header.html ├── changelog.html └── nav.html ├── 404.html ├── _layouts ├── index.html ├── base.html ├── answer.html └── chapter.html ├── README.md ├── Gemfile ├── CONTRIBUTING.md ├── Gemfile.lock ├── _config.yml ├── ch08a.md ├── ch04a.md ├── ch07a.md ├── ch06a.md ├── ch03a.md ├── ch09a.md ├── ch14a.md ├── ch05a.md ├── ch10a.md ├── ch12a.md ├── ch13a.md ├── ch11a.md └── intro.md /CNAME: -------------------------------------------------------------------------------- 1 | ocpj21.javastudyguide.com -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eh3rrera/ocpj21-book/HEAD/LICENSE.txt -------------------------------------------------------------------------------- /assets/img/cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eh3rrera/ocpj21-book/HEAD/assets/img/cover.jpg -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _site 2 | .sass-cache 3 | .jekyll-cache 4 | .jekyll-metadata 5 | vendor 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /index.md: -------------------------------------------------------------------------------- 1 | --- 2 | # Feel free to add content and custom Front Matter to this file. 3 | # To modify the layout, see https://jekyllrb.com/docs/themes/#overriding-theme-defaults 4 | 5 | layout: index 6 | is_index: true 7 | --- 8 | -------------------------------------------------------------------------------- /_includes/buy-info.html: -------------------------------------------------------------------------------- 1 |
2 |

Buying the Kindle version from Amazon

3 |

Buying from other stores

4 |
-------------------------------------------------------------------------------- /404.html: -------------------------------------------------------------------------------- 1 | --- 2 | permalink: /404.html 3 | layout: base 4 | --- 5 | 6 | 18 | 19 |
20 |

404

21 | 22 |

Page not found :(

23 |

The requested page could not be found.

24 |
25 | -------------------------------------------------------------------------------- /_layouts/index.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: base 3 | --- 4 | 5 |
6 |

7 | Read online for free 8 | 9 | {{ content }} 10 | 11 | {% include buy-info.html %} 12 | 13 |

This site is on Github, so you can fork it, modify it, and create pull requests.

14 | 15 |
16 | 17 | {% include changelog.html %} -------------------------------------------------------------------------------- /_layouts/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {% include head.html %} 5 | 6 | 7 | 8 | {% include nav.html %} 9 | 10 | {% if page.is_index %} 11 | 12 |
13 |
14 | {{ content }} 15 |
16 |
17 | {% else %} 18 | {% include header.html %} 19 | 20 |
21 |
22 | {{ content }} 23 |
24 |
25 | {% endif %} 26 | 27 | {% include footer.html %} 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /_layouts/answer.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: base 3 | --- 4 | 5 | 6 | {{ content }} 7 | 8 |
9 |

Do you like what you read? Would you consider?

10 | 11 | {% include buy-info.html %} 12 | 13 |
14 |

Do you have a problem or something to say?

15 |

Report an issue with the book

16 |

Contact me

17 |
-------------------------------------------------------------------------------- /_includes/footer.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /_includes/head.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{ page.title }} 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /assets/js/common-sections.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | $("a.dropdown-desktop").click(function(event) { 3 | showMenu($("div.menu.desktop"), event); 4 | }); 5 | $("a.dropdown-mobile").click(function(event) { 6 | showMenu($("div.menu.mobile"), event); 7 | }); 8 | 9 | // Close the menu when clicking anywhere on the screen 10 | $(document).click(function(event) { 11 | $("div.menu").removeClass("open"); 12 | }); 13 | 14 | // Prevent closing the menu when clicking inside it 15 | $("div.menu").click(function(event) { 16 | event.stopPropagation(); 17 | }); 18 | 19 | function showMenu(el, event) { 20 | event.preventDefault(); 21 | event.stopPropagation(); // Stop propagation to document 22 | el.toggleClass("open"); 23 | } 24 | }); -------------------------------------------------------------------------------- /_includes/header.html: -------------------------------------------------------------------------------- 1 | {% if page.is_intro %} 2 |
3 |
4 |
5 | 6 |

{{ page.title }}

7 | 8 |
9 |
10 |
11 | {% else %} 12 |
13 |
14 |
15 | 16 |

{{ page.title }}
17 | 18 | {% if page.exam_objectives %} 19 | {{ page.subtitle }}

20 | 21 |


22 | 23 |

Exam Objectives

24 |

25 | {% for objective in page.exam_objectives %} 26 | {{ objective }}
27 | {% endfor %} 28 |

29 | {% else %} 30 | 31 | {% endif %} 32 | 33 |
34 |
35 |
36 | {% endif %} 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java SE 21 Developer Study Guide 2 | Study guide for the Java SE 21 Developer Exam (1Z0-830). 3 | 4 | # Buying 5 | You can read the book for free [here](http://ocpj21.javastudyguide.com/), but if you like the content and want to support me, you can buy the print and e-book version: 6 | 7 | SOON... 8 | 9 | # Contributing 10 | Any contributions are welcomed. Please have a look at [CONTRIBUTING.md](https://github.com/eh3rrera/ocpj21-book/blob/master/CONTRIBUTING.md). 11 | 12 | 13 | # License 14 | ©2024 by Esteban Herrera 15 | 16 | Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. 17 | 18 | Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. -------------------------------------------------------------------------------- /_includes/changelog.html: -------------------------------------------------------------------------------- 1 |

Changelog

2 |

September 26, 2025

3 |

Fix error in chapter 13 about unnamed and automatic modules. Thanks to https://github.com/Alchemik

4 | 5 |

August 31, 2025

6 |

Fix errors in chapters 3 and 5. Thanks to https://github.com/Alchemik

7 | 8 |

March 24, 2025

9 |

Fix output of example of Function in chapter 8. Thanks to https://github.com/UninspiredNickname

10 | 11 |

April 21, 2025

12 |

Improve operator precedence table in chapter 4.

13 | 14 |

March 24, 2025

15 |

Fix typo in question 5 of chapter 7. Thanks to https://github.com/rjuric-tn

16 | 17 |

February 13, 2025

18 |

Fix errors in chapters 4 and 11.

19 | 20 |

August 09, 2024

21 |

First version.

-------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | # Hello! This is where you manage which Jekyll version is used to run. 3 | # When you want to use a different version, change it below, save the 4 | # file and run `bundle install`. Run Jekyll with `bundle exec`, like so: 5 | # 6 | # bundle exec jekyll serve 7 | # 8 | # This will help ensure the proper Jekyll version is running. 9 | # Happy Jekylling! 10 | gem "jekyll", "~> 4.3.2" 11 | # If you want to use GitHub Pages, remove the "gem "jekyll"" above and 12 | # uncomment the line below. To upgrade, run `bundle update github-pages`. 13 | # gem "github-pages", group: :jekyll_plugins 14 | # If you have any plugins, put them here! 15 | group :jekyll_plugins do 16 | gem "jekyll-feed", "~> 0.12" 17 | end 18 | 19 | # Windows and JRuby does not include zoneinfo files, so bundle the tzinfo-data gem 20 | # and associated library. 21 | platforms :mingw, :x64_mingw, :mswin, :jruby do 22 | gem "tzinfo", ">= 1", "< 3" 23 | gem "tzinfo-data" 24 | end 25 | 26 | # Performance-booster for watching directories on Windows 27 | gem "wdm", "~> 0.1.1", :platforms => [:mingw, :x64_mingw, :mswin] 28 | 29 | # Lock `http_parser.rb` gem to `v0.6.x` on JRuby builds since newer versions of the gem 30 | # do not have a Java counterpart. 31 | gem "http_parser.rb", "~> 0.6.0", :platforms => [:jruby] 32 | 33 | gem "rouge", "~> 4.2" 34 | -------------------------------------------------------------------------------- /assets/css/code2.css: -------------------------------------------------------------------------------- 1 | div.highlight { 2 | border: 1px solid #ccc; 3 | } 4 | 5 | .highlight { 6 | display: block; 7 | overflow-x: auto; 8 | padding: 0.1em; 9 | background: #eee; 10 | color: black; 11 | padding: 1px 10px; 12 | -webkit-text-size-adjust: none; 13 | } 14 | .highlight .c, 15 | .highlight .cm, 16 | .highlight .c1, 17 | .highlight .cs { color: #006a00; } /* Comment */ 18 | 19 | .highlight .err { border: 1px solid #FF0000 } /* Error */ 20 | 21 | .highlight .k, 22 | .highlight .kc, 23 | .highlight .kd, 24 | .highlight .kn, 25 | .highlight .kp, 26 | .highlight .kr { color: #aa0d91; } /* Keyword */ 27 | 28 | .highlight .ge { font-style: italic } /* Generic.Emph */ 29 | .highlight .gh { font-weight: bold } /* Generic.Heading */ 30 | .highlight .gp { font-weight: bold } /* Generic.Prompt */ 31 | .highlight .gs { font-weight: bold } /* Generic.Strong */ 32 | .highlight .gu { font-weight: bold } /* Generic.Subheading */ 33 | 34 | .highlight .kt { color: #5c2699; } /* Keyword.Type */ 35 | 36 | .highlight .s, 37 | .highlight .sb, 38 | .highlight .sc, 39 | .highlight .sd, 40 | .highlight .s2, 41 | .highlight .se, 42 | .highlight .sh, 43 | .highlight .si, 44 | .highlight .sx, 45 | .highlight .sr, 46 | .highlight .s1, 47 | .highlight .ss { color: #c41a16; } /* Literal.String */ 48 | 49 | .highlight .nc { color: #1c00cf; } /* Name.Class */ 50 | 51 | .highlight .ow { color: #0000ff; } /* Operator.Word */ 52 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Any contributions like typo corrections, added review questions, added explanations, translations, etc. are greatly appreciated. 3 | 4 | However, if you choose to contribute something more than typo corrections, in addition to the terms of the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](http://creativecommons.org/licenses/by-nc-sa/4.0/) license, you agree to give me a non-exclusive license to use that content for the book as I deem appropriate. 5 | 6 | # Translations 7 | We may be accustomed to using English every day, but language can be a real problem for some people. 8 | 9 | You can help everyone a lot by translating the book into your own language. However, I don't think it would be fair for me or someone else to make money off your effort, so every translation must be licensed under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](http://creativecommons.org/licenses/by-nc-sa/4.0/) license to make it free for everybody. 10 | 11 | If you agree with that, here are some guidelines: 12 | - Use the English version as a source for your translation. 13 | - Open a new issue indicating the language and the chapters you wish to translate. 14 | - Create a directory in the root of the project for your language (if there's none yet), and put your translation there. 15 | - Try to remain as close to the original text as possible, but also, feel free to adapt the text so it feels natural in your language. 16 | - If you have any questions, don't hesitate to contact me. 17 | -------------------------------------------------------------------------------- /_layouts/chapter.html: -------------------------------------------------------------------------------- 1 | --- 2 | layout: base 3 | --- 4 | 5 | 6 | {{ content }} 7 | 8 | {% unless page.is_intro %} 9 | {% if page.answers_link %} 10 |
11 | Open answers page 12 |
13 | {% endif %} 14 | {% endunless %} 15 | 16 |
17 |

Do you like what you read? Would you consider?

18 | 19 | {% include buy-info.html %} 20 | 21 |
22 |

Do you have a problem or something to say?

23 |

Report an issue with the book

24 |

Contact me

25 |
26 | 27 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | addressable (2.8.6) 5 | public_suffix (>= 2.0.2, < 6.0) 6 | colorator (1.1.0) 7 | concurrent-ruby (1.2.2) 8 | em-websocket (0.5.3) 9 | eventmachine (>= 0.12.9) 10 | http_parser.rb (~> 0) 11 | eventmachine (1.2.7) 12 | ffi (1.16.3) 13 | forwardable-extended (2.6.0) 14 | google-protobuf (3.25.1-x86_64-darwin) 15 | http_parser.rb (0.8.0) 16 | i18n (1.14.1) 17 | concurrent-ruby (~> 1.0) 18 | jekyll (4.3.2) 19 | addressable (~> 2.4) 20 | colorator (~> 1.0) 21 | em-websocket (~> 0.5) 22 | i18n (~> 1.0) 23 | jekyll-sass-converter (>= 2.0, < 4.0) 24 | jekyll-watch (~> 2.0) 25 | kramdown (~> 2.3, >= 2.3.1) 26 | kramdown-parser-gfm (~> 1.0) 27 | liquid (~> 4.0) 28 | mercenary (>= 0.3.6, < 0.5) 29 | pathutil (~> 0.9) 30 | rouge (>= 3.0, < 5.0) 31 | safe_yaml (~> 1.0) 32 | terminal-table (>= 1.8, < 4.0) 33 | webrick (~> 1.7) 34 | jekyll-feed (0.17.0) 35 | jekyll (>= 3.7, < 5.0) 36 | jekyll-sass-converter (3.0.0) 37 | sass-embedded (~> 1.54) 38 | jekyll-watch (2.2.1) 39 | listen (~> 3.0) 40 | kramdown (2.4.0) 41 | rexml 42 | kramdown-parser-gfm (1.1.0) 43 | kramdown (~> 2.0) 44 | liquid (4.0.4) 45 | listen (3.8.0) 46 | rb-fsevent (~> 0.10, >= 0.10.3) 47 | rb-inotify (~> 0.9, >= 0.9.10) 48 | mercenary (0.4.0) 49 | pathutil (0.16.2) 50 | forwardable-extended (~> 2.6) 51 | public_suffix (5.0.4) 52 | rb-fsevent (0.11.2) 53 | rb-inotify (0.10.1) 54 | ffi (~> 1.0) 55 | rexml (3.2.6) 56 | rouge (4.2.0) 57 | safe_yaml (1.0.5) 58 | sass-embedded (1.69.5-x86_64-darwin) 59 | google-protobuf (~> 3.23) 60 | terminal-table (3.0.2) 61 | unicode-display_width (>= 1.1.1, < 3) 62 | unicode-display_width (2.5.0) 63 | webrick (1.8.1) 64 | 65 | PLATFORMS 66 | x86_64-darwin-20 67 | 68 | DEPENDENCIES 69 | http_parser.rb (~> 0.6.0) 70 | jekyll (~> 4.3.2) 71 | jekyll-feed (~> 0.12) 72 | rouge (~> 4.2) 73 | tzinfo (>= 1, < 3) 74 | tzinfo-data 75 | wdm (~> 0.1.1) 76 | 77 | BUNDLED WITH 78 | 2.2.3 79 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | # Welcome to Jekyll! 2 | # 3 | # This config file is meant for settings that affect your whole blog, values 4 | # which you are expected to set up once and rarely edit after that. If you find 5 | # yourself editing this file very often, consider using Jekyll's data files 6 | # feature for the data you need to update frequently. 7 | # 8 | # For technical reasons, this file is *NOT* reloaded automatically when you use 9 | # 'bundle exec jekyll serve'. If you change this file, please restart the server process. 10 | # 11 | # If you need help with YAML syntax, here are some quick references for you: 12 | # https://learn-the-web.algonquindesign.ca/topics/markdown-yaml-cheat-sheet/#yaml 13 | # https://learnxinyminutes.com/docs/yaml/ 14 | # 15 | # Site settings 16 | # These are used to personalize your new site. If you look in the HTML files, 17 | # you will see them accessed via {{ site.title }}, {{ site.email }}, and so on. 18 | # You can create any custom variable you would like, and they will be accessible 19 | # in the templates via {{ site.myvariable }}. 20 | 21 | title: Study guide for the Oracle Certified Professional, Java SE 21 Developer Exam 22 | email: your-email@example.com 23 | description: >- # this means to ignore newlines until "baseurl:" 24 | Study guide for the Java SE 21 Developer Professional Exam (1Z0-830) 25 | baseurl: "" # the subpath of your site, e.g. /blog 26 | url: "" # the base hostname & protocol for your site, e.g. http://example.com 27 | twitter_username: eh3rrera 28 | github_username: eh3rrera 29 | 30 | highlighter: rouge 31 | 32 | # Build settings 33 | #theme: minima 34 | #plugins: 35 | # - jekyll-feed 36 | 37 | # Exclude from processing. 38 | # The following items will not be processed, by default. 39 | # Any item listed under the `exclude:` key here will be automatically added to 40 | # the internal "default list". 41 | # 42 | # Excluded items can be processed by explicitly listing the directories or 43 | # their entries' file path in the `include:` list. 44 | # 45 | # exclude: 46 | # - .sass-cache/ 47 | # - .jekyll-cache/ 48 | # - gemfiles/ 49 | # - Gemfile 50 | # - Gemfile.lock 51 | # - node_modules/ 52 | # - vendor/bundle/ 53 | # - vendor/cache/ 54 | # - vendor/gems/ 55 | # - vendor/ruby/ 56 | -------------------------------------------------------------------------------- /_includes/nav.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ch08a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter EIGHT" 5 | subtitle: "Functional Interfaces and Lambda Expressions" 6 | exam_objectives: 7 | - "Use Java object and primitive Streams, including lambda expressions implementing functional interfaces, to create, filter, transform, process, and sort data." 8 | --- 9 | 10 | ## Answers 11 | **1. The correct answers are B and D.** 12 | 13 | **Explanation:** 14 | 15 | - **A)** A functional interface can have multiple `abstract` methods. 16 | - This option is incorrect. A functional interface can have only one abstract method. Having multiple abstract methods would disqualify it from being a functional interface. 17 | 18 | - **B)** A functional interface can have default and `static` methods. 19 | - This option is correct. A functional interface is allowed to have default and static methods, which are not counted as abstract methods. 20 | 21 | - **C)** The `@FunctionalInterface` annotation is mandatory to declare a functional interface. 22 | - This option is incorrect. The `@FunctionalInterface` annotation is not mandatory; it is only a marker to indicate that the interface is intended to be a functional interface. An interface can be a functional interface without this annotation as long as it has exactly one abstract method. 23 | 24 | - **D)** Lambda expressions can be used to instantiate functional interfaces. 25 | - This option is correct. Lambda expressions are used to provide implementations for the single abstract method of a functional interface, making them a key feature for functional programming in Java. 26 | 27 | 28 | **2. The correct answer is A.** 29 | 30 | **Explanation:** 31 | 32 | - **A)** `(s1, s2) -> s1.compareTo(s2)` 33 | - This option is correct. This lambda expression correctly implements the `Comparator` interface. It uses the correct syntax for a lambda expression, with parameters enclosed in parentheses and a single expression for the body. 34 | 35 | - **B)** `(String s1, s2) -> s1.compareTo(s2)` 36 | - This option is incorrect. The syntax is invalid because if you specify the type of one parameter, you must specify the type for all parameters. It should be `(String s1, String s2)`. 37 | 38 | - **C)** `s1, s2 -> s1.compareTo(s2)` 39 | - This option is incorrect. Parameters must be enclosed in parentheses. The correct syntax is `(s1, s2)`. 40 | 41 | - **D)** `(s1, s2) -> return s1.compareTo(s2);` 42 | - This option is incorrect. When using a return statement, you must also include curly braces. 43 | 44 | - **E)** `(s1, s2) -> { s1.compareTo(s2); }` 45 | - This option is incorrect. When using curly braces, you must include a return statement for expressions that return a value. The correct syntax would be `(s1, s2) -> { return s1.compareTo(s2); }`. 46 | 47 | 48 | **3. The correct answer is B.** 49 | 50 | **Explanation:** 51 | 52 | - **A)** `java.util.function.Function` 53 | - This option is incorrect. `Function` represents a function that takes one argument and produces a result. 54 | 55 | - **B)** `java.util.function.BiFunction` 56 | - This option is correct. `BiFunction` represents a function that takes two arguments and produces a result. 57 | 58 | - **C)** `java.util.function.Supplier` 59 | - This option is incorrect. `Supplier` represents a function that takes no arguments and produces a result. 60 | 61 | - **D)** `java.util.function.Consumer` 62 | - This option is incorrect. `Consumer` represents a function that takes one argument and does not produce a result. 63 | 64 | - **E)** `java.util.function.Predicate` 65 | - This option is incorrect. `Predicate` represents a function that takes one argument and returns a `boolean` value. 66 | 67 | 68 | **4. The correct answer is A.** 69 | 70 | **Explanation:** 71 | 72 | - **A)** `13` 73 | - This option is correct. The `combinedFunction` first multiplies 5 by 2 to get 10, then adds 3, resulting in 13. 74 | 75 | - **B)** `16` 76 | - This option is incorrect. It incorrectly assumes that 5 is added after doubling and doubling again. 77 | 78 | - **C)** `10` 79 | - This option is incorrect. It represents only the result of the first function without applying the second function. 80 | 81 | - **D)** `11` 82 | - This option is incorrect. It seems to mistakenly represent 5 plus the first function (double). 83 | 84 | - **E)** `8` 85 | - This option is incorrect. It seems to incorrectly represent the input value doubled without adding 3. 86 | 87 | 88 | 89 | **5. The correct answer is C.** 90 | 91 | **Explanation:** 92 | 93 | - **A)** `String::valueOf` 94 | - This option is incorrect. `String::valueOf` converts an integer to a string, not a string to an integer. 95 | 96 | - **B)** `Integer::valueOf` 97 | - This option is incorrect. `Integer::valueOf` returns an `Integer` object, while the lambda returns an `int`. 98 | 99 | - **C)** `Integer::parseInt` 100 | - This option is correct. `Integer::parseInt` is a method reference that matches the lambda expression `str -> Integer.parseInt(str)` which converts a string to an integer. 101 | 102 | - **D)** `String::parseInt` 103 | - This option is incorrect. `String` class does not have a `parseInt` method. 104 | 105 | - **E)** `Integer::toString` 106 | - This option is incorrect. `Integer::toString` converts an integer to a string, not a string to an integer. 107 | 108 | -------------------------------------------------------------------------------- /ch04a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter FOUR" 5 | subtitle: "Working with Data" 6 | exam_objectives: 7 | - "Use primitives and wrapper classes. Evaluate arithmetic and boolean expressions, using the Math API and by applying precedence rules, type conversions, and casting." 8 | - "Manipulate text, including text blocks, using String and StringBuilder classes." 9 | --- 10 | 11 | ## Answers 12 | **1. The correct answer is C.** 13 | 14 | **Explanation:** 15 | 16 | - **A)** A `double` can be directly assigned to a `float` without casting. 17 | - This option is incorrect. A `double` cannot be directly assigned to a `float` without casting because `double` has a larger range and precision than a `float`. 18 | 19 | - **B)** A `boolean` can be cast to an `int`. 20 | - This option is incorrect. `boolean` values cannot be cast to `int` in Java. They are not compatible types. 21 | 22 | - **C)** A `String` can be assigned to an `Object` reference variable. 23 | - This option is correct. A `String` is an instance of the `Object` class, and hence it can be assigned to an `Object` reference variable. 24 | 25 | - **D)** A `char` is a reference data type. 26 | - This option is incorrect. `char` is a primitive data type, not a reference data type. 27 | 28 | - **E)** An `int` can store a `long` value without any explicit casting. 29 | - This option is incorrect. an `int` cannot store a `long` value without explicit casting because `long` has a larger range than `int`. 30 | 31 | 32 | **2. The correct answer is A.** 33 | 34 | **Explanation:** 35 | 36 | Let's break down the expression `a + b * c / a - b` step-by-step according to the order of operations: 37 | 38 | 1. **Multiplication and Division** are performed first from left to right: 39 | - `b * c` = `10 * 15` = `150` 40 | - `150 / a` = `150 / 5` = `30` 41 | 42 | 2. **Addition and Subtraction** are performed next from left to right: 43 | - `a + 30` = `5 + 30` = `35` 44 | - `35 - b` = `35 - 10` = `25` 45 | 46 | So, the value of `result` is `25`, and the program prints `25`. 47 | 48 | - **A)** `25` 49 | - This option is correct. 50 | 51 | - **B)** `35` 52 | - This option is incorrect. 53 | 54 | - **C)** `20` 55 | - This option is incorrect. 56 | 57 | - **D)** `15` 58 | - This option is incorrect. 59 | 60 | 61 | **3. The correct answer is D.** 62 | 63 | **Explanation:** 64 | 65 | - **A)** `StringBuilder` objects are immutable. 66 | - This option is incorrect. `StringBuilder` objects are mutable, meaning they can be changed after they are created. 67 | 68 | - **B)** `String` objects can be modified after they are created. 69 | - This option is incorrect. `String` objects are immutable, meaning once a `String` object is created, it cannot be modified. Any modification results in a new `String` object. 70 | 71 | - **C)** `StringBuilder` is synchronized and thread-safe. 72 | - This option is incorrect. `StringBuilder` is not synchronized and is not thread-safe. If synchronization is required, `StringBuffer` should be used instead. 73 | 74 | - **D)** `StringBuilder` provides methods for mutable sequence of characters. 75 | - This option is correct. `StringBuilder` provides methods for a mutable sequence of characters, allowing for modification of the object without creating new instances. 76 | 77 | - **E)** `String` and `StringBuilder` have the same performance characteristics for string manipulation. 78 | - This option is incorrect. `String` and `StringBuilder` do not have the same performance characteristics for string manipulation. `StringBuilder` is generally more efficient for such operations because it is mutable and does not create new instances with each modification. 79 | 80 | 81 | **4. The correct answers are A and B.** 82 | 83 | **Explanation:** 84 | 85 | - **A)** Text blocks can span multiple lines without needing escape sequences for new lines. 86 | - This option is correct. Text blocks can indeed span multiple lines without needing escape sequences for new lines, making it easier to work with multi-line strings. 87 | 88 | 89 | - **B)** Text blocks preserve the exact format, including whitespace, of the code as written. 90 | - This option is correct. Text blocks preserve the exact format, including whitespace, of the code as written. This is useful for maintaining the original layout of the text. 91 | 92 | 93 | - **C)** Text blocks can only be used within methods. 94 | - This option is incorrect. Text blocks can be used anywhere a regular `String` can be used, not just within methods. They can be part of class fields, method parameters, etc. 95 | 96 | 97 | - **D)** Text blocks automatically trim leading and trailing whitespace from each line. 98 | - This option is incorrect. Text blocks do not automatically trim leading and trailing whitespace from each line. They preserve the exact whitespace as written in the code. 99 | 100 | - **E)** Text blocks require a minimum indentation level of one space. 101 | - This option is incorrect. Text blocks do not require a minimum indentation level of one space. The leading indentation common to all lines is removed automatically, but lines within the text block can have zero or more leading spaces. 102 | 103 | 104 | **5. The correct answer is D.** 105 | 106 | **Explanation:** 107 | 108 | - **A)** The `Math.round()` method returns a `double`. 109 | - This option is incorrect. The `Math.round()` method returns a `long` when given a `double` argument and an `int` when given a `float` argument. 110 | 111 | - **B)** The `Math.random()` method returns a random integer. 112 | - This option is incorrect. The `Math.random()` method returns a `double` value between 0.0 (inclusive) and 1.0 (exclusive). 113 | 114 | - **C)** The `Math.max()` method can only be used with integers. 115 | - This option is incorrect. The `Math.max()` method can be used with various numeric types, including `int`, `long`, `float`, and `double`. 116 | 117 | - **D)** The `Math.pow()` method returns the result of raising the first argument to the power of the second argument. 118 | - This option is correct. The `Math.pow()` method returns the result of raising the first argument to the power of the second argument. Both arguments are of type `double`. 119 | 120 | - **E)** The `Math.abs()` method can only be used with positive numbers. 121 | - This option is incorrect. The `Math.abs()` method can be used with negative numbers to return their absolute value, and it works with various numeric types including `int`, `long`, `float`, and `double`. -------------------------------------------------------------------------------- /ch07a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter SEVEN" 5 | subtitle: "Error Handling and Exceptions" 6 | exam_objectives: 7 | - "Handle exceptions using try/catch/finally, try-with-resources, and multi-catch blocks, including custom exceptions." 8 | --- 9 | 10 | ## Answers 11 | **1. The correct answer is B.** 12 | 13 | **Explanation:** 14 | 15 | - **A.** A checked exception is a type of exception that inherits from the `java.lang.RuntimeException` class. 16 | - This option is incorrect. A checked exception does not inherit from `java.lang.RuntimeException`. Checked exceptions are subclasses of `java.lang.Exception` but not of `java.lang.RuntimeException`. 17 | 18 | - **B.** A checked exception must be either caught or declared in the method signature using the `throws` keyword. 19 | - This option is correct. Checked exceptions must be either caught using a `try-catch` block or declared in the method signature with the `throws` keyword. This is to ensure that the exception is properly handled at some point in the code. 20 | 21 | - **C.** A checked exception is an error that is typically caused by the environment in which the application is running, and it cannot be handled by the application. 22 | - This option is incorrect. It describes errors more accurately than checked exceptions. Errors are typically caused by the environment and are not expected to be handled by the application. 23 | 24 | - **D.** A checked exception can be thrown by the Java Virtual Machine when a severe error occurs, such as an out-of-memory error. 25 | - This option is incorrect. It describes errors rather than checked exceptions. Errors like out-of-memory errors are thrown by the JVM and are not meant to be caught or handled by applications in most cases. 26 | 27 | 28 | **2. The correct answer is A.** 29 | 30 | **Explanation:** 31 | 32 | - **A.** This code defines a custom checked exception and correctly throws and handles it. 33 | - This option is correct. The code defines a custom checked exception by extending `Exception`. The `methodThatThrowsException` method throws this custom exception, which is then caught and handled in the `main` method. 34 | 35 | - **B.** This code defines a custom unchecked exception. 36 | - This option is incorrect. The code extends `Exception`, not `RuntimeException`, making it a checked exception rather than an unchecked one. 37 | 38 | - **C.** This code will not compile because the custom exception is not declared correctly in the method signature. 39 | - This option is incorrect. The custom exception is correctly declared in the method signature of `methodThatThrowsException`, so it will compile without issues. 40 | 41 | - **D.** This code will compile but will not throw the custom exception at runtime. 42 | - This option is incorrect. The code will throw the custom exception at runtime as expected, and it will be caught and handled in the `catch` block. 43 | 44 | 45 | **3. The correct answer is B.** 46 | 47 | **Explanation:** 48 | 49 | - **A.** `1` 50 | - This option is incorrect. Although the `catch` block returns `1`, the `finally` block will override this return value with `2`. 51 | 52 | - **B.** `2` 53 | - This option is correct. The `finally` block always executes and its return value overrides the return value from the `catch` block, resulting in `2` being printed. 54 | 55 | - **C.** Compilation fails 56 | - This option is incorrect. The code compiles without any errors. 57 | 58 | - **D.** An exception occurs at runtime 59 | - This option is incorrect. While a `RuntimeException` is thrown in the `try` block, it is caught by the `catch` block, and no exception propagates to cause a runtime error. 60 | 61 | 62 | **4. The correct answer is D.** 63 | 64 | **Explanation:** 65 | 66 | - **A.** The code doesn't compile correctly. 67 | - This option is incorrect. The code does compile correctly. A `try` block can be followed by a `finally` block without a `catch` block. 68 | 69 | - **B.** The code would compile correctly if we add a `catch` block. 70 | - This option is incorrect. While adding a `catch` block is valid, it is not necessary for the code to compile. The `try` block can be used with only a `finally` block. 71 | 72 | - **C.** The code would compile correctly if we remove the `finally` block. 73 | - This option is incorrect. Removing the `finally` block is not necessary for the code to compile. The code is valid with the `finally` block present. 74 | 75 | - **D.** The code compiles correctly as it is. 76 | - This option is correct. The code compiles correctly as it is. A `try` block must be followed by either a `catch` block, a `finally` block, or both. 77 | 78 | 79 | **5. The correct answers are C and D.** 80 | 81 | **Explanation:** 82 | 83 | - **A.** In a `try-with-resources`, the `catch` block is required. 84 | - This option is incorrect. In a `try-with-resources` statement, the catch block is optional. The primary purpose of `try-with-resources` is to ensure that each resource is closed at the end of the statement, whether an exception is thrown or not. 85 | 86 | - **B.** The `throws` keyword is used to throw an exception. 87 | - This option is incorrect. The `throws` keyword is used in method declarations to specify that the method can throw an exception, not to throw an exception. The `throw` keyword is used to actually throw an exception. 88 | 89 | - **C.** In a `try-with-resources` block, if you declare more than one resource, they have to be separated by a semicolon. 90 | - This option is correct. In a `try-with-resources` block, if you declare more than one resource, they must be separated by a semicolon. 91 | 92 | - **D.** If a `catch` block is defined for an exception that couldn't be thrown by the code in the `try` block, a compile-time error is generated. 93 | - This option is correct. If a `catch` block is defined for an exception that cannot be thrown by the code in the `try` block, the compiler will generate an error because the `catch` block is unreachable. 94 | 95 | 96 | **6. The correct answer is E.** 97 | 98 | **Explanation:** 99 | 100 | - **A.** `Close Exception` 101 | - This option is incorrect. While the `IOException` from `close()` will occur, it will be suppressed by the `RuntimeException`. 102 | 103 | - **B.** `RuntimeException` 104 | - This option is incorrect. The primary exception is `RuntimeException`, but it will not print its message directly because the catch block does not handle it. 105 | 106 | - **C.** `RuntimeException` and then `CloseException` 107 | - This option is incorrect. Although both exceptions occur, the `RuntimeException` is primary, and the `IOException` is suppressed. Both messages are not printed in sequence. 108 | 109 | - **D.** Compilation fails 110 | - This option is incorrect. The code compiles without any errors. 111 | 112 | - **E.** The stack trace of an uncaught exception is printed. 113 | - This option is correct. The `RuntimeException` thrown in the try block is not caught by the `catch (IOException e)` block. Hence, the stack trace of the `RuntimeException` is printed. 114 | 115 | 116 | **7. The correct answers are B and C.** 117 | 118 | **Explanation:** 119 | 120 | - **A.** `java.io.FileNotFoundException` is incorrect. It is a subclass of `java.io.IOException`, which in turn is a subclass of `java.lang.Exception`, making it a checked exception. 121 | 122 | - **B.** `java.lang.ArithmeticException` is correct. It is a direct subclass of `java.lang.RuntimeException` and represents arithmetic errors such as division by zero. 123 | 124 | - **C.** `java.lang.ClassCastException` is correct. It is a direct subclass of `java.lang.RuntimeException` and indicates an invalid cast operation. 125 | 126 | - **D.** `java.lang.InterruptedException` is incorrect. It is a direct subclass of `java.lang.Exception`, making it a checked exception. It indicates that a thread has been interrupted. 127 | 128 | 129 | **8. The correct answer is D.** 130 | 131 | **Explanation:** 132 | 133 | - **A.** Only `"Try Block Exception"` is printed. 134 | - This option is incorrect. The `Try Block Exception` is the main exception and is not directly printed because the `catch` block checks for suppressed exceptions first. 135 | 136 | - **B.** Only `"Close Exception"` is printed. 137 | - This option is incorrect. The `Close Exception` is not directly printed; it is suppressed and accessed via the `getSuppressed` method. 138 | 139 | - **C.** Both `"Try Block Exception"` and `"Close Exception"` are printed. 140 | - This option is incorrect. The code only prints suppressed exceptions, not the main exception message directly. 141 | 142 | - **D.** `"Suppressed: Close Exception"` is printed. 143 | - This option is correct. The `RuntimeException` thrown in the `try` block is the main exception, and the `RuntimeException` from the `close` method is suppressed. The `catch` block prints the suppressed exception message, `"Suppressed: Close Exception"`. -------------------------------------------------------------------------------- /ch06a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter SIX" 5 | subtitle: "Arrays, Generics, and Collections" 6 | exam_objectives: 7 | - "Create arrays, List, Set, Map and Deque collections, and add, remove, update, retrieve and sort their elements." 8 | --- 9 | 10 | ## Answers 11 | **1. The correct answer is D.** 12 | 13 | **Explanation:** 14 | 15 | - **A)** 16 | ``` 17 | 0 0 0 18 | 0 0 0 19 | ``` 20 | - This option is incorrect because the array elements are initialized and modified within the loops. The values are not all zeros. 21 | 22 | - **B)** 23 | ``` 24 | 0 1 2 25 | 0 1 2 26 | ``` 27 | - This option is incorrect because each row is initialized with incremental values based on the sum of indices, not identical for both rows. 28 | 29 | - **C)** 30 | ``` 31 | 0 0 0 32 | 1 1 1 33 | ``` 34 | - This option is incorrect because the values should be the sum of the row index and the column index, not all zeros or all ones for the second row. 35 | 36 | - **D)** 37 | ``` 38 | 0 1 2 39 | 1 2 3 40 | ``` 41 | - This is the correct answer. Each element of the array is set to the sum of its indices. So, `arr[0][0] = 0 + 0 = 0`, `arr[0][1] = 0 + 1 = 1`, `arr[0][2] = 0 + 2 = 2`, `arr[1][0] = 1 + 0 = 1`, `arr[1][1] = 1 + 1 = 2`, `arr[1][2] = 1 + 2 = 3`. 42 | 43 | 44 | **2. The correct answer is B.** 45 | 46 | **Explanation:** 47 | 48 | - **A)** 49 | ```java 50 | public static T getFirstElement(T[] array) { 51 | return array[0]; 52 | } 53 | ``` 54 | - This option is incorrect because the generic type `` is missing before the return type `T`. 55 | 56 | - **B)** 57 | ```java 58 | public static T getFirstElement(T[] array) { 59 | return array[0]; 60 | } 61 | ``` 62 | - This is the correct answer. The generic type `` is correctly declared before the return type `T`. 63 | 64 | - **C)** 65 | ```java 66 | public static getFirstElement(T[] array) { 67 | return array[0]; 68 | } 69 | ``` 70 | - This option is incorrect because the return type `T` is missing. 71 | 72 | - **D)** 73 | ```java 74 | public static T[] getFirstElement(T[] array) { 75 | return array[0]; 76 | } 77 | ``` 78 | - This option is incorrect because the return type is `T[]`, which does not match the intended method return type. 79 | 80 | 81 | **3. The correct answer is D.** 82 | 83 | **Explanation:** 84 | 85 | **A)** The code compiles and prints: 86 | ``` 87 | 1 2 3 88 | 1.1 2.2 3.3 89 | one two three 90 | ``` 91 | - This option is incorrect. The code does not compile, so it cannot produce any output. 92 | 93 | **B)** The code compiles and prints: 94 | ``` 95 | 1 2 3 96 | 1.1 2.2 3.3 97 | ``` 98 | - This option is incorrect. While this would be the output if the `printList(strings)` line were removed, the code as written does not compile. 99 | 100 | **C)** The code does not compile due to an error in the `printList` method. 101 | - This option is incorrect. The `printList` method is correctly defined using an upper bound wildcard ``. 102 | 103 | **D)** The code does not compile due to an error in the `main` method. 104 | - This option is correct. The code fails to compile due to an error in the `main` method. `printList(strings)` causes a compilation error because `String` is not a subclass of `Number`. 105 | 106 | **E)** The code compiles but throws a runtime exception when executed. 107 | - This option is incorrect. The code fails to compile so it cannot be executed. 108 | 109 | 110 | **4. The correct answer is A.** 111 | 112 | **Explanation:** 113 | 114 | - **A)** `[A, B, E, C, D]` 115 | - This option is correct. The `add` method with an index parameter inserts the specified element at the specified position in the list. All elements after the specified position are shifted to the right. Hence, `"E"` is inserted at index 2, pushing `"C"` and `"D"` to the right. 116 | 117 | - **B)** `[A, E, B, C, D]` 118 | - This option is incorrect. This would be the result if `"E"` were added at index 1, not index 2. 119 | 120 | - **C)** `[A, B, C, E, D]` 121 | - This option is incorrect. This would be the result if `"E"` were added at index 3, not index 2. 122 | 123 | - **D)** `[A, B, C, D, E]` 124 | - This option is incorrect. This would be the result if `"E"` were added at the end of the list, not at index 2. 125 | 126 | - **E)** `[A, C, B, E, D]` 127 | - This option is incorrect. This sequence does not follow the proper behavior of the `add` method with index 2. It seems like a random shuffle and doesn't correspond to how elements are shifted when a new element is added. 128 | 129 | 130 | **5. The correct answers are C and D.**. 131 | 132 | **Explanation:** 133 | 134 | - **A)** A `Set` allows duplicate elements. 135 | - This option is incorrect. One of the primary characteristics of a `Set` is that it does not allow duplicate elements. Each element must be unique. 136 | 137 | - **B)** Elements in a `Set` are maintained in the order they were inserted. 138 | - This option is incorrect. The ordering of elements depends on the specific implementation of the `Set` interface. For example, `HashSet` does not maintain any order, while `LinkedHashSet` maintains insertion order, and `TreeSet` maintains a sorted order. 139 | 140 | - **C)** The `Set` interface includes methods for adding, removing, and checking the presence of elements. 141 | - This option is correct. The `Set` interface provides methods such as `add()`, `remove()`, and `contains()` to manage its elements. 142 | 143 | - **D)** The `Set` interface is implemented by classes like `HashSet`, `LinkedHashSet`, and `TreeSet`. 144 | - This option is correct. `HashSet`, `LinkedHashSet`, and `TreeSet` are all concrete implementations of the `Set` interface, each with different characteristics regarding order and performance. 145 | 146 | - **E)** A `Set` guarantees constant-time performance for the basic operations (add, remove, contains). 147 | - This option is incorrect. This statement is true for `HashSet` specifically, which provides average constant-time performance for these operations. However, it is not true for all `Set` implementations. For example, `TreeSet` provides logarithmic time performance for these operations because it is based on a Red-Black tree. 148 | 149 | 150 | **6. The correct answer is C.** 151 | 152 | **Explanation:** 153 | 154 | - **A)** `[A, B, C, D]` 155 | - This option is incorrect.This option ignores the order in which elements are added to the deque. It simply lists elements in the order they appear to be added without considering the `addFirst` and `addLast` methods. 156 | 157 | - **B)** `[C, B, A, D]` 158 | - This option is incorrect. This option incorrectly assumes `"A"` is added after `"B"`, howerver, `addFirst("A")` puts `"A"` at the second position. 159 | 160 | - **C)** `[C, A, B, D]` 161 | - This option is correct. This is indeed the correct output. The method `addFirst("C")` puts "C" at the front, `addFirst("A")` puts `"A"` at the second position, `addLast("B")` adds `"B"` after `"A"`, and `addLast("D")` adds `"D"` at the end. Thus, the final order is `[C, A, B, D]`. 162 | 163 | - **D)** `[D, B, A, C]` 164 | - This option is incorrect. This option shows the reverse order, which does not match how elements are actually added to the deque. 165 | 166 | - **E)** `[A, C, B, D]` 167 | - This option is incorrect. This option incorrectly assumes `"A"` is added before `"C"` despite `addFirst("C")` being called after `addFirst("A")`. 168 | 169 | 170 | **7. The correct answer is D.** 171 | 172 | **Explanation:** 173 | 174 | - **A)** `{1=A, 2=B, 3=C, 2=D}` 175 | - This option is incorrect. This option suggests that the map would keep duplicate keys, which is not true for a `Map`. A key can only have one value associated with it at a time. 176 | 177 | - **B)** `{1=A, 2=B, 3=C}` 178 | - This option is incorrect. This option ignores the fact that the value associated with key `2` is updated from `"B"` to `"D"`. 179 | 180 | - **C)** `{1=A, 2=D, 3=C, 2=D}` 181 | - This option is incorrect. This option again suggests that the map can have duplicate keys, which it cannot. 182 | 183 | - **D)** `{1=A, 2=D, 3=C}` 184 | - This option is correct. The `put` method updates the value associated with a key if the key already exists in the map. Therefore, the value associated with key `2` is updated from `"B"` to `"D"`. 185 | 186 | - **E)** `{1=A, 3=C, 2=B}` 187 | - This option is incorrect. This option ignores the update to the value associated with key `2` from `"B"` to `"D"`. 188 | 189 | 190 | **8. The correct answer is C.** 191 | 192 | **Explanation:** 193 | 194 | - **A)** 195 | ``` 196 | Alice 30 197 | Bob 25 198 | Charlie 35 199 | ``` 200 | - This option is incorrect. This option lists the elements in their original order, not the sorted order based on age. 201 | 202 | - **B)** 203 | ``` 204 | Charlie 35 205 | Alice 30 206 | Bob 25 207 | ``` 208 | - This option is incorrect. This option lists the elements in descending order of age, but the `compareTo` method sorts in ascending order of age. 209 | 210 | - **C)** 211 | ``` 212 | Bob 25 213 | Alice 30 214 | Charlie 35 215 | ``` 216 | - This option is correct. The `compareTo` method sorts the `Person` objects in ascending order based on their age. Hence, the sorted order is `Bob (25)`, `Alice (30)`, and `Charlie (35)`. 217 | 218 | - **D)** 219 | ``` 220 | Bob 25 221 | Charlie 35 222 | Alice 30 223 | ``` 224 | - This option is incorrect. This option does not correctly follow the ascending order of age. 225 | 226 | - **E)** 227 | ``` 228 | Alice 30 229 | Charlie 35 230 | Bob 25 231 | ``` 232 | - This option is incorrect. This option does not correctly follow the ascending order of age. 233 | 234 | 235 | **9 .The correct answer is A.** 236 | 237 | 238 | **Explanation:** 239 | 240 | - **A)** 241 | ``` 242 | Bob 25 243 | Alice 30 244 | Charlie 35 245 | ``` 246 | - This option is incorrect. The `AgeComparator` sorts the `Person` objects in ascending order based on their age. Hence, the sorted order is `Bob (25)`, `Alice (30)`, and `Charlie (35)`. 247 | 248 | - **B)** 249 | ``` 250 | Charlie 35 251 | Alice 30 252 | Bob 25 253 | ``` 254 | - This option is incorrect. This option lists the elements in descending order of age, but the `AgeComparator` sorts in ascending order of age. 255 | 256 | - **C)** 257 | ``` 258 | Alice 30 259 | Bob 25 260 | Charlie 35 261 | ``` 262 | - This option is incorrect. This option does not correctly follow the ascending order of age. 263 | 264 | - **D)** 265 | ``` 266 | Bob 25 267 | Charlie 35 268 | Alice 30 269 | ``` 270 | - This option is incorrect. This option does not correctly follow the ascending order of age. 271 | 272 | - **E)** 273 | ``` 274 | Alice 30 275 | Charlie 35 276 | Bob 25 277 | ``` 278 | - This option is incorrect. This option does not correctly follow the ascending order of age. 279 | 280 | -------------------------------------------------------------------------------- /ch03a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter THREE" 5 | subtitle: "Working with Records and Enums" 6 | exam_objectives: 7 | - "Create classes and records, and define and use instance and static fields and methods, constructors, and instance and static initializers." 8 | - "Create and use enum types with fields, methods, and constructors." 9 | --- 10 | 11 | ## Answers 12 | 13 | **1. The correct answer is C.** 14 | 15 | **Explanation:** 16 | 17 | - **A)** The `Employee` record explicitly defines a public constructor that initializes its fields. 18 | - This option is incorrect because the record `Employee` does not explicitly define a `public` constructor. Records automatically generate a `public` constructor with the same parameters as the record's declaration. 19 | 20 | - **B)** The fields `name` and `age` can be reassigned to new values after an `Employee` object is created. 21 | - This option is incorrect as the fields within a record are `final`, which means they cannot be reassigned to new values after an `Employee` object has been created. This immutability is one of the key characteristics of records. 22 | 23 | - **C)** The `Employee` record implicitly creates a `public` constructor and `private` `final` fields for `name` and `age`. 24 | - This is the correct option. Records implicitly create a public constructor for the record's fields and also make these fields `private` and `final`. This means you don't have to manually write boilerplate code for constructor, getters, or to ensure immutability. 25 | 26 | - **D)** It is mandatory to define getters for the fields `name` and `age` in the `Employee` record. 27 | - This option is incorrect because records automatically generate public methods to access the fields, known as accessor methods, which essentially act as getters. Therefore, it is not mandatory (or even possible) to define separate getters for the fields. 28 | 29 | 30 | 31 | **2. The correct answer is B.** 32 | 33 | **Explanation:** 34 | 35 | - **A)** The `balance` field can be modified using a public setter method within the `Account` record. 36 | - This option is incorrect because records in Java do not support public setter methods for their fields. The fields of a record are `final` and cannot be modified after the object's construction, which is a key aspect of their design to enforce immutability. 37 | 38 | - **B)** Once an `Account` object is created, its `id` and `balance` cannot be changed. 39 | - This is the correct option. Records are immutable by design, meaning that once a record object is created, the values of its fields (`id` and `balance` in this case) cannot be changed. This immutability is ensured by making the fields `private` and `final`, and by not providing setter methods. 40 | 41 | - **C)** Immutability of records can be bypassed by you define custom setter methods for the `id` and `balance` fields. 42 | - This option is incorrect. Custom setter methods cannot be defined for the record fields because records do not allow defining mutators for their components. 43 | 44 | - **D)** Records allow field values to be modified if accessed directly, without using setter methods. 45 | - This option is incorrect because the fields in a record are implicitly `final` and private, which means they cannot be modified directly or through setter methods. The design of records enforces this immutability to ensure that instances of records act as true carriers of immutable data. 46 | 47 | 48 | **3. The correct answer is D.** 49 | 50 | **Explanation:** 51 | 52 | - **A)** `Product p = new Product();` 53 | - This option is incorrect because the default constructor without parameters does not exist for records in Java. Records require all their fields to be specified at the time of instantiation. 54 | 55 | - **B)** `Product p = Product(101, "Coffee", 15.99);` 56 | - This option is incorrect because the syntax used here is not valid for creating a new instance of a record in Java. The correct syntax for instantiating a record involves using the `new` keyword followed by the record name and the parameters in parentheses. 57 | 58 | - **C)** `Product p = {101, "Coffee", 15.99};` 59 | - This option is incorrect as it mistakenly uses the syntax for array initialization. In Java, objects, including records, cannot be instantiated using curly braces without the `new` keyword and proper constructor. 60 | 61 | - **D)** `Product p = new Product(101, "Coffee", 15.99);` 62 | - This is the correct option. Records in Java are instantiated using the `new` keyword followed by the record's constructor, which requires passing all the fields defined in the record. This syntax correctly creates a new `Product` record with the given `id`, `name`, and `price`. 63 | 64 | 65 | **4. The correct answer is B.** 66 | 67 | **Explanation:** 68 | 69 | - **A)** Records cannot implement interfaces because they are `final` and immutable by design, which prevents any form of behavior customization. 70 | - This option is incorrect. Records in Java can implement interfaces. The finality and immutability of records do not preclude them from implementing interfaces, which can be used to add behaviors or contractual obligations to a record. 71 | 72 | - **B)** This record correctly implements the `Comparable` interface, allowing `Item` objects to be sorted based on their `price`. 73 | - This is the correct option. The provided record definition correctly implements the `Comparable` interface by overriding the `compareTo` method. This customization allows instances of the `Item` record to be sorted based on the `price` field, demonstrating that records can indeed implement interfaces and override their methods as needed. 74 | 75 | - **C)** Implementing interfaces in records is restricted only to functional interfaces due to their immutable nature. 76 | - This option is incorrect. There is no such restriction that limits records to implementing only functional interfaces. Records can implement any interface, including those with multiple abstract methods, as long as the record provides implementations for the abstract methods defined in the interface. 77 | 78 | - **D)** The `compareTo` method cannot be overridden in records because method overriding is not supported in record types. 79 | - This option is incorrect. Records can override methods from the interfaces they implement, including the `compareTo` method from the `Comparable` interface in this example. Method overriding is a key aspect of implementing interfaces and is fully supported by record types in Java. 80 | 81 | 82 | **5. The correct answers are A and D.** 83 | 84 | **Explanation:** 85 | 86 | - **A)** 87 | ```java 88 | public enum Day { 89 | MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY 90 | } 91 | ``` 92 | - This option is correct. It demonstrates a valid declaration of an enum in Java. Enums are used to define a set of named constants, and this syntax is the standard way to declare them. The `public` access modifier makes this enum accessible from any other class. 93 | 94 | - **B)** 95 | ```java 96 | enum Month { 97 | private JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER; 98 | } 99 | ``` 100 | - This option is incorrect. Enums cannot have `private` access modifiers for their constants. Enum constants are implicitly `public`, `static`, and `final` and should be declared without access modifiers. 101 | 102 | - **C)** 103 | ```java 104 | protected enum Season { 105 | WINTER, SPRING, SUMMER, FALL 106 | } 107 | ``` 108 | - This option is incorrect because enums cannot be declared with `protected` or `private` access levels. Enums are implicitly `public` if they are defined outside of a class. If defined within a class, they can have any access level, but the `protected` keyword cannot be used at the enum level itself. 109 | 110 | - **D)** 111 | ```java 112 | enum Status { 113 | ACTIVE, INACTIVE, DELETED; 114 | 115 | public void printStatus() { 116 | System.out.println("Current status: " + this); 117 | } 118 | } 119 | ``` 120 | - This option is correct. It shows an enum `Status` with a method `printStatus()`. Enums in Java can contain methods, fields, constructors, and implement interfaces. This demonstrates the ability of enums to have methods, making this declaration valid. 121 | 122 | 123 | **6. The correct answer is A.** 124 | 125 | **Explanation:** 126 | 127 | - **A)** `1` 128 | - This option is correct. The `ordinal()` method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Since `GREEN` is the second enum constant declared in the `Color` enum, its ordinal value is 1. 129 | 130 | - **B)** `2` 131 | - This option is incorrect. The ordinal value of `BLUE` would be 2, not `GREEN`, because `BLUE` is the third declared constant in the `Color` enum. 132 | 133 | - **C)** `0` 134 | - This option is incorrect. The ordinal value of `RED` is 0, as it is the first declared constant in the `Color` enum. 135 | 136 | - **D)** `Color.GREEN` 137 | - This option is incorrect. The `ordinal()` method returns an integer representing the position of the enum constant in the declaration, not the enum constant itself. 138 | 139 | 140 | **7. The correct answer is D.** 141 | 142 | **Explanation:** 143 | 144 | - **A)** 145 | ```java 146 | public enum Size { 147 | SMALL, MEDIUM, LARGE; 148 | public static void printSize() { 149 | System.out.println("The size is " + this.name()); 150 | } 151 | } 152 | ``` 153 | - This option is incorrect because the method `printSize()` is defined as `static`, which means it cannot access the `this` reference. Static methods in enums can't directly access the enum constants without specifying the constant explicitly or being passed a reference. 154 | 155 | - **B)** 156 | ```java 157 | enum Flavor { 158 | CHOCOLATE, VANILLA, STRAWBERRY; 159 | void printFlavor() { 160 | System.out.println("Flavor: " + Flavor.name); 161 | } 162 | } 163 | ``` 164 | - This option is incorrect because the `name` property of an enum constant is `private`. You can only access it using the `this` reference and the `name()` method (`this.name()`). 165 | 166 | - **C)** 167 | ```java 168 | protected enum Direction { 169 | NORTH, SOUTH, EAST, WEST; 170 | private printDirection() { 171 | System.out.println("Going " + this.toString()); 172 | } 173 | } 174 | ``` 175 | - This option is incorrect for two reasons. First, `protected` is not a valid access modifier for a top-level enum, top-level enums can only be `public` or package-private (no modifier). Second, `printDirection()` method is missing a return type (e.g., `void`). 176 | 177 | - **D)** 178 | ```java 179 | public enum Season { 180 | WINTER, SPRING, SUMMER, FALL; 181 | public void printSeason() { 182 | System.out.println("The season is " + this.name()); 183 | } 184 | } 185 | ``` 186 | - This is the correct option. The `printSeason()` method is properly defined: it's `public`, non-static, and utilizes the `this` reference to access the name of the current enum constant. This method correctly provides custom behavior for each enum constant, allowing it to print a message indicating the current season. 187 | -------------------------------------------------------------------------------- /ch09a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter NINE" 5 | subtitle: "Streams" 6 | exam_objectives: 7 | - "Use Java object and primitive Streams, including lambda expressions implementing functional interfaces, to create, filter, transform, process, and sort data." 8 | - "Perform decomposition, concatenation, and reduction, and grouping and partitioning on sequential and parallel streams." 9 | --- 10 | 11 | ## Answers 12 | **1. The correct answer is C.** 13 | 14 | **Explanation:** 15 | 16 | - **A)** `Optional optional = new Optional<>(value);` 17 | - This option is incorrect because `Optional` does not have a public constructor. Instead, static factory methods like `of` and `ofNullable` should be used. 18 | 19 | - **B)** `Optional optional = Optional.of(value);` 20 | - This option is incorrect because `Optional.of(value)` throws a `NullPointerException` if `value` is `null`. In this scenario, since `getValue()` can return `null`, this line could lead to an exception. 21 | 22 | - **C)** `Optional optional = Optional.ofNullable(value);` 23 | - This option is correct because `Optional.ofNullable(value)` will return an `Optional` describing the specified value if non-null, or an empty `Optional` if the value is `null`. This is the appropriate way to handle a potentially `null` value. 24 | 25 | - **D)** `Optional optional = Optional.empty(value);` 26 | - This option is incorrect because `Optional.empty()` does not accept any arguments. It simply returns an empty `Optional`. 27 | 28 | - **E)** `Optional optional = Optional.nullable(value);` 29 | - This option is incorrect because there is no method `nullable` in the `Optional` class. The correct method for this purpose is `ofNullable`. 30 | 31 | 32 | **2. The correct answer is E.** 33 | 34 | **Explanation:** 35 | 36 | - **A)** `stream.filter(s -> s.contains("A"));` 37 | - This option is incorrect because `filter` is an intermediate operation. It returns a new stream with elements that match the given predicate. 38 | 39 | - **B)** `stream.map(String::toLowerCase);` 40 | - This option is incorrect because `map` is an intermediate operation. It returns a new stream with elements that are the results of applying the given function. 41 | 42 | - **C)** `stream.distinct();` 43 | - This option is incorrect because `distinct` is an intermediate operation. It returns a new stream with distinct elements. 44 | 45 | - **D)** `stream.limit(2);` 46 | - This option is incorrect because `limit` is an intermediate operation. It returns a new stream that is truncated to be no longer than the given size. 47 | 48 | - **E)** `stream.collect(Collectors.toList());` 49 | - This option is correct because `collect` is a terminal operation. It triggers the processing of the stream and collects the elements into a `List`. 50 | 51 | 52 | **3. The correct answer is D.** 53 | 54 | **Explanation:** 55 | 56 | - **A)** `int sum = numbers.stream().sum();` 57 | - This option is incorrect because arrays do not have a `stream` method directly on them. You need to use a method from a utility class like `IntStream` to create a stream. 58 | 59 | - **B)** `int sum = IntStream.range(0, numbers.length).sum();` 60 | - This option is incorrect because `IntStream.range(0, numbers.length)` generates a stream of integers from 0 to the length of the array, not the elements of the array itself. 61 | 62 | - **C)** `int sum = IntStream.from(numbers).sum();` 63 | - This option is incorrect because `IntStream` does not have a `from` method. The correct method is `of`. 64 | 65 | - **D)** `int sum = IntStream.of(numbers).sum();` 66 | - This option is correct because `IntStream.of(numbers).sum()` correctly creates an `IntStream` from the array and calculates the sum of its elements. 67 | 68 | - **E)** `int sum = IntStream.range(numbers).sum();` 69 | - This option is incorrect because `IntStream.range` requires two arguments (a start and an end index) and is used to generate a stream of numbers within a range, not to sum an array. 70 | 71 | 72 | **4. The correct answer is A.** 73 | 74 | **Explanation:** 75 | 76 | - **A)** `Stream filteredStream = stream.filter(s -> s.length() > 3);` 77 | - This option is correct because `filter` is the correct intermediate operation to apply a predicate to each element of the stream and return a new stream containing only elements that match the predicate. 78 | 79 | - **B)** `Stream filteredStream = stream.map(s -> s.length() > 3);` 80 | - This option is incorrect because `map` is used to transform elements of the stream and does not filter them. The result would be a stream of `Boolean` values instead of the original strings. 81 | 82 | - **C)** `Stream filteredStream = stream.collect(Collectors.filtering(s -> s.length() > 3));` 83 | - This option is incorrect because `Collectors.filtering` is not a valid method. Filtering is done through the `filter` method on the stream itself, not via collectors. 84 | 85 | - **D)** `Stream filteredStream = stream.filtering(s -> s.length() > 3);` 86 | - This option is incorrect because there is no `filtering` method on the stream. The correct method is `filter`. 87 | 88 | - **E)** `Stream filteredStream = stream.filterByLength(3);` 89 | - This option is incorrect because there is no `filterByLength` method on the stream. The correct method to use is `filter`. 90 | 91 | 92 | **5. The correct answer is C.** 93 | 94 | **Explanation:** 95 | 96 | - **A)** `Stream lengthStream = stream.map(s -> s.length());` 97 | - This option is incorrect because the `map` method will transform the elements to `Integer`, not `String`. The correct type for the resulting stream should be `Stream`. 98 | 99 | - **B)** `Stream lengthStream = stream.mapToInt(s -> s.length());` 100 | - This option is incorrect because `mapToInt` produces an `IntStream`, not a `Stream`. Additionally, the resulting stream type would not be `Stream`. 101 | 102 | - **C)** `Stream lengthStream = stream.map(s -> s.length());` 103 | - This option is correct because `map` transforms each string in the stream to its length, resulting in a `Stream`. 104 | 105 | - **D)** `IntStream lengthStream = stream.map(s -> s.length());` 106 | - This option is incorrect because `map` produces a `Stream`, not an `IntStream`. The correct method for producing an `IntStream` would be `mapToInt`. 107 | 108 | - **E)** `Stream lengthStream = stream.flatMap(s -> Stream.of(s.length()));` 109 | - This option is incorrect because `flatMap` is used to flatten nested streams and not simply map to another type. Additionally, the resulting stream type would not be `Stream`. 110 | 111 | 112 | **6. The correct answer is A.** 113 | 114 | **Explanation:** 115 | 116 | - **A)** `Stream resultStream = stream.skip(2).limit(3);` 117 | - This option is correct because `skip(2)` skips the first 2 elements of the stream, and `limit(3)` limits the stream to the next 3 elements. Therefore, the resulting stream will contain the 3rd, 4th, and 5th elements of the original list. 118 | 119 | - **B)** `Stream resultStream = stream.limit(3).skip(2);` 120 | - This option is incorrect because `limit(3)` first limits the stream to the first 3 elements, and then `skip(2)` skips 2 of those elements, resulting in a stream with only the 3rd element. 121 | 122 | - **C)** `Stream resultStream = stream.skip(3).limit(2);` 123 | - This option is incorrect because `skip(3)` skips the first 3 elements, and `limit(2)` then limits the stream to the next 2 elements, resulting in a stream with the 4th and 5th elements. 124 | 125 | - **D)** `Stream resultStream = stream.limit(2).skip(3);` 126 | - This option is incorrect because `limit(2)` first limits the stream to the first 2 elements, and then `skip(3)` would attempt to skip more elements than are available, resulting in an empty stream. 127 | 128 | - **E)** `Stream resultStream = stream.slice(2, 5);` 129 | - This option is incorrect because there is no `slice` method in the Stream API. The correct methods to achieve the desired result are `skip` and `limit`. 130 | 131 | 132 | **7. The correct answer is B.** 133 | 134 | **Explanation:** 135 | 136 | - **A)** `Stream resultStream = Stream.concat(stream1, stream2.collect(Collectors.toList()));` 137 | - This option is incorrect because `Stream.concat` expects two streams as arguments. `stream2.collect(Collectors.toList())` converts `stream2` into a `List`, not a `Stream`. 138 | 139 | - **B)** `Stream resultStream = Stream.concat(stream1, stream2);` 140 | - This option is correct because `Stream.concat(stream1, stream2)` correctly concatenates the two streams into a single stream containing all elements from both streams. 141 | 142 | - **C)** `Stream resultStream = stream1.concat(stream2);` 143 | - This option is incorrect because `Stream` does not have an instance method `concat`. The `concat` method is a static method of the `Stream` class. 144 | 145 | - **D)** `Stream resultStream = stream1.merge(stream2);` 146 | - This option is incorrect because there is no `merge` method in the `Stream` API. The correct method for concatenating streams is `Stream.concat`. 147 | 148 | - **E)** `Stream resultStream = Stream.of(stream1, stream2);` 149 | - This option is incorrect because `Stream.of(stream1, stream2)` creates a stream of streams, resulting in `Stream>` rather than a single concatenated `Stream`. 150 | 151 | 152 | **8. The correct answer is E.** 153 | 154 | **Explanation:** 155 | 156 | - **A)** `int product = stream.reduce(1, (a, b) -> a + b);` 157 | - This option is incorrect because the reduction operation is using addition instead of multiplication. The correct operation for calculating the product should be `(a, b) -> a * b`. 158 | 159 | - **B)** `int product = stream.reduce((a, b) -> a * b);` 160 | - This option is incorrect because it does not provide an identity value, which is necessary for the reduction operation when dealing with an empty stream. Without an identity value, the result is an `Optional` rather than an `int`. 161 | 162 | - **C)** `int product = stream.reduce(0, (a, b) -> a * b);` 163 | - This option is incorrect because the identity value for multiplication should be `1`, not `0`. Using `0` as the identity value would result in a product of `0` regardless of the stream elements. 164 | 165 | - **D)** `Optional product = stream.reduce(1, (a, b) -> a * b);` 166 | - This option is incorrect because the correct use of the `reduce` method with an identity value does not return an `Optional`. It should return the result directly as `int`. 167 | 168 | - **E)** `int product = stream.reduce(1, (a, b) -> a * b, (a, b) -> a * b);` 169 | - This option is correct because it correctly uses the `reduce` method with an identity value of `1` and a combiner function that multiplies the results. This form of `reduce` is suitable for parallel processing as well, ensuring the product is correctly calculated across multiple segments of the stream. 170 | 171 | 172 | **9. The correct answer is B.** 173 | 174 | **Explanation:** 175 | 176 | - **A)** `Set resultSet = stream.collect(Collectors.toSet());` 177 | - This option is incorrect because `Collectors.toSet()` does not guarantee the order of the elements. The implementation returned by this collector does not preserve the order of insertion. 178 | 179 | - **B)** `Set resultSet = stream.collect(Collectors.toCollection(LinkedHashSet::new));` 180 | - This option is correct because `Collectors.toCollection(LinkedHashSet::new)` collects the elements into a `LinkedHashSet`, which maintains the order of insertion. 181 | 182 | - **C)** `Set resultSet = stream.collect(Collectors.toCollection(TreeSet::new));` 183 | - This option is incorrect because `TreeSet` sorts the elements according to their natural ordering (or by a comparator, if provided). This does not necessarily preserve the original order of the stream elements. 184 | 185 | - **D)** `Set resultSet = stream.collect(Collectors.toList());` 186 | - This option is incorrect because `Collectors.toList()` collects the elements into a `List`, not a `Set`. 187 | 188 | - **E)** `Set resultSet = stream.collect(Collectors.toMap());` 189 | - This option is incorrect because `Collectors.toMap()` is used to collect the elements into a `Map`, not a `Set`. -------------------------------------------------------------------------------- /ch14a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter FOURTEEN" 5 | subtitle: "Localization" 6 | exam_objectives: 7 | - "Implement localization using locales and resource bundles. Parse and format messages, dates, times, and numbers, including currency and percentage values." 8 | --- 9 | 10 | ## Answers 11 | **1. The correct answer is C.** 12 | 13 | **Explanation:** 14 | 15 | - **A)** 16 | ``` 17 | true 18 | true 19 | true 20 | French (Canada) 21 | French (Canada) 22 | French (Canada) 23 | ``` 24 | - This option is incorrect because it doesn't account for the differences caused by the variant in `locale2`. 25 | 26 | - **B)** 27 | ``` 28 | false 29 | true 30 | false 31 | French (Canada) 32 | French (Canada, UNIX2024) 33 | French (Canada) 34 | ``` 35 | - This option is incorrect because it doesn't correctly represent the display name for `Locale.CANADA_FRENCH`. 36 | 37 | - **C)** 38 | ``` 39 | false 40 | true 41 | false 42 | French (Canada) 43 | French (Canada, UNIX2024) 44 | Canadian French 45 | ``` 46 | - This option is correct. Let's break it down: 47 | 48 | 1. `locale1.equals(locale2)` is `false` because `locale2` has a variant (`"UNIX2024"`) while `locale1` doesn't. 49 | 2. `locale1.equals(locale3)` is `true` because `Locale.CANADA_FRENCH` is equivalent to `new Locale("fr", "CA")`. 50 | 3. `locale2.equals(locale3)` is `false` because `locale2` has a variant while `locale3` doesn't. 51 | 4. `locale1.getDisplayName(Locale.ENGLISH)` returns `"French (Canada)"`. 52 | 5. `locale2.getDisplayName(Locale.ENGLISH)` returns `"French (Canada, UNIX2024)"`, including the variant. 53 | 6. `locale3.getDisplayName(Locale.ENGLISH)` returns `"Canadian French"`, which is the special display name for this constant. 54 | 55 | - **D)** 56 | ``` 57 | false 58 | false 59 | false 60 | French (Canada) 61 | French (Canada, UNIX2024) 62 | Canadian French 63 | ``` 64 | - This option is incorrect because it suggests that `locale1` and `locale3` are not equal, which they are. 65 | 66 | - **E)** The code will throw a `IllegalArgumentException` because `UNIX2024` is not a valid variant. 67 | - This option is incorrect. While `UNIX2024` is not a standard ISO 639 variant code, the `Locale` constructor accepts any string as a variant without throwing an exception. 68 | 69 | 70 | **2. The correct answer is D.** 71 | 72 | **Explanation:** 73 | 74 | - **A)** The `Locale.Category` enum has three values: `DISPLAY`, `FORMAT`, and `LANGUAGE`. 75 | - This option is incorrect. The `Locale.Category` enum has only two values: `DISPLAY` and `FORMAT`. There is no `LANGUAGE` category. 76 | 77 | - **B)** The `Locale.setDefault(Locale.Category, Locale)` method can only set the default locale for the `FORMAT` category. 78 | - This option is incorrect. The `Locale.setDefault(Locale.Category, Locale)` method can set the default locale for both the `DISPLAY` and `FORMAT` categories, not just `FORMAT`. 79 | 80 | - **C)** Using `Locale.getDefault(Locale.Category)` always returns the same locale regardless of the category specified. 81 | - This option is incorrect. `Locale.getDefault(Locale.Category)` can return different locales depending on the category specified. The `DISPLAY` and `FORMAT` categories can have different default locales. 82 | 83 | - **D)** The `DISPLAY` category affects the language used for displaying user interface elements, while the `FORMAT` category affects the formatting of numbers, dates, and currencies. 84 | - This option is correct. The `DISPLAY` category indeed affects the language used for displaying user interface elements (like error messages or GUI labels), while the `FORMAT` category affects how numbers, dates, currencies, and other locale-sensitive data are formatted. 85 | 86 | - **E)** Locale categories were introduced in Java 8 to replace the older `Locale` methods. 87 | - This option is incorrect. Locale categories were added to provide more granular control over localization aspects, complementing (not replacing) the existing `Locale` methods. 88 | 89 | 90 | **3. The correct answer is D.** 91 | 92 | **Explanation:** 93 | 94 | - **A)** Resource bundles can only be stored in `.properties` files. 95 | - This option is incorrect. While `.properties` files are commonly used for resource bundles, Java also supports class-based resource bundles. These are Java classes that extend `ResourceBundle` and provide localized resources programmatically. 96 | 97 | - **B)** The `ResourceBundle.getBundle()` method always throws a `MissingResourceException` if the requested bundle is not found. 98 | - This option is incorrect. The `ResourceBundle.getBundle()` method does not always throw a `MissingResourceException` if the requested bundle is not found. It follows a fallback mechanism, trying to find the most specific bundle, then falling back to more general bundles, and finally to the default bundle. 99 | 100 | - **C)** When searching for a resource bundle, Java only considers the specified locale and its language. 101 | - This option is incorrect. When searching for a resource bundle, Java considers not only the specified locale and its language but also the country, variant, and even the default locale. It follows a well-defined lookup procedure to find the most appropriate bundle. 102 | 103 | - **D)** If a key is not found in a specific locale's resource bundle, Java will look for it in the parent locale's bundle. 104 | - This option is correct. Java implements a parent chain fallback mechanism for resource bundles. If a key is not found in the specific locale's bundle, it will look in the parent locale's bundle. For example, if a key is not found in a `fr_FR` (French France) bundle, it will look in the `fr` (French) bundle, and then in the default bundle. 105 | 106 | - **E)** Resource bundles are loaded dynamically at runtime, so changes to `.properties` files are immediately reflected in the running application. 107 | - This option is incorrect. Resource bundles are typically loaded when `ResourceBundle.getBundle()` is called and then cached. Changes to .properties files are not immediately reflected in a running application. The application usually needs to be restarted or the resource bundle cache cleared for changes to take effect. 108 | 109 | 110 | **4. The correct answer is A.** 111 | 112 | **Explanation:** 113 | 114 | - **A)** 115 | ``` 116 | red 117 | blue 118 | ``` 119 | - This option is correct. Let's break down the code execution: 120 | 1. Properties are set and stored in the `config.properties` file. 121 | 2. `props.clear()` removes all properties from the `props` object. 122 | 3. `System.out.println(props.getProperty("color", "red"))` prints `red` because the properties have been cleared, so it uses the default value. 123 | 4. The properties are loaded from the file. 124 | 5. `System.out.println(props.getProperty("color", "red"))` now prints `blue` because it's loaded from the file. 125 | 126 | - **B)** 127 | ``` 128 | blue 129 | blue 130 | ``` 131 | - This option is incorrect. It doesn't account for the `clear()` method call which empties the properties before the first print statement. 132 | 133 | - **C)** 134 | ``` 135 | red 136 | red 137 | ``` 138 | - This option is incorrect. It doesn't account for the successful loading of properties from the file before the second print statement. 139 | 140 | - **D)** The code will throw a `FileNotFoundException`. 141 | - This option is incorrect. The code creates the file in the first `try-with-resources` block, so it should exist for the second block to read from. 142 | 143 | - **E)** 144 | ``` 145 | null 146 | blue 147 | ``` 148 | - This option is incorrect. `getProperty()` returns the default value `red` when the property is not found, not `null`. 149 | 150 | 151 | **5. The correct answer is B.** 152 | 153 | **Explanation:** 154 | 155 | - **A)** The code will throw a `IllegalArgumentException` because the date format is invalid. 156 | - This option is incorrect. The date format `"long"` is valid in `MessageFormat` and will not throw an exception. 157 | 158 | - **B)** The output will include the date in long format, the name `"Alice"`, the number 3, the word `"apples"`, and the price in US currency format. 159 | - This option is correct. The `MessageFormat` will correctly format each parameter according to the specified pattern: 160 | - `{0, date, long}` will format the `Date` in long format (`"June 1, 2023"`) 161 | - `{1}` will simply insert `"Alice"` 162 | - `{2,number,integer}` will format 3 as an integer 163 | - `{3}` will insert "apples" 164 | - `{4,number,currency}` will format 19.99 as currency according to the US locale (`"$19.99"`) 165 | 166 | 167 | - **C)** The `{2,number,integer}` format will display 3 as `"3.0"`. 168 | - This option is incorrect. The `{2,number,integer}` format will display 3 as `"3"`, not `"3.0"`. The integer format doesn't include decimal places. 169 | 170 | - **D)** The code will not compile because `MessageFormat` doesn't accept a `Locale` in its constructor. 171 | - This option is incorrect. `MessageFormat` does have a constructor that accepts a `Locale`. The code will compile successfully. 172 | 173 | - **E)** The `{4,number,currency}` format will always display the price in USD, regardless of the `Locale`. 174 | - This option is incorrect. The currency format will use the locale specified in the `MessageFormat` constructor, which in this case is `Locale.US`. If a different locale were used, the currency symbol and formatting could change. 175 | 176 | 177 | **6. The correct answer is A.** 178 | 179 | **Explanation:** 180 | 181 | - **A)** The `NumberFormat.getCurrencyInstance()` method returns a formatter that can format monetary amounts according to the specified locale's conventions. 182 | - This option is correct. The `getCurrencyInstance()` method of `NumberFormat` returns a currency formatter for the specified locale (or the default locale if none is specified). This formatter applies the appropriate currency symbol, digit grouping, and decimal separator according to the locale's conventions. 183 | 184 | - **B)** `NumberFormat` is a concrete class that can be instantiated directly using its constructor. 185 | - This option is incorrect. `NumberFormat` is an abstract class and cannot be instantiated directly. Instead, you obtain instances through its static factory methods like `getInstance()`, `getCurrencyInstance()`, or `getPercentInstance()`. 186 | 187 | - **C)** The `setMaximumFractionDigits()` method in `NumberFormat` can only accept values between 0 and 3. 188 | - This option is incorrect. The `setMaximumFractionDigits()` method is not limited to the range of 0 to 3. 189 | 190 | - **D)** When parsing strings, `NumberFormat` always throws a `ParseException` if the input doesn't exactly match the expected format. 191 | - This option is incorrect. `NumberFormat` is generally lenient when parsing. It will attempt to parse as much of the string as it can recognize as a number, and will only throw a `ParseException` if it can't parse any part of the string as a number. 192 | 193 | - **E)** The `NumberFormat` class can only format and parse integer values, not floating-point numbers. 194 | - This option is incorrect. `NumberFormat` can format and parse both integer and floating-point numbers. It provides methods like `setMaximumFractionDigits()` and `setMinimumFractionDigits()` specifically for handling decimal places in floating-point numbers. 195 | 196 | 197 | **7. The correct answer is A.** 198 | 199 | **Explanation:** 200 | 201 | - **A)** 202 | ``` 203 | 2023-06-15 10:30 EDT America/New_York 204 | 2023-06-15 23:30 JST Asia/Tokyo 205 | ``` 206 | - This option is correct. Let's break down the formatter pattern: 207 | - `"yyyy-MM-dd HH:mm"` formats the date and time 208 | - `"z"` outputs the short name of the zone, like EDT or JST 209 | - `"VV"` outputs the full time zone ID, like `America/New_York` or `Asia/Tokyo` 210 | The second line shows the correct time in Tokyo, which is 13 hours ahead of New York. 211 | 212 | - **B)** 213 | ``` 214 | 2023-06-15 10:30 EDT New_York 215 | 2023-06-15 23:30 JST Tokyo 216 | ``` 217 | - This option is incorrect. The `"VV"` pattern outputs the full time zone ID, not just the city name. 218 | 219 | - **C)** 220 | ``` 221 | 2023-06-15 10:30 -04:00 America/New_York 222 | 2023-06-15 23:30 +09:00 Asia/Tokyo 223 | ``` 224 | - This option is incorrect. The `"z"` pattern outputs the short name of the zone (EDT, JST), not the offset. 225 | 226 | - **D)** 227 | ``` 228 | 2023-06-15 10:30 America/New_York 229 | 2023-06-15 23:30 Asia/Tokyo 230 | ``` 231 | - This option is incorrect. It's missing the short zone names (EDT, JST) that the `"z"` pattern should output. 232 | 233 | - **E)** The code will throw a `DateTimeException` because the formatter pattern is invalid. 234 | - This option is incorrect. The formatter pattern is valid and will not throw an exception. 235 | -------------------------------------------------------------------------------- /ch05a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter FIVE" 5 | subtitle: "Controlling Program Flow" 6 | exam_objectives: 7 | - "Create program flow control constructs including if/else, switch statements and expressions, loops, and break and continue statements." 8 | - "Implement inheritance, including abstract and sealed types as well as record classes. Override methods, including that of the Object class. Implement polymorphism and differentiate between object type and reference type. Perform reference type casting, identify object types using the instanceof operator, and pattern matching with the instanceof operator and the switch construct." 9 | --- 10 | 11 | ## Answers 12 | **1. The correct answer is A.** 13 | 14 | **Explanation:** 15 | 16 | - **A)** `x is between 5 and 20` 17 | - This option is correct. The value of `x` is 10, which satisfies both conditions in the nested `if` statements (`x > 5` and `x < 20`). Therefore, the program prints `"x is between 5 and 20"`. 18 | 19 | - **B)** `x is 5 or less` 20 | - This option is incorrect. The value of `x` is 10, which does not satisfy the condition `x <= 5` in the `else` block. Therefore, this message will not be printed. 21 | 22 | - **C)** `x is greater than 20` 23 | - This option is incorrect. The value of `x` is 10, which does not satisfy the condition `x > 20`. Therefore, this message will not be printed. 24 | 25 | - **D)** The program does not compile 26 | - This option is incorrect. The program compiles successfully without any errors. 27 | 28 | - **E)** The program compiles but does not produce any output 29 | - This option is incorrect. The program produces output because the value of `x` satisfies the conditions within the nested `if` statements, leading to the output `"x is between 5 and 20"`. 30 | 31 | 32 | **2. The correct answer is D.** 33 | 34 | **Explanation:** 35 | 36 | - **A)** 37 | ```java 38 | if (emp instanceof Employee) { 39 | var (id, Person(name, age)) = emp; 40 | System.out.println(name + " is " + age + " years old."); 41 | } 42 | ``` 43 | - This option is incorrect. While it attempts to use destructuring, this syntax is not valid in Java. Java doesn't support destructuring assignment in this way. 44 | 45 | - **B)** 46 | ```java 47 | if (emp instanceof Employee(_, Person(var name, var age))) { 48 | System.out.println(name + " is " + age + " years old."); 49 | } 50 | ``` 51 | - This option is incorrect. It uses the underscore (`_`) to ignore the `id` field, which is not a valid technique in Java 21. 52 | 53 | - **C)** 54 | ```java 55 | if (emp instanceof Employee e) { 56 | System.out.println(e.person().name() + " is " + e.person().age() + " years old."); 57 | } 58 | ``` 59 | - This option is incorrect. It uses traditional `instanceof` without pattern matching, relying on accessor methods to extract the data. 60 | 61 | - **D)** 62 | ```java 63 | if (emp instanceof Employee(var id, Person(var name, var age))) { 64 | System.out.println(name + " is " + age + " years old."); 65 | } 66 | ``` 67 | - This option is correct. It uses nested record pattern matching to extract both the `Employee` and `Person` data in a single step. It uses `var` for type inference and correctly names the variables `name` and `age` as required. 68 | 69 | - **E)** 70 | ```java 71 | if (emp instanceof Employee(var id, var person)) { 72 | System.out.println(person.name() + " is " + person.age() + " years old."); 73 | } 74 | ``` 75 | - This option is incorrect. While it uses pattern matching for the `Employee` record, it doesn't nest the pattern matching for the `Person` record, so it still requires calling accessor methods on `person`. 76 | 77 | 78 | 79 | **3. The correct answer is C.** 80 | 81 | 82 | 83 | **Explanation:** 84 | 85 | - **A)** Code snippet 1 86 | - This option is incorrect. The variable `y` is declared inside the first `if` statement and is not accessible outside its block. Therefore, trying to print `y` outside its scope results in a compilation error. 87 | 88 | - **B)** Code snippet 2 89 | - This option is incorrect. The variable `z` is declared inside the second `if` statement and is not accessible outside its block. Therefore, attempting to use `z` outside its scope results in a compilation error. 90 | 91 | - **C)** Code snippet 3 92 | - This option is correct. The variable `a` is declared outside the `if` statement, so it is accessible both inside and outside the `if` block. Reassigning a inside the `if` block is allowed. 93 | 94 | - **D)** None of the above 95 | - This option is incorrect. While it's true that code snippets 1, 2 and 4 will not compile, code snippet 3 does compile without any errors. Therefore, the answer cannot be "none of the above". 96 | 97 | 98 | **4. The correct answer is C.** 99 | 100 | **Explanation:** 101 | 102 | - **A)** `Weekend` 103 | - This option is incorrect. The value of `dayOfWeek` is 3, which does not match cases 1 or 7, so it does not print `"Weekend"`. 104 | 105 | - **B)** `Invalid day` 106 | - This option is incorrect. The default case is not executed because the value of `dayOfWeek` matches one of the specific cases (2, 3, 4, 5, or 6). 107 | 108 | - **C)** `Weekday` 109 | - This option is correct. The value of `dayOfWeek` is 3, which matches case 3. Therefore, the variable `dayType` is set to `"Weekday"`, and this value is printed. 110 | 111 | - **D)** The program does not compile 112 | - This option is incorrect. The program compiles without errors. 113 | 114 | - **E)** The program compiles but does not produce any output 115 | - This option is incorrect. The program compiles and produces output, which is `"Weekday"` based on the given `dayOfWeek` value. 116 | 117 | 118 | **5. The correct answer is B.** 119 | 120 | **Explanation:** 121 | 122 | - **A)** `A` 123 | - This option is incorrect. The value of `score` is 85, which does not match the cases for 90 or 100. Therefore, it does not print `"A"`. 124 | 125 | - **B)** `F` 126 | - This option is correct. The default case is executed because the value of `score` doesn't match any of the other `case` statements. 127 | 128 | - **C)** The program does not compile 129 | - This option is incorrect. The program uses a `switch` expression correctly, compiling without errors. 130 | 131 | - **D)** `B` 132 | - This option is incorrect. The value of `score` is 85, which doesn't match the case for 80 or 89. 133 | 134 | - **E)** The program compiles but does not produce any output 135 | - This option is incorrect. The program compiles and produces output, which is `"F"` based on the given `score` value. 136 | 137 | 138 | **6. The correct answer is A.** 139 | 140 | **Explanation:** 141 | 142 | - **A)** 143 | ```java 144 | case CarType.SEDAN, CarType.HATCHBACK -> System.out.println("Compact vehicle"); 145 | case CarType.SUV -> System.out.println("Large vehicle"); 146 | case CarType.CONVERTIBLE -> System.out.println("Open-top vehicle"); 147 | ``` 148 | - This option is correct. In Java 21, you can use fully qualified names of enum constants in switch statements, even when the selector expression is of a type that's assignment-compatible with the enum type (in this case, `Vehicle` is assignment-compatible with `CarType`). 149 | 150 | - **B)** 151 | ```java 152 | case SEDAN, HATCHBACK -> System.out.println("Compact vehicle"); 153 | case SUV -> System.out.println("Large vehicle"); 154 | case CONVERTIBLE -> System.out.println("Open-top vehicle"); 155 | ``` 156 | - This option is incorrect. When using an interface type (`Vehicle`) as the selector expression, you must use fully qualified names for the enum constants. Using unqualified names (`SEDAN`, `HATCHBACK`, etc.) will result in a compilation error. 157 | 158 | - **C)** 159 | ```java 160 | case CarType.SEDAN || CarType.HATCHBACK -> System.out.println("Compact vehicle"); 161 | case CarType.SUV -> System.out.println("Large vehicle"); 162 | case CarType.CONVERTIBLE -> System.out.println("Open-top vehicle"); 163 | ``` 164 | - This option is incorrect. It attempts to use the logical OR operator (`||`) in the case label, which is not valid syntax for switch statements. Multiple case labels should be separated by commas, not logical operators. 165 | 166 | - **D)** 167 | ```java 168 | case Vehicle.SEDAN, Vehicle.HATCHBACK -> System.out.println("Compact vehicle"); 169 | case Vehicle.SUV -> System.out.println("Large vehicle"); 170 | case Vehicle.CONVERTIBLE -> System.out.println("Open-top vehicle"); 171 | ``` 172 | - This option is incorrect. Although it uses fully qualified names, it incorrectly prefixes the enum constants with `Vehicle` instead of `CarType`. The enum constants belong to the `CarType` enum, not the `Vehicle` interface, so this will result in a compilation error. 173 | 174 | 175 | **7. The correct answer is D.** 176 | 177 | **Explanation:** 178 | 179 | - **A)** 180 | ```java 181 | case Circle c -> Math.PI * c.radius() * c.radius(); 182 | case Square s -> s.side() * s.side(); 183 | case null -> 0; 184 | ``` 185 | - This option is incorrect. It doesn't compile because the `switch` expression is not exhaustive, it does not cover all possible `Shape` values. 186 | 187 | - **B)** 188 | ```java 189 | default -> 0; 190 | case Circle c -> Math.PI * c.radius() * c.radius(); 191 | case Square s -> s.side() * s.side(); 192 | case Triangle t -> 0.5 * t.base() * t.height(); 193 | ``` 194 | - This option is incorrect. It doesn't compile because the (unnecessary) `default` case comes before the rest of the `case` statements. 195 | 196 | - **C)** 197 | ```java 198 | case Shape s when s instanceof Circle -> 199 | Math.PI * ((Circle)s).radius() * ((Circle)s).radius(); 200 | case Shape s when s instanceof Square -> 201 | ((Square)s).side() * ((Square)s).side(); 202 | case Shape s when s instanceof Triangle -> 203 | 0.5 * ((Triangle)s).base() * ((Triangle)s).height(); 204 | ``` 205 | - This option is incorrect. It doesn't compile because it's not exhaustive. Since it uses verbose `instanceof` checks instead of leveraging pattern matching, it's missing a `default` branch. 206 | 207 | - **D)** 208 | ```java 209 | case Circle c -> Math.PI * c.radius() * c.radius(); 210 | case Square s -> s.side() * s.side(); 211 | case Triangle t -> 0.5 * t.base() * t.height(); 212 | ``` 213 | - This option is correct. It covers all possible subtypes of the sealed `Shape` interface without an unnecessary `default` case. 214 | 215 | 216 | **8. The correct answer is B.** 217 | 218 | **Explanation:** 219 | 220 | - **A)** `2` 221 | - This option is incorrect. The value of `count` is incremented until it reaches 3. The labeled `break` statement breaks out of the outer loop when `count` equals 3. 222 | 223 | - **B)** `3` 224 | - This option is correct. The value of `count` is incremented inside the inner `while` loop. When `count` reaches 3, the labeled `break` statement (`break outerLoop`) is executed, causing the control to exit the outer loop. Therefore, `count` is 3 when printed. 225 | 226 | - **C)** `4` 227 | - This option is incorrect. The loop does not continue incrementing `count` to 4 because the labeled `break` statement exits the loop when `count` is 3. 228 | 229 | - **D)** `5` 230 | - This option is incorrect. The loop does not continue incrementing `count` to 5 because the labeled `break` statement exits the loop when `count` is 3. 231 | 232 | - **E)** The program does not compile 233 | - This option is incorrect. The program compiles successfully and runs without errors. 234 | 235 | 236 | **9. The correct answer is C.** 237 | 238 | **Explanation:** 239 | 240 | - **A)** `5` 241 | - This option is incorrect. The value 5 is just the upper limit of the loop and not the sum of the integers from 1 to 5. 242 | 243 | - **B)** `10` 244 | - This option is incorrect. The value 10 is less than the sum of the integers from 1 to 5. 245 | 246 | - **C)** `15` 247 | - This option is correct. The loop iterates from 1 to 5, adding each value of `i` to `sum`. The calculations are as follows: 1 + 2 + 3 + 4 + 5 = 15. 248 | 249 | - **D)** `20` 250 | - This option is incorrect. The value 20 is more than the sum of the integers from 1 to 5. 251 | 252 | - **E)** The program does not compile 253 | - This option is incorrect. The program compiles successfully and runs without errors. 254 | 255 | 256 | **10. The correct answer is A.** 257 | 258 | **Explanation:** 259 | 260 | - **A)** `9` 261 | - This option is correct. The `continue` statement skips the current iteration when the number is even (`num % 2 == 0`). The odd numbers in the array are 1, 3, and 5. Their sum is 1 + 3 + 5 = 9. 262 | 263 | - **B)** `10` 264 | - This option is incorrect. The sum of the odd numbers (1, 3, and 5) is 9, not 10. 265 | 266 | - **C)** `12` 267 | - This option is incorrect. The sum of the odd numbers (1, 3, and 5) is 9, not 12. 268 | 269 | - **D)** `15` 270 | - This option is incorrect. The sum of all the numbers in the array (1 + 2 + 3 + 4 + 5) is 15, but the `continue` statement causes the loop to skip adding the even numbers. 271 | 272 | - **E)** The program does not compile 273 | - This option is incorrect. The program compiles successfully and runs without errors. 274 | 275 | -------------------------------------------------------------------------------- /ch10a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter TEN" 5 | subtitle: "Concurrency and Multithreading" 6 | exam_objectives: 7 | - "Create both platform and virtual threads. Use both Runnable and Callable objects, manage the thread lifecycle, and use different Executor services and concurrent API to run tasks." 8 | - "Develop thread-safe code, using locking mechanisms and concurrent API." 9 | - "Process Java collections concurrently and utilize parallel streams." 10 | --- 11 | 12 | ## Answers 13 | **1. The correct answer is C.** 14 | 15 | **Explanation:** 16 | 17 | - **A)** `Thread thread = Thread.ofVirtual(); thread.start(task);` 18 | - This option is incorrect because `Thread.ofVirtual()` returns a `Thread.Builder`, not a `Thread`. The `start()` method on `Thread.Builder` takes a `Runnable`, but this syntax is incorrect. 19 | 20 | - **B)** `Thread thread = Thread.ofVirtual().unstarted(task).run();` 21 | - This option is incorrect because calling `run()` directly does not start a new thread. It executes the task in the current thread. 22 | 23 | - **C)** `Thread thread = Thread.ofVirtual().start(task);` 24 | - This option is correct. It uses the new thread builder API in Java 21 to create and start a virtual thread in one step. 25 | 26 | - **D)** `Thread thread = Thread.ofVirtual(); task.run();` 27 | - This option is incorrect because it doesn't actually start a new thread. It creates a thread builder but doesn't use it, and then runs the task in the current thread. 28 | 29 | - **E)** `Thread thread = Thread.start(task);` 30 | - This option is incorrect because `Thread.start(task)` is not a valid static method in Java 21. 31 | 32 | 33 | **2. The correct answer is B.** 34 | 35 | **Explanation:** 36 | - **A)** `synchronized (this) { counter++; }` 37 | - This option is incorrect because `this` cannot be used in a static context. In the `main` method, `this` is not available. For a static field like `counter`, you need to synchronize on a static object or class. 38 | 39 | - **B)** `synchronized (Main.class) { counter++; }` 40 | - This option is correct because synchronizing on `Main.class` ensures that only one thread can enter the synchronized block at a time for all instances of `Main`, which is appropriate for protecting static fields like `counter`. 41 | 42 | - **C)** `synchronized (task) { counter++; }` 43 | - This option is incorrect because `task` is a `Runnable` object, and synchronizing on it does not effectively control access to the shared static field `counter`. 44 | 45 | - **D)** `synchronized (counter) { counter++; }` 46 | - This option is incorrect because `counter` is a primitive type (`int`), and you cannot synchronize on a primitive type. Synchronization requires an object. 47 | 48 | - **E)** `synchronized (System.out) { counter++; }` 49 | - This option is incorrect because synchronizing on `System.out` is not related to controlling access to `counter`. It would also interfere with other potential uses of `System.out`. 50 | 51 | 52 | **3. The correct answers are B and C.** 53 | 54 | **Explanation:** 55 | 56 | - **A)** `AtomicInteger` is part of the `java.util.concurrent.atomic` package, but it does not provide atomic operations for increment and decrement. 57 | - This statement is incorrect. `AtomicInteger` provides atomic operations for increment and decrement, such as `incrementAndGet()` and `decrementAndGet()`. 58 | 59 | - **B)** `AtomicReference` can only be used with reference types, not primitive types. 60 | - This statement is correct. `AtomicReference` is designed to work with reference types and cannot be used with primitive types directly. 61 | 62 | - **C)** `AtomicLong` supports atomic operations on `long` values, including `getAndIncrement()` and `compareAndSet()` methods. 63 | - This statement is correct. `AtomicLong` provides atomic operations on `long` values, including `getAndIncrement()` and `compareAndSet()` methods. 64 | 65 | - **D)** `AtomicBoolean` can be used to perform atomic arithmetic operations on `boolean` values. 66 | - This statement is incorrect. `AtomicBoolean` is used for atomic updates to `boolean` values, but it does not support atomic arithmetic operations. 67 | 68 | 69 | 70 | **4. The correct answer is A.** 71 | 72 | **Explanation:** 73 | 74 | - **A)** 75 | ```java 76 | lock.lock(); 77 | try { 78 | count++; 79 | } finally { 80 | lock.unlock(); 81 | } 82 | ``` 83 | - This option correctly acquires the lock before modifying the shared resource and ensures the lock is released in the `finally` block, which is the proper use of the `Lock` interface. 84 | 85 | - **B)** 86 | ```java 87 | lock.lock(); 88 | count++; 89 | lock.unlock(); 90 | ``` 91 | - This option is incorrect because if an exception occurs between `lock.lock()` and `lock.unlock()`, the lock will not be released, potentially causing a deadlock. 92 | 93 | - **C)** 94 | ```java 95 | try { 96 | lock.lock(() -> { 97 | count++; 98 | }); 99 | } finally { 100 | lock.unlock(); 101 | } 102 | ``` 103 | - This option is incorrect because that's not a valid `lock.lock()` call. 104 | 105 | - **D)** 106 | ```java 107 | synchronized(lock) { 108 | count++; 109 | } 110 | ``` 111 | - This option is incorrect because the `synchronized` block is used with the `lock` object itself, which is not the correct usage of the `Lock` interface and does not provide the intended functionality. 112 | 113 | 114 | 115 | **5. The correct answer is A.** 116 | 117 | **Explanation:** 118 | 119 | - **A)** 120 | ```java 121 | try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { 122 | executor.submit(() -> System.out.println("Task executed")); 123 | } 124 | ``` 125 | - This option is correct. It uses the `try-with-resources` block with the new `Executors.newVirtualThreadPerTaskExecutor()` method introduced in Java 21. The `ExecutorService` will be automatically closed when the `try` block exits, eliminating the need for explicit shutdown calls. 126 | 127 | - **B)** 128 | ```java 129 | try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { 130 | executor.submit(() -> System.out.println("Task executed")); 131 | } finally { 132 | executor.shutdown(); 133 | } 134 | ``` 135 | - This option is incorrect because it unnecessarily calls `shutdown()` in the finally block. With `try-with-resources`, the `ExecutorService` is automatically closed, making the explicit `shutdown()` call redundant and potentially harmful. 136 | 137 | - **C)** 138 | ```java 139 | ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); 140 | try { 141 | executor.submit(() -> System.out.println("Task executed")); 142 | } finally { 143 | executor.close(); 144 | } 145 | ``` 146 | - This option is incorrect because it doesn't use `the try-with-resources` syntax. While it does correctly close the `ExecutorService`, it doesn't take advantage of the automatic resource management provided by `try-with-resources`. 147 | 148 | - **D)** 149 | ```java 150 | try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { 151 | executor.submit(() -> System.out.println("Task executed")); 152 | executor.awaitTermination(1, TimeUnit.SECONDS); 153 | } 154 | ``` 155 | - This option is incorrect because it unnecessarily calls `awaitTermination()`. In a `try-with-resources` block, the `ExecutorService` is automatically closed when the block exits, making the explicit wait for termination unnecessary and potentially causing the thread to block for 1 second. 156 | 157 | 158 | 159 | **6. The correct answer is D.** 160 | 161 | **Explanation:** 162 | 163 | - **A)** 164 | ```java 165 | try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { 166 | Future future = executor.submit(task); 167 | System.out.println(future.get()); 168 | } 169 | ``` 170 | - This option is incorrect because it doesn't handle the potential `InterruptedException` and `ExecutionException` that `future.get()` can throw. 171 | 172 | - **B)** 173 | ```java 174 | try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { 175 | Future future = executor.submit(task); 176 | Integer result = future.get(1, TimeUnit.SECONDS); 177 | System.out.println(result); 178 | } 179 | ``` 180 | - This option is incorrect because it doesn't handle the potential exceptions (`InterruptedException`, `ExecutionException`, and `TimeoutException`) that `future.get(long, TimeUnit)` can throw. 181 | 182 | - **C)** 183 | ```java 184 | try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { 185 | Future future = executor.submit(task); 186 | executor.shutdown(); 187 | System.out.println(future.get()); 188 | } 189 | ``` 190 | - This option is incorrect because it unnecessarily calls `executor.shutdown()`. In a `try-with-resources` block, the `ExecutorService` is automatically closed when the block exits. Also, it doesn't handle the potential exceptions from `future.get()`. 191 | 192 | - **D)** 193 | ```java 194 | try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { 195 | Future future = executor.submit(task); 196 | try { 197 | Integer result = future.get(); 198 | System.out.println(result); 199 | } catch (InterruptedException | ExecutionException e) { 200 | e.printStackTrace(); 201 | } 202 | } 203 | ``` 204 | - This option is correct. It uses `try-with-resources` to automatically close the `ExecutorService`, properly submits the `Callable` task, retrieves the result using `Future.get()`, and handles the potential `InterruptedException` and `ExecutionException` that might be thrown. 205 | 206 | 207 | 208 | **7. The correct answer is A.** 209 | 210 | **Explanation:** 211 | 212 | - **A)** `ConcurrentHashMap` allows concurrent read and write operations, and retrieval operations do not block even when updates are being made. 213 | - This statement is correct. `ConcurrentHashMap` is designed to handle concurrent access, allowing multiple threads to read and write simultaneously without blocking read operations during updates. 214 | 215 | - **B)** `CopyOnWriteArrayList` is optimized for scenarios with a high number of write operations compared to read operations. 216 | - This statement is incorrect. `CopyOnWriteArrayList` is optimized for scenarios where read operations are far more frequent than write operations because it creates a new copy of the array on each write, which can be costly if writes are frequent. 217 | 218 | - **C)** `ConcurrentSkipListSet` does not kept elements sorted. 219 | - This statement is incorrect. `ConcurrentSkipListSet` keep elements according to their natural ordering, or by a `Comparator` provided at set creation time. 220 | 221 | - **D)** `BlockingQueue` implementations like `LinkedBlockingQueue` allow elements to be added and removed concurrently without any internal locking mechanisms. 222 | - This statement is incorrect. `BlockingQueue` implementations like `LinkedBlockingQueue` do use internal locking mechanisms to handle concurrent access safely. 223 | 224 | 225 | 226 | **8. The correct answer is B.** 227 | 228 | **Explanation:** 229 | 230 | - **A)** Parallel streams always improve the performance of a program by utilizing multiple threads. 231 | - This statement is incorrect because parallel streams do not always improve performance. The overhead of managing multiple threads can sometimes outweigh the benefits, especially for small datasets or simple operations. 232 | 233 | - **B)** Parallel streams can lead to incorrect results if the operations performed are not thread-safe. 234 | - This statement is correct. When using parallel streams, care must be taken to ensure that the operations performed on the elements are thread-safe. Failure to do so can lead to race conditions and incorrect results. 235 | 236 | - **C)** The order of elements in a parallel stream is always preserved compared to the original stream. 237 | - This statement is incorrect. The order of elements in a parallel stream is not guaranteed to be the same as in the original stream unless special care is taken to preserve the order, such as using ordered stream operations. 238 | 239 | - **D)** Using parallel streams guarantees that the operations on elements will execute in a fixed order. 240 | - This statement is incorrect because parallel streams do not guarantee the order of execution of operations on elements. The operations may execute in a non-deterministic order due to the concurrent nature of parallel processing. 241 | 242 | 243 | 244 | **9. The correct answer is B.** 245 | 246 | **Explanation:** 247 | 248 | - **A)** 249 | ```java 250 | int sum = numbers.parallelStream().reduce(1, Integer::sum); 251 | System.out.println(sum); 252 | ``` 253 | - This option is incorrect because it uses `1` as the identity value. The identity value for sum should be `0`, as it is the neutral element for addition. Starting the reduction with `1` will result in an incorrect sum that is incremented by `1`. 254 | 255 | - **B)** 256 | ```java 257 | int sum = numbers.parallelStream().reduce(0, Integer::sum).collect(); 258 | System.out.println(sum); 259 | ``` 260 | - This option is correct. It correctly uses `parallelStream()` to create a parallel stream and the `reduce` method with the identity value `0` and the method reference `Integer::sum` to sum the elements. 261 | 262 | - **C)** 263 | ```java 264 | int sum = numbers.stream().reduce(0, Integer::sum); 265 | System.out.println(sum); 266 | ``` 267 | - This option is incorrect because it uses a sequential stream (`stream()`) instead of a parallel stream. While it correctly sums the elements, it does not demonstrate the use of a parallel stream as specified in the question. 268 | 269 | - **D)** 270 | ```java 271 | int sum = numbers.parallelStream().collect(reduce(0, Integer::sum)); 272 | System.out.println(sum); 273 | ``` 274 | - This option is incorrect because it attempts to use the `collect()` method in combination with `reduce()`, which is not the correct syntax. The `collect()` method is used for mutable reduction and is typically used with collectors, not with the `reduce()` operation directly. -------------------------------------------------------------------------------- /ch12a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter TWELVE" 5 | subtitle: "File I/O and Serialization" 6 | exam_objectives: 7 | - "Read and write console and file data using I/O streams." 8 | - "Serialize and de-serialize Java objects." 9 | - "Construct, traverse, create, read, and write Path objects and their properties using the java.nio.file API." 10 | --- 11 | 12 | ## Answers 13 | **1. The correct answer is D.** 14 | 15 | **Explanation:** 16 | 17 | - **A)** `/home/user` 18 | - This option is incorrect. The `resolve` method appends the given path to the base path. It does not return the base path alone. 19 | 20 | - **B)** `/home/user/documents` 21 | - This option is incorrect. The `resolve` method includes the entire relative path provided as an argument, not just part of it. 22 | 23 | - **C)** `/documents/notes.txt` 24 | - This option is incorrect. The `resolve` method combines the base path with the given relative path; it does not replace the base path with the relative path. 25 | 26 | - **D)** `/home/user/documents/notes.txt` 27 | - This option is correct. The `resolve` method appends the relative path to the base path, resulting in `/home/user/documents/notes.txt`. 28 | 29 | 30 | 31 | **2. The correct answer is C.** 32 | 33 | **Explanation:** 34 | 35 | - **A)** `/home/user/../documents/./notes.txt` 36 | - This option is incorrect. The `normalize` method removes redundant `.` and `..` elements, so it wouldn't leave the path as is. 37 | 38 | - **B)** `/home/user/documents/notes.txt` 39 | - This option is incorrect. While the `.` is removed, the `..` navigates one directory up, resulting in an incorrect final path. 40 | 41 | - **C)** `/home/documents/notes.txt` 42 | - This option is correct. The `normalize` method processes the path by removing the `.` and moving one directory up due to `..`, resulting in `/home/documents/notes.txt`. 43 | 44 | - **D)** `/documents/notes.txt` 45 | - This option is incorrect. The `normalize` method does not completely remove the leading part of the path up to `documents`. It only processes the `.` and `..` elements. 46 | 47 | 48 | 49 | **3. The correct answer is B.** 50 | 51 | **Explanation:** 52 | 53 | - **A)** `FileOutputStream` 54 | - This option is incorrect. `FileOutputStream` is used for writing binary data to a file, not for reading character streams. 55 | 56 | - **B)** `FileReader` 57 | - This option is correct. `FileReader` is designed for reading character streams from a file, making it the appropriate class for this purpose. 58 | 59 | - **C)** `BufferedOutputStream` 60 | - This option is incorrect. `BufferedOutputStream` is used to write binary data to an output stream, buffering the data for efficient writing. It is not used for reading character streams. 61 | 62 | - **D)** `ObjectInputStream` 63 | - This option is incorrect. `ObjectInputStream` is used for deserializing objects from an input stream, not for reading character streams. 64 | 65 | 66 | 67 | **4. The correct answer is C.** 68 | 69 | **Explanation:** 70 | 71 | - **A)** 72 | ```java 73 | Path source = Paths.get("source.txt"); 74 | Path target = Paths.get("target.txt"); 75 | Files.copy(source, target, StandardCopyOption.ATOMIC_MOVE); 76 | ``` 77 | - This option is incorrect. `StandardCopyOption.ATOMIC_MOVE` is used for moving files atomically, not for copying. It does not ensure that an existing file is overwritten. 78 | 79 | - **B)** 80 | ```java 81 | Path source = Paths.get("source.txt"); 82 | Path target = Paths.get("target.txt"); 83 | Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); 84 | ``` 85 | - This option is incorrect. `Files.move` is used to move or rename a file, not to copy it. `StandardCopyOption.REPLACE_EXISTING` ensures the target file is overwritten during a move, not a copy. 86 | 87 | - **C)** 88 | ```java 89 | Path source = Paths.get("source.txt"); 90 | Path target = Paths.get("target.txt"); 91 | Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); 92 | ``` 93 | - This option is correct. `Files.copy` with `StandardCopyOption.REPLACE_EXISTING` ensures the target file is overwritten if it exists, which is the correct way to copy a file with overwriting. 94 | 95 | - **D)** 96 | ```java 97 | Path source = Paths.get("source.txt"); 98 | Path target = Paths.get("target.txt"); 99 | Files.copy(source, target, StandardCopyOption.APPEND); 100 | ``` 101 | - This option is incorrect. `StandardCopyOption.APPEND` does not exist in the `StandardCopyOption` enum, making this code snippet invalid. 102 | 103 | 104 | 105 | **5. The correct answer is D.** 106 | 107 | **Explanation:** 108 | 109 | - **A)** 110 | ```java 111 | Path path = Paths.get("file.txt"); 112 | List lines = Files.readAllBytes(path); 113 | ``` 114 | - This option is incorrect. `Files.readAllBytes(path)` returns a byte array, not a `List`. 115 | 116 | - **B)** 117 | ```java 118 | Path path = Paths.get("file.txt"); 119 | List lines = Files.readString(path); 120 | ``` 121 | - This option is incorrect. `Files.readString(path)` returns a single `String` containing the entire content of the file, not a `List`. 122 | 123 | - **C)** 124 | ```java 125 | Path path = Paths.get("file.txt"); 126 | List lines = Files.lines(path); 127 | ``` 128 | - This option is incorrect. `Files.lines(path)` returns a `Stream`, not a `List`. It provides a lazy-loaded stream of lines. 129 | 130 | - **D)** 131 | ```java 132 | Path path = Paths.get("file.txt"); 133 | List lines = Files.readAllLines(path); 134 | ``` 135 | - This option is correct. `Files.readAllLines(path)` reads all lines from the file and returns them as a `List`, which is the desired behavior. 136 | 137 | 138 | 139 | **6. The correct answer is A.** 140 | 141 | **Explanation:** 142 | 143 | - **A)** 144 | ```java 145 | Path path = Paths.get("output.txt"); 146 | List lines = Arrays.asList("line1", "line2", "line3"); 147 | Files.write(path, lines); 148 | ``` 149 | - This option is correct. `Files.write(path, lines)` writes the given list of strings to the file at the specified path, creating the file if it does not exist. 150 | 151 | - **B)** 152 | ```java 153 | Path path = Paths.get("output.txt"); 154 | List lines = Arrays.asList("line1", "line2", "line3"); 155 | Files.writeString(path, lines); 156 | ``` 157 | - This option is incorrect. `Files.writeString(path, lines)` does not exist. `Files.writeString` expects a single `String` as the second argument, not a `List`. 158 | 159 | - **C)** 160 | ```java 161 | Path path = Paths.get("output.txt"); 162 | List lines = Arrays.asList("line1", "line2", "line3"); 163 | Files.writeLines(path, lines); 164 | ``` 165 | - This option is incorrect. `Files.writeLines(path, lines)` does not exist. There is no such method in the `Files` class. 166 | 167 | - **D)** 168 | ```java 169 | Path path = Paths.get("output.txt"); 170 | List lines = Arrays.asList("line1", "line2", "line3"); 171 | Files.write(path, lines, StandardOpenOption.READ); 172 | ``` 173 | - This option is incorrect. `StandardOpenOption.READ` is not a valid option for writing files. It is used for reading files. 174 | 175 | 176 | 177 | **7. The correct answer is B.** 178 | 179 | **Explanation:** 180 | 181 | - **A)** 182 | ```java 183 | BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 184 | attrs.lastModifiedTime(); 185 | ``` 186 | - This option is incorrect. `attrs.lastModifiedTime()` retrieves the last modified time of the file, not the creation time. 187 | 188 | - **B)** 189 | ```java 190 | BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 191 | attrs.creationTime(); 192 | ``` 193 | - This option is correct. `attrs.creationTime()` retrieves the creation time of the file, which is the correct method from `BasicFileAttributes` for this purpose. 194 | 195 | - **C)** 196 | ```java 197 | BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 198 | attrs.lastAccessTime(); 199 | ``` 200 | - This option is incorrect. `attrs.lastAccessTime()` retrieves the last access time of the file, not the creation time. 201 | 202 | - **D)** 203 | ```java 204 | BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); 205 | attrs.size(); 206 | ``` 207 | - This option is incorrect. `attrs.size()` retrieves the size of the file, not the creation time. 208 | 209 | 210 | **8. The correct answer is D.** 211 | 212 | **Explanation:** 213 | 214 | - **A)** 215 | ```java 216 | Path start = Paths.get("start_directory"); 217 | Files.walkFileTree(start, new SimpleFileVisitor() { 218 | @Override 219 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 220 | return FileVisitResult.SKIP_SUBTREE; 221 | } 222 | }); 223 | ``` 224 | - This option is incorrect. `FileVisitResult.SKIP_SUBTREE` will skip the traversal of the entire subtree, not allowing the complete traversal of the directory tree. 225 | 226 | - **B)** 227 | ```java 228 | Path start = Paths.get("start_directory"); 229 | Files.walkFileTree(start, new SimpleFileVisitor() { 230 | @Override 231 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 232 | throw new IOException("Error visiting file"); 233 | } 234 | }); 235 | ``` 236 | - This option is incorrect. Throwing an `IOException` inside `visitFile` will stop the traversal due to an unhandled exception. 237 | 238 | - **C)** 239 | ```java 240 | Path start = Paths.get("start_directory"); 241 | Files.walkFileTree(start, new SimpleFileVisitor() { 242 | @Override 243 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 244 | System.out.println("Visited file: " + file); 245 | return FileVisitResult.TERMINATE; 246 | } 247 | }); 248 | ``` 249 | - This option is incorrect. The use of `FileVisitResult.TERMINATE` will stop the traversal after visiting the first file, not allowing the complete traversal of the directory tree. 250 | 251 | - **D)** 252 | ```java 253 | Path start = Paths.get("start_directory"); 254 | Files.walkFileTree(start, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, new SimpleFileVisitor() { 255 | @Override 256 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { 257 | System.out.println("Visited file: " + file); 258 | return FileVisitResult.CONTINUE; 259 | } 260 | 261 | @Override 262 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { 263 | return FileVisitResult.CONTINUE; 264 | } 265 | 266 | @Override 267 | public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { 268 | return FileVisitResult.CONTINUE; 269 | } 270 | 271 | @Override 272 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { 273 | return FileVisitResult.CONTINUE; 274 | } 275 | }); 276 | ``` 277 | - This option is correct. It uses `Files.walkFileTree` with `SimpleFileVisitor`, specifying no special `FileVisitOption` and setting the maximum depth to `Integer.MAX_VALUE`, ensuring full traversal of the directory tree. Additionally, it correctly handles directory pre-visit, file visit, file visit failure, and directory post-visit events. 278 | 279 | 280 | 281 | **9. The correct answer is B.** 282 | 283 | **Explanation:** 284 | 285 | - **A)** 286 | 287 | ```java 288 | class Animal implements Serializable { 289 | private static final long serialVersionUID = 1L; 290 | private String species; 291 | private int age; 292 | 293 | public Animal(String species, int age) { 294 | this.species = species; 295 | this.age = age; 296 | } 297 | } 298 | 299 | Animal animal = new Animal("Lion", 5); 300 | try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("animal.ser"))) { 301 | ois.writeObject(animal); 302 | } catch (IOException e) { 303 | e.printStackTrace(); 304 | } 305 | ``` 306 | - This option is incorrect. `ObjectInputStream` is used for deserialization (reading objects from a stream), not serialization. It should be `ObjectOutputStream`. 307 | 308 | - **B)** 309 | 310 | ```java 311 | class Animal implements Serializable { 312 | private static final long serialVersionUID = 1L; 313 | private String species; 314 | private int age; 315 | 316 | public Animal(String species, int age) { 317 | this.species = species; 318 | this.age = age; 319 | } 320 | } 321 | 322 | Animal animal = new Animal("Lion", 5); 323 | try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("animal.ser"))) { 324 | oos.writeObject(animal); 325 | } catch (IOException e) { 326 | e.printStackTrace(); 327 | } 328 | ``` 329 | - This option is correct. `ObjectOutputStream` is used to serialize an object to a file, which is what this code snippet does correctly. 330 | 331 | - **C)** 332 | 333 | ```java 334 | class Animal { 335 | private String species; 336 | private int age; 337 | 338 | public Animal(String species, int age) { 339 | this.species = species; 340 | this.age = age; 341 | } 342 | } 343 | 344 | Animal animal = new Animal("Lion", 5); 345 | try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("animal.ser"))) { 346 | oos.writeObject(animal); 347 | } catch (IOException e) { 348 | e.printStackTrace(); 349 | } 350 | ``` 351 | - This option is incorrect. The `Animal` class does not implement `Serializable`, so it cannot be serialized using `ObjectOutputStream`. 352 | 353 | - **D)** 354 | 355 | ```java 356 | class Animal implements Serializable { 357 | private static final long serialVersionUID = 1L; 358 | private String species; 359 | private int age; 360 | 361 | public Animal(String species, int age) { 362 | this.species = species; 363 | this.age = age; 364 | } 365 | } 366 | 367 | Animal animal = new Animal("Lion", 5); 368 | try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("animal.ser"))) { 369 | bos.write(animal); 370 | } catch (IOException e) { 371 | e.printStackTrace(); 372 | } 373 | ``` 374 | - This option is incorrect. `BufferedOutputStream` cannot be used to write objects directly; `ObjectOutputStream` should be used for serialization. 375 | -------------------------------------------------------------------------------- /ch13a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter THIRTEEN" 5 | subtitle: "The Java Platform Module System" 6 | exam_objectives: 7 | - "Define modules and expose module content, including that by reflection, and declare module dependencies, define services, providers, and consumers." 8 | - "Compile Java code, create modular and non-modular jars, runtime images, and implement migration to modules using unnamed and automatic modules." 9 | --- 10 | 11 | ## Answers 12 | **1. The correct answers are A and C.** 13 | 14 | **Explanation:** 15 | 16 | - **A)** Automatic module 17 | - This option is correct. An automatic module is created from a JAR file that is placed on the module path but does not have a module descriptor (`module-info.java`). The module system infers a module name from the JAR file name and exports all packages in the JAR. 18 | 19 | - **B)** Default module 20 | - This option incorrect. There is no concept of a "default module" in JPMS. The term might be confused with unnamed modules or other types of configurations, but it is not a recognized type. 21 | 22 | - **C)** Unnamed module 23 | - This option is correct. The unnamed module is a special module that includes all classes on the classpath. It does not have a module descriptor and can access other unnamed modules but cannot be required by named modules. 24 | 25 | - **D)** Core module 26 | - This option is incorrect. There is no specific type called "core module" in JPMS. JPMS does not categorize modules this way. 27 | 28 | - **E)** Primary module 29 | - This option is incorrect. Similar to "core module," there is no type called "primary module" in JPMS. 30 | 31 | 32 | 33 | **2. The correct answer is D.** 34 | 35 | **Explanation:** 36 | 37 | - **A)** `module com.example { export com.example.api; }` 38 | - This option is incorrect. In this case, `exports`is missing an "s". The correct syntax to export a package would be `exports com.example.api;`. 39 | 40 | - **B)** `declare module com.example { }` 41 | - This option is incorrect. There is no `declare` keyword used in the JPMS for defining a module. 42 | 43 | - **C)** `create module com.example { requires java.base; }` 44 | - This option is incorrect. The correct syntax does not use the `create` keyword for module declaration. 45 | 46 | - **D)** `module com.example { }` 47 | - This option is correct. This is the correct way to declare a module named `com.example` without any additional requirements. 48 | 49 | - **E)** `module com.example requires java.base;` 50 | - This option is incorrect. The syntax is invalid because it lacks braces `{ }` to define the module body. 51 | 52 | 53 | 54 | **3. The correct answer is A.** 55 | 56 | **Explanation:** 57 | 58 | - **A)** `module com.example { exports com.example.internal to com.example.client; }` 59 | - This option is correct. The `exports` directive with the `to` clause restricts the export of the `com.example.internal` package to only the specified module `com.example.client`. 60 | 61 | - **B)** `module com.example { opens com.example.internal to com.example.client; }` 62 | - This option is incorrect. The `opens` directive is used for reflection purposes, not for compile-time access control. 63 | 64 | - **C)** `module com.example { requires com.example.internal; }` 65 | - This option is incorrect. The `requires` directive is used to specify module dependencies, not to control package accessibility. 66 | 67 | - **D)** `module com.example { provides com.example.internal to com.example.client; }` 68 | - This option is incorrect. The `provides` directive is used to specify service providers in the module system, not for restricting package access. 69 | 70 | - **E)** `module com.example { uses com.example.internal; }` 71 | - This option is incorrect. The `uses` directive is used to specify service consumers in the module system, not for restricting package access. 72 | 73 | 74 | 75 | **4. The correct answer is B.** 76 | 77 | **Explanation:** 78 | 79 | - **A)** The `com.example.client` module can access the `com.example.api` package for deep reflection. 80 | - This option is incorrect. The `com.example.api` package is exported, not opened, meaning it is available for use but not for deep reflection by other modules. 81 | 82 | - **B)** The `com.example.client` module cannot access the `com.example.api` package for deep reflection. 83 | - This option is correct. The `com.example.api` package is not opened for deep reflection; it is only exported for use by other modules. 84 | 85 | - **C)** The `com.example.api` package is opened to all modules for deep reflection. 86 | - This option is incorrect. The `com.example.api` package is exported to all modules, but it is not opened for deep reflection to any module. 87 | 88 | - **D)** The `com.example.internal` package is exported to the `com.example.client` module. 89 | - This option is incorrect. The `com.example.internal` package is opened to `com.example.client` for deep reflection but not exported. 90 | 91 | - **E)** The `com.example.api` package is exported to the `com.example.client` module for deep reflection. 92 | - This option is incorrect. The `com.example.api` package is exported to the `com.example.client` module, but exporting does not include deep reflection capabilities. 93 | 94 | 95 | 96 | **5. The correct answer is D.** 97 | 98 | **Explanation:** 99 | 100 | - **A)** The `java.base` module provides the Swing and AWT libraries for building graphical user interfaces. 101 | - This option is incorrect. The `java.base` module does not provide the Swing and AWT libraries. These libraries are provided by the `java.desktop` module. 102 | 103 | - **B)** The `java.logging` module is responsible for handling collections, including lists, sets, and maps. 104 | - This option is incorrect. The `java.logging` module is responsible for the logging framework in Java, not for handling collections. The collections framework is part of the `java.base` module. 105 | 106 | - **C)** The `java.desktop` module provides the classes for implementing standard input and output streams. 107 | - This option is incorrect. The `java.desktop` module includes classes for building graphical user interfaces (Swing and AWT), not for standard input and output streams. Standard I/O is part of the `java.base` module. 108 | 109 | - **D)** The `java.xml` module includes the classes for processing XML documents. 110 | - This option is correct. The `java.xml` module includes classes for processing XML documents, such as those for parsing and transforming XML using APIs like DOM, SAX, and StAX. 111 | 112 | - **E)** The `java.naming` module provides APIs for accessing and processing annotations. 113 | - This option is incorrect. The `java.naming` module provides APIs for accessing naming and directory services (JNDI), not for processing annotations. Annotations are part of the `java.base` module. 114 | 115 | 116 | 117 | **6. The correct answer is C.** 118 | 119 | **Explanation:** 120 | 121 | - **A)** `javac -d out src/com.example/module-info.java src/com.example/com/example/*.java` 122 | - This option is incorrect. While it correctly specifies the output directory and the source files, it does not use the `--module-source-path` option and does not specify the module name with `-m`. 123 | 124 | - **B)** `javac -sourcepath src -d out com.example/module-info.java com.example/com/example/*.java` 125 | - This option is incorrect. The `-sourcepath` option is not used for module compilation. The correct option should be `--module-source-path`. 126 | 127 | - **C)** `javac -d out --module-source-path src -m com.example` 128 | - This option is correct. The `javac -d out --module-source-path src -m com.example` command correctly compiles the module `com.example` located in the `src` directory and outputs the compiled classes to the `out` directory. 129 | 130 | - **D)** `javac -modulepath out -d src src/com.example/module-info.java src/com.example/com/example/*.java` 131 | - This option is incorrect. The `-modulepath` option is incorrectly placed, and the source and destination directories are swapped. 132 | 133 | - **E)** `javac --module-path src --module com.example -d out` 134 | - This option is incorrect. The command incorrectly uses `--module-path` instead of `--module-source-path` and the module name is specified with `--module` instead of `-m`. 135 | 136 | 137 | 138 | **7. The correct answer is A.** 139 | 140 | **Explanation:** 141 | 142 | - **A)** `javac --module-source-path src -d out $(find src -name "*.java")` 143 | - This option is correct. The command `javac --module-source-path src -d out $(find src -name "*.java")` correctly compiles both modules by specifying the module source path and finding all Java files in the source directory. 144 | 145 | - **B)** `javac -d out --module com.foo,com.bar --module-source-path src` 146 | - This option is incorrect. The `--module` option does not accept multiple modules separated by commas in this context. 147 | 148 | - **C)** `javac -sourcepath src -d out src/com.foo/module-info.java src/com.foo/com/foo/*.java src/com.bar/module-info.java src/com.bar/com/bar/*.java` 149 | - This option is incorrect. Although it specifies the source files, it does not use the `--module-source-path` option and is unnecessarily verbose. 150 | 151 | - **D)** `javac -modulepath src -d out src/com.foo/*.java src/com.bar/*.java` 152 | - This option is incorrect. The `-modulepath` option is misused, and the path should point to the directory containing the module source code. 153 | 154 | - **E)** `javac --module-source-path src/com.foo,src/com.bar -d out` 155 | - This option is incorrect. The `--module-source-path` option should point to the base directory (`src`), not individual module directories. 156 | 157 | 158 | 159 | **8. The correct answer is C.** 160 | 161 | **Explanation:** 162 | 163 | - **A)** `requires com.example.Service with com.provider.ServiceImpl;` 164 | - This option is incorrect. The `requires` keyword is used to declare dependencies on other modules, not for specifying service providers. 165 | 166 | - **B)** `exports com.example.Service with com.provider.ServiceImpl;` 167 | - This option is incorrect. The `exports` keyword is used to make packages accessible to other modules, not for specifying service providers. 168 | 169 | - **C)** `provides com.example.Service with com.provider.ServiceImpl;` 170 | - This option is correct. The `provides com.example.Service with com.provider.ServiceImpl;` statement correctly specifies that the `com.provider` module provides an implementation of the `com.example.Service`. 171 | 172 | - **D)** `uses com.example.Service with com.provider.ServiceImpl;` 173 | - This option is incorrect. The `uses` keyword is used to declare that the module relies on a service but does not provide an implementation. 174 | 175 | 176 | 177 | **9. The correct answer is D.** 178 | 179 | **Explanation:** 180 | 181 | - **A)** `java --describe-module com.example/module-info.java` 182 | - This option is incorrect. The `--describe-module` option is not used with a specific file path like `module-info.java`; it requires a module name. 183 | 184 | - **B)** `javac --describe-module com.example` 185 | - This option is incorrect. The `--describe-module` option is not valid for the `javac` command; it is used with the `java` command. 186 | 187 | - **C)** `jar --describe-module com.example` 188 | - This option is incorrect. The `--describe-module` option is not valid for the `jar` command; it is used with the `java` command. 189 | 190 | - **D)** `java --describe-module com.example` 191 | - This option is correct. The `java --describe-module com.example` command correctly describes the module `com.example` using the `--describe-module` option. 192 | 193 | 194 | 195 | **10. The correct answers are B and C.** 196 | 197 | **Explanation:** 198 | 199 | - **A)** `jdeps --list-deps example.jar` 200 | - This option is incorrect. The `--list-deps` option does not exist for `jdeps`. 201 | 202 | - **B)** `jdeps -verbose example.jar` 203 | - This option is correct. While `-verbose` is a valid option, it provides more information. 204 | 205 | - **C)** `jdeps -s example.jar` 206 | - This option is correct. The `-s` option with `jdeps` provides a summary of the dependencies of the `example.jar` file. 207 | 208 | - **D)** `jdeps --check example.jar` 209 | - This option is incorrect. The `--check` option does not exist for `jdeps`. 210 | 211 | 212 | 213 | **11. The correct answer is A.** 214 | 215 | **Explanation:** 216 | 217 | - **A)** `jmod create --class-path mods/com.example --output com.example.jmod` 218 | - This option is correct. It uses the correct syntax for the `jmod` command to create a JMOD file. The `create` operation is specified, followed by the `--class-path` option to indicate the source directory, and finally the name of the output JMOD file. This command will create a JMOD file named `com.example.jmod` using the contents of the `mods/com.example` directory. 219 | 220 | - **B)** `jmod --create --class-path mods/com.example --output com.example.jmod` 221 | - This option is incorrect. The `create` operation in the `jmod` command should not be prefixed with `--`. The correct format is `jmod create`, not `jmod --create`. The rest of the command is correct, but this syntax error makes the entire command invalid. 222 | 223 | - **C)** `jmod --create --dir mods/com.example --output com.example.jmod` 224 | - This option is incorrect. First, like option B, it incorrectly uses `--create` instead of `create`. Second, it uses the `--dir` option, which is not used for creating JMOD files, but for specifying the output directory when extracting files from a JMOD. When creating a JMOD file, we use `--class-path` to specify the source directory. The `--output` option is also not a valid option for the `jmod` command. 225 | 226 | - **D)** `jmod create --dir mods/com.example --output com.example.jmod` 227 | - This option is incorrect. It uses the `--dir` option instead of `--class-path` for specifying the source directory, and it incorrectly includes an `--output` option, which is not valid for the `jmod` command. When creating a JMOD file, the output file name is simply specified as the last argument, not with an `--output` option. 228 | 229 | 230 | 231 | **12. The correct answer is B.** 232 | 233 | **Explanation:** 234 | 235 | - **A)** `jlink --module-path java.base:com.example --output myimage` 236 | - This option is incorrect. The `--module-path` option should specify the directory containing the modules, not the module names directly. 237 | 238 | - **B)** `jlink --module-path mods --add-modules java.base,com.example --output myimage` 239 | - This option is correct. The command `jlink --module-path mods --add-modules java.base,com.example --output myimage` correctly specifies the module path and adds the necessary modules, outputting the custom runtime image to the `myimage` directory. 240 | 241 | - **C)** `jlink --add-modules java.base,com.example --image myimage` 242 | - This option is incorrect. The `--image` option is not valid; the correct option is `--output`. 243 | 244 | - **D)** `jlink --modules java.base,com.example --dir myimage` 245 | - This option is incorrect. The `--modules` option is incorrect; the correct option is `--add-modules`, and `--dir` should be `--output`. 246 | 247 | 248 | 249 | **13. The correct answer is D.** 250 | 251 | **Explanation:** 252 | 253 | - **A)** An unnamed module can depend on named modules and other unnamed modules. 254 | - This option is incorrect. An unnamed module can depend on named modules, which is true. However, unnamed modules cannot depend on other unnamed modules. Unnamed modules are created when classes are loaded from the classpath, and they cannot read other unnamed modules. They can only read the named modules of the platform and other modules explicitly added to the module path. 255 | 256 | - **B)** Automatic modules must have a `module-info.java` file to be placed on the module path. 257 | - This option is incorrect. Automatic modules do not require a `module-info.java` file. Their module name is inferred from the JAR file name. 258 | 259 | - **C)** Unnamed modules can export their packages to named modules using `module-info.java`. 260 | - This option is incorrect. Unnamed modules cannot export packages because they do not use `module-info.java`. 261 | 262 | - **D)** An automatic module is created when a JAR file without a `module-info.java` is placed on the module path, and it can read all other modules. 263 | - This option is correct. An automatic module is created by placing a JAR file without a `module-info.java` on the module path. This automatic module can read all other modules, both named and unnamed. 264 | -------------------------------------------------------------------------------- /ch11a.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: answer 3 | 4 | title: "Chapter ELEVEN" 5 | subtitle: "The Date API" 6 | exam_objectives: 7 | - "Manipulate date, time, duration, period, instant and time-zone objects including daylight saving time using Date-Time API." 8 | --- 9 | 10 | ## Answers 11 | **1. The correct answer is D.** 12 | 13 | **Explanation:** 14 | 15 | - **A)** `LocalDate.of(2014);` 16 | - This option is incorrect. The `LocalDate.of()` method requires a year, month, and day to be specified. Providing only a year will result in a compilation error. 17 | 18 | - **B)** `LocalDate.with(2014, 1, 30);` 19 | - This option is incorrect. The `LocalDate` class does not have a `with()` method that takes three int arguments for year, month, and day. The correct method to use is `LocalDate.of(int year, int month, int dayOfMonth)`. 20 | 21 | - **C)** `LocalDate.of(2014, 0, 30);` 22 | - This option is incorrect. The month value is 0, but months in the `LocalDate` class are indexed starting from 1. Valid month values are from 1 to 12, so using 0 will throw a `DateTimeException`. 23 | 24 | - **D)** `LocalDate.now().plusDays(5);` 25 | - This option is correct. It accurately obtains the current date using `LocalDate.now()` and then adds 5 days to it using the `plusDays()` method. This will create a new `LocalDate` object representing the date 5 days from now. 26 | 27 | 28 | **2. The correct answer is C.** 29 | 30 | **Explanation:** 31 | 32 | - **A)** A `LocalDate` instance representing `2014-01-02` 33 | - This option is incorrect. The `atTime` method does not return a `LocalDate`, but rather combines the `LocalDate` with the provided time parameters to create a `LocalDateTime` object. 34 | 35 | - **B)** A `LocalTime` instance representing `14:30:59:999999` 36 | - This option is incorrect. The `atTime` method does not return a `LocalTime`, but rather combines the `LocalDate` with the provided time parameters to create a `LocalDateTime` object. Additionally, `LocalTime` does not have nanosecond precision, so `999999` nanoseconds would be an invalid `LocalTime`. 37 | 38 | - **C)** A `LocalDateTime` instance representing `2014-01-02 14:30:59:999999` 39 | - This option is correct. The `atTime` method takes a `LocalDate` and combines it with the provided hour, minute, second, and nanosecond parameters to create a `LocalDateTime` object representing that date and time. The resulting `LocalDateTime` will be `2014-01-02 14:30:59:999999`. 40 | 41 | - **D)** An exception is thrown 42 | - This option is incorrect. The provided parameters of 14 for hour, 30 for minute, 59 for second, and 999999 for nanosecond are all valid values for their respective fields, so combining them with the `LocalDate` will not throw an exception. 43 | 44 | 45 | **3. The correct answers are B and D.** 46 | 47 | **Explanation:** 48 | 49 | - **A)** `YEAR` 50 | - This option is incorrect. `YEAR` is not a valid `ChronoUnit` for `LocalTime`. `LocalTime` represents a time of day without any date information, so units of `YEAR` do not apply. 51 | 52 | - **B)** `NANOS` 53 | - This option is correct. `NANOS` is a valid `ChronoUnit` for `LocalTime`. `LocalTime` has nanosecond precision, so you can perform operations on `LocalTime` using the `NANOS` unit. 54 | 55 | - **C)** `DAY` 56 | - This option is incorrect. `DAY` is not a valid `ChronoUnit` for `LocalTime`. Similar to `YEAR`, `LocalTime` has no concept of days since it only represents a time, not a date. 57 | 58 | - **D)** `HALF_DAYS` 59 | - This option is correct. `HALF_DAYS` is a valid `ChronoUnit` for `LocalTime`. A day can be divided into two 12-hour periods (AM and PM), so `HALF_DAYS` can be used with `LocalTime` to represent a difference or addition of 12 hour chunks of time. 60 | 61 | 62 | **4. The correct answers are B and C.** 63 | 64 | **Explanation:** 65 | 66 | - **A)** `java.time.Period` implements `java.time.temporal.Temporal` 67 | - This option is incorrect. `java.time.Period` does not implement the `java.time.temporal.Temporal` interface. `Period` represents a span of time between two dates and is not itself a temporal object. 68 | 69 | - **B)** `java.time.Instant` implements `java.time.temporal.Temporal` 70 | - This option is correct. `java.time.Instant` does implement the `java.time.temporal.Temporal` interface. `Instant` represents a point in time on the timeline and can be thought of as a temporal object. 71 | 72 | - **C)** `LocalDate` and `LocalTime` are thread-safe. 73 | - This option is correct. `LocalDate` and `LocalTime` are indeed thread-safe. All the core Java Time classes, including `LocalDate`, `LocalTime`, `LocalDateTime`, `Instant`, etc., are designed to be immutable and thread-safe. 74 | 75 | - **D)** `LocalDateTime.now()` will return the current time in UTC zone 76 | - This option is incorrect. `LocalDateTime.now()` returns the current date and time using the system clock in the default time zone, not necessarily in the UTC zone. To get the current time in UTC, you would use `LocalDateTime.now(ZoneOffset.UTC)` or `Instant.now()`. 77 | 78 | 79 | **5. The correct answer is A.** 80 | 81 | **Explanation:** 82 | 83 | - **A)** `int nanos = i.getNano();` 84 | - This option is correct. The `Instant` class does have a `getNano()` method that returns the nanosecond part of the `Instant` as an `int`. This is a valid way to get the nanoseconds. 85 | 86 | - **B)** `long nanos = i.get(ChronoField.NANOS);` 87 | - This option is incorrect. You can use the `get(TemporalField)` method of `Instant` to get the value of a specific `ChronoField`. Passing `ChronoField.NANO_OF_SECOND` (not `ChronoField.NANO`) will return the nanosecond part of the `Instant` as a `long`. 88 | 89 | - **C)** `long nanos = i.get(ChronoUnit.NANOS);` 90 | - This option is incorrect. While `Instant` does have a `get(TemporalUnit)` method, `ChronoUnit.NANOS` is not a valid argument for it. `ChronoUnit` values are used for durations and periods, not for fields of a temporal object. 91 | 92 | - **D)** `int nanos = i.getEpochNano();` 93 | - This option is incorrect. The `Instant` class does have a `getEpochSecond()` method that returns the number of seconds since the Unix epoch, but there is no corresponding `getEpochNano()` method. 94 | 95 | 96 | 97 | **6. The correct answer is D.** 98 | 99 | **Explanation:** 100 | 101 | - **A)** `P29D` 102 | - This option is incorrect. The `Period.between` method calculates the period between the second date and the first date, in that order. Since the first date (2025-03-20) is later than the second date (2025-02-20), the resulting period will be negative, not positive. 103 | 104 | - **B)** `P-29D` 105 | - This option is incorrect. While the resulting period will be negative, it will not be represented as `-29D`. A `Period` first counts the number of complete months, then the remaining days. 106 | 107 | - **C)** `P1M` 108 | - This option is incorrect. The resulting period will be negative because the first date is later than the second date. 109 | 110 | - **D)** `P-1M` 111 | - This option is correct. The `Period.between` method subtracts the second date from the first date. In this case, `2025-03-20` minus `2025-02-20` results in a period of -1 month, which is represented as `P-1M`. The `Period` class first calculates the difference in complete months, and then any remaining days. Since the difference is exactly one month, the result is `P-1M`. 112 | 113 | 114 | 115 | **7. The correct answer is D.** 116 | 117 | **Explanation:** 118 | 119 | - **A)** `PT5M` 120 | - This option is incorrect. `PT5M` represents a duration of 5 minutes, which would be the result if the second time point was 5 minutes after the first. However, since `LocalTime.of(18, 5)` is being compared to a `LocalDateTime`, this causes an issue because they are not of the same type. 121 | 122 | - **B)** `PT-5M` 123 | - This option is incorrect. `PT-5M` represents a duration of negative 5 minutes. Similar to option A, this would only be the case if the second time point was before the first. The main issue is that there is a type mismatch between `LocalDateTime` and `LocalTime`. 124 | 125 | - **C)** `PT300S` 126 | - This option is incorrect. `PT300S` represents a duration of 300 seconds (or 5 minutes), which again would be the result if the second time point was 5 minutes after the first. However, this still doesn't resolve the type mismatch issue between `LocalDateTime` and `LocalTime`. 127 | 128 | - **D)** An exception is thrown 129 | - This option is correct. An exception is thrown because there is a type mismatch between `LocalDateTime.of(2025, 3, 20, 18, 0)` and `LocalTime.of(18, 5)`. The `Duration.between` method requires two temporal objects of the same type. 130 | 131 | 132 | **8. The correct answers are A and C.** 133 | 134 | **Explanation:** 135 | 136 | - **A)** `DAY_OF_WEEK` 137 | - This option is correct. `DAY_OF_WEEK` is a valid `ChronoField` value for `LocalDate`. It represents the day of the week, an integer from 1 (Monday) to 7 (Sunday), which can be extracted from a `LocalDate`. 138 | 139 | - **B)** `HOUR_OF_DAY` 140 | - This option is incorrect. `HOUR_OF_DAY` is not a valid `ChronoField` value for `LocalDate`. `HOUR_OF_DAY` pertains to `LocalTime` or `LocalDateTime`, which include time components, whereas `LocalDate` only deals with date components. 141 | 142 | - **C)** `DAY_OF_MONTH` 143 | - This option is correct. `DAY_OF_MONTH` is a valid `ChronoField` value for `LocalDate`. It represents the day of the month, which can be extracted from a `LocalDate`. 144 | 145 | - **D)** `MILLI_OF_SECOND` 146 | - This option is incorrect. `MILLI_OF_SECOND` is not a valid `ChronoField` value for `LocalDate`. `MILLI_OF_SECOND` pertains to time components, specifically for `LocalTime` or `LocalDateTime`, and `LocalDate` only deals with date components. 147 | 148 | 149 | 150 | **9. The correct answer is C.** 151 | 152 | **Explanation:** 153 | 154 | - **A)** `ZoneId.ofHours(2);` 155 | - This option is incorrect. The method `ofHours(int)` belongs to the `ZoneOffset` class, not `ZoneId`. 156 | 157 | - **B)** `ZoneId.of("2");` 158 | - This option is incorrect. The format of the offset is incorrect for `ZoneId`. It should be a proper time-zone ID or start with a sign (`+` or `-`). 159 | 160 | - **C)** `ZoneId.of("-1");` 161 | - This option is correct. `ZoneId.of("-1")` is valid since it follows the correct format for time-zone offsets. 162 | 163 | - **D)** `ZoneId.of("America/Canada");` 164 | - This option is incorrect. The format for zone regions should be in the `"Area/City"` format, not `"Area/Country"`. A valid example would be `"America/Montreal"`. 165 | 166 | 167 | **10. The correct answer is D.** 168 | 169 | **Explanation:** 170 | 171 | - **A)** `0` 172 | - This option is incorrect. The method `offset.get(ChronoField.HOUR_OF_DAY)` does not return the hour value of the `ZoneOffset`. `ZoneOffset` represents a time-zone offset from UTC/Greenwich, and calling `get(ChronoField.HOUR_OF_DAY)` on it is not appropriate. 173 | 174 | - **B)** `1` 175 | - This option is incorrect. Similar to option A, the `get` method of `ZoneOffset` with `ChronoField.HOUR_OF_DAY` does not produce this result. The `ZoneOffset` class is not meant to provide such a field directly. 176 | 177 | - **C)** `12:00` 178 | - This option is incorrect. `12:00` is not a valid response for the method call as it implies a time representation, while `ZoneOffset` is dealing with offset values rather than specific time of day values. 179 | 180 | - **D)** An exception is thrown 181 | - This option is correct. An exception is thrown because `ZoneOffset` does not support the field `ChronoField.HOUR_OF_DAY`. The `ZoneOffset` class provides offset values in terms of seconds rather than specific chrono fields like hour of day. 182 | 183 | 184 | **11. The correct answer is A.** 185 | 186 | **Explanation:** 187 | 188 | - **A)** `05:00` 189 | - This option is correct. `ZonedDateTime.of(2025, 02, 28, 5, 0, 0, 0, ZoneId.of("+05:00"))` creates a `ZonedDateTime` instance with the specified date, time, and time zone offset of +05:00. Calling `toLocalTime()` on this instance returns the local time, which is `05:00`, as no conversion to the local time zone of +2:00 is done in this code snippet. 190 | 191 | - **B)** `17:00` 192 | - This option is incorrect. `17:00` would be the time if the code converted the given time (05:00) from the +05:00 time zone to the local time zone of +02:00, which it does not. 193 | 194 | - **C)** `02:00` 195 | - This option is incorrect. `02:00` does not correspond to any logical result based on the given time and time zone offset. 196 | 197 | - **D)** `03:00` 198 | - This option is incorrect. `03:00` also does not correspond to any logical result based on the given time and time zone offset. 199 | 200 | 201 | **12. The correct answer is C.** 202 | 203 | **Explanation:** 204 | 205 | - **A)** `2025-10-04T00:00-03:00[America/Asuncion]` 206 | - This option is incorrect. The initial time is `2025-10-04T00:00-03:00[America/Asuncion]` before DST starts. When 1 hour is added, the time will shift forward by 1 hour, but since DST starts at this moment, the offset will change. 207 | 208 | - **B)** `2025-10-04T01:00-03:00[America/Asuncion]` 209 | - This option is incorrect. Adding 1 hour to the initial time `2025-10-04T00:00-03:00[America/Asuncion]` while considering the start of DST (which typically adds 1 hour to the local time) means that the effective time would be adjusted by the DST transition. 210 | 211 | - **C)** `2025-10-04T02:00-03:00[America/Asuncion]` 212 | - This option is correct. Initially, the time is `2025-10-04T00:00-03:00[America/Asuncion]`. With the addition of 1 hour and considering the DST start at `2025-10-04T00:00`, the time advances to `2025-10-04T02:00-03:00[America/Asuncion]`, as it effectively skips the 01:00 hour. 213 | 214 | - **D)** `2025-10-03T23:00-03:00[America/Asuncion]` 215 | - This option is incorrect. The date and time `2025-10-03T23:00-03:00[America/Asuncion]` does not correlate correctly with the 1 hour addition from the initial time and does not account for the DST transition. 216 | 217 | 218 | **13. The correct answer is B.** 219 | 220 | **Explanation:** 221 | 222 | - **A)** `java.time.ZoneOffset` is a subclass of `java.time.ZoneId`. 223 | - This option is incorrect. `java.time.ZoneOffset` is not a subclass of `java.time.ZoneId`. `java.time.ZoneOffset` is a final class that extends `java.time.ZoneId` but it is not a subclass. 224 | 225 | - **B)** `java.time.Instant` can be obtained from `java.time.ZonedDateTime`. 226 | - This option is correct. `java.time.Instant` can indeed be obtained from `java.time.ZonedDateTime` using the `toInstant()` method. 227 | 228 | - **C)** `java.time.ZoneOffset` can manage DST. 229 | - This option is incorrect. `java.time.ZoneOffset` represents a fixed offset from UTC and does not manage Daylight Saving Time (DST). DST is managed by `java.time.ZoneId`. 230 | 231 | - **D)** `java.time.OffsetDateTime` represents a point in time in the UTC time zone. 232 | - This option is incorrect. `java.time.OffsetDateTime` represents a date-time with an offset from UTC, but it does not necessarily represent a point in the UTC time zone. The offset can be any valid `ZoneOffset`. 233 | 234 | 235 | **14. The correct answer is C.** 236 | 237 | **Explanation:** 238 | 239 | - **A)** `5/7/15 4:00 PM` 240 | - This option is incorrect. The `DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)` method is used to format only the time portion of a `LocalDateTime` object, and it does not include the date. Therefore, the output will not include `5/7/15`. 241 | 242 | - **B)** `5/7/15` 243 | - This option is incorrect. As mentioned earlier, the `DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)` formats only the time portion and does not include the date. Thus, the output `5/7/15` is not possible. 244 | 245 | - **C)** `4:00 PM` 246 | - This option is correct. The `DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)` formats the time portion of the `LocalDateTime` object in a short style. Given the input time `16:00`, in the `Locale.ENGLISH`, the formatted output is `4:00 PM`. 247 | 248 | - **D)** `4:00:00 PM` 249 | - This option is incorrect. The `DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)` formats the time portion without including seconds. Therefore, the output will not include `4:00:00 PM`. 250 | 251 | 252 | **15. The correct answer is D.** 253 | 254 | **Explanation:** 255 | 256 | - **A)** The pattern `HH:mm:ss X` is invalid. 257 | - This option is incorrect. The pattern `HH:mm:ss X` is valid. `HH` represents the hour of the day (00-23), `mm` represents the minute of the hour, `ss` represents the second of the minute, and `X` represents the ISO 8601 time zone offset. 258 | 259 | - **B)** An `OffsetDateTime` is created successfully. 260 | - This option is incorrect. The pattern `HH:mm:ss X` is valid, but the `OffsetDateTime.parse` method requires a date and time format along with the offset. Since the input string `"11:50:20 Z"` does not contain a date part, this will cause a `DateTimeParseException`. 261 | 262 | - **C)** `Z` is an invalid offset. 263 | - This option is incorrect. `Z` is a valid offset representing UTC (Coordinated Universal Time). 264 | 265 | - **D)** An exception is thrown at runtime. 266 | - This option is correct. An exception is thrown at runtime because the input string `"11:50:20 Z"` does not match the expected pattern for an `OffsetDateTime`, which typically includes a date part as well as the time and offset. 267 | -------------------------------------------------------------------------------- /assets/css/style.css: -------------------------------------------------------------------------------- 1 | /*! normalize.css v4.0.0 | MIT License | github.com/necolas/normalize.css */ 2 | 3 | 4 | /** 5 | * 1. Change the default font family in all browsers (opinionated). 6 | * 2. Prevent adjustments of font size after orientation changes in IE and iOS. 7 | */ 8 | 9 | html { 10 | font-family: sans-serif; 11 | /* 1 */ 12 | -ms-text-size-adjust: 100%; 13 | /* 2 */ 14 | -webkit-text-size-adjust: 100%; 15 | /* 2 */ 16 | } 17 | 18 | 19 | /** 20 | * Remove the margin in all browsers (opinionated). 21 | */ 22 | 23 | body { 24 | margin: 0; 25 | } 26 | 27 | 28 | /* HTML5 display definitions 29 | ========================================================================== */ 30 | 31 | 32 | /** 33 | * Add the correct display in IE 9-. 34 | * 1. Add the correct display in Edge, IE, and Firefox. 35 | * 2. Add the correct display in IE. 36 | */ 37 | 38 | article, 39 | aside, 40 | details, 41 | 42 | /* 1 */ 43 | 44 | figcaption, 45 | /*figure,*/ 46 | footer, 47 | header, 48 | main, 49 | 50 | /* 2 */ 51 | 52 | menu, 53 | nav, 54 | section, 55 | summary { 56 | /* 1 */ 57 | display: block; 58 | } 59 | 60 | 61 | /** 62 | * Add the correct display in IE 9-. 63 | */ 64 | 65 | audio, 66 | canvas, 67 | progress, 68 | video { 69 | display: inline-block; 70 | } 71 | 72 | 73 | /** 74 | * Add the correct display in iOS 4-7. 75 | */ 76 | 77 | audio:not([controls]) { 78 | display: none; 79 | height: 0; 80 | } 81 | 82 | 83 | /** 84 | * Add the correct vertical alignment in Chrome, Firefox, and Opera. 85 | */ 86 | 87 | progress { 88 | vertical-align: baseline; 89 | } 90 | 91 | 92 | /** 93 | * Add the correct display in IE 10-. 94 | * 1. Add the correct display in IE. 95 | */ 96 | 97 | template, 98 | 99 | /* 1 */ 100 | 101 | [hidden] { 102 | display: none; 103 | } 104 | 105 | 106 | /* Links 107 | ========================================================================== */ 108 | 109 | 110 | /** 111 | * Remove the gray background on active links in IE 10. 112 | */ 113 | 114 | a { 115 | background-color: transparent; 116 | } 117 | 118 | 119 | /** 120 | * Remove the outline on focused links when they are also active or hovered 121 | * in all browsers (opinionated). 122 | */ 123 | 124 | a:active, 125 | a:hover { 126 | outline-width: 0; 127 | } 128 | 129 | 130 | /* Text-level semantics 131 | ========================================================================== */ 132 | 133 | 134 | /** 135 | * 1. Remove the bottom border in Firefox 39-. 136 | * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari. 137 | */ 138 | 139 | abbr[title] { 140 | border-bottom: none; 141 | /* 1 */ 142 | text-decoration: underline; 143 | /* 2 */ 144 | text-decoration: underline dotted; 145 | /* 2 */ 146 | } 147 | 148 | 149 | /** 150 | * Prevent the duplicate application of `bolder` by the next rule in Safari 6. 151 | */ 152 | 153 | b, 154 | strong { 155 | font-weight: inherit; 156 | } 157 | 158 | 159 | /** 160 | * Add the correct font weight in Chrome, Edge, and Safari. 161 | */ 162 | 163 | b, 164 | strong { 165 | font-weight: bolder; 166 | } 167 | 168 | 169 | /** 170 | * Add the correct font style in Android 4.3-. 171 | */ 172 | 173 | dfn { 174 | font-style: italic; 175 | } 176 | 177 | 178 | /** 179 | * Correct the font size and margin on `h1` elements within `section` and 180 | * `article` contexts in Chrome, Firefox, and Safari. 181 | */ 182 | 183 | h1 { 184 | font-size: 2em; 185 | margin: 0.67em 0; 186 | } 187 | 188 | 189 | /** 190 | * Add the correct background and color in IE 9-. 191 | */ 192 | 193 | mark { 194 | background-color: #ff0; 195 | color: #000; 196 | } 197 | 198 | 199 | /** 200 | * Add the correct font size in all browsers. 201 | */ 202 | 203 | small { 204 | font-size: 80%; 205 | } 206 | 207 | 208 | /** 209 | * Prevent `sub` and `sup` elements from affecting the line height in 210 | * all browsers. 211 | */ 212 | 213 | sub, 214 | sup { 215 | font-size: 75%; 216 | line-height: 0; 217 | position: relative; 218 | vertical-align: baseline; 219 | } 220 | 221 | sub { 222 | bottom: -0.25em; 223 | } 224 | 225 | sup { 226 | top: -0.5em; 227 | } 228 | 229 | 230 | /* Embedded content 231 | ========================================================================== */ 232 | 233 | 234 | /** 235 | * Remove the border on images inside links in IE 10-. 236 | */ 237 | 238 | img { 239 | border-style: none; 240 | } 241 | 242 | 243 | /** 244 | * Hide the overflow in IE. 245 | */ 246 | 247 | svg:not(:root) { 248 | overflow: hidden; 249 | } 250 | 251 | 252 | /* Grouping content 253 | ========================================================================== */ 254 | 255 | 256 | /** 257 | * 1. Correct the inheritance and scaling of font size in all browsers. 258 | * 2. Correct the odd `em` font sizing in all browsers. 259 | */ 260 | 261 | code, 262 | kbd, 263 | pre, 264 | samp { 265 | font-family: monospace, monospace; 266 | /* 1 */ 267 | font-size: 1em; 268 | /* 2 */ 269 | } 270 | 271 | 272 | /** 273 | * Add the correct margin in IE 8. 274 | */ 275 | 276 | /*figure { 277 | margin: 1em 40px; 278 | }*/ 279 | 280 | 281 | /** 282 | * 1. Add the correct box sizing in Firefox. 283 | * 2. Show the overflow in Edge and IE. 284 | */ 285 | 286 | hr { 287 | box-sizing: content-box; 288 | /* 1 */ 289 | height: 0; 290 | /* 1 */ 291 | overflow: visible; 292 | /* 2 */ 293 | } 294 | 295 | 296 | /* Forms 297 | ========================================================================== */ 298 | 299 | 300 | /** 301 | * Change font properties to `inherit` in all browsers (opinionated). 302 | */ 303 | 304 | button, 305 | input, 306 | select, 307 | textarea { 308 | font: inherit; 309 | } 310 | 311 | 312 | /** 313 | * Restore the font weight unset by the previous rule. 314 | */ 315 | 316 | optgroup { 317 | font-weight: bold; 318 | } 319 | 320 | 321 | /** 322 | * Show the overflow in IE. 323 | * 1. Show the overflow in Edge. 324 | * 2. Show the overflow in Edge, Firefox, and IE. 325 | */ 326 | 327 | button, 328 | input, 329 | 330 | /* 1 */ 331 | 332 | select { 333 | /* 2 */ 334 | overflow: visible; 335 | } 336 | 337 | 338 | /** 339 | * Remove the margin in Safari. 340 | * 1. Remove the margin in Firefox and Safari. 341 | */ 342 | 343 | button, 344 | input, 345 | select, 346 | textarea { 347 | /* 1 */ 348 | margin: 0; 349 | } 350 | 351 | 352 | /** 353 | * Remove the inheritence of text transform in Edge, Firefox, and IE. 354 | * 1. Remove the inheritence of text transform in Firefox. 355 | */ 356 | 357 | button, 358 | select { 359 | /* 1 */ 360 | text-transform: none; 361 | } 362 | 363 | 364 | /** 365 | * Change the cursor in all browsers (opinionated). 366 | */ 367 | 368 | button, 369 | [type="button"], 370 | [type="reset"], 371 | [type="submit"] { 372 | cursor: pointer; 373 | } 374 | 375 | 376 | /** 377 | * Restore the default cursor to disabled elements unset by the previous rule. 378 | */ 379 | 380 | [disabled] { 381 | cursor: default; 382 | } 383 | 384 | 385 | /** 386 | * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video` 387 | * controls in Android 4. 388 | * 2. Correct the inability to style clickable types in iOS. 389 | */ 390 | 391 | button, 392 | html [type="button"], 393 | 394 | /* 1 */ 395 | 396 | [type="reset"], 397 | [type="submit"] { 398 | -webkit-appearance: button; 399 | /* 2 */ 400 | } 401 | 402 | 403 | /** 404 | * Remove the inner border and padding in Firefox. 405 | */ 406 | 407 | button::-moz-focus-inner, 408 | input::-moz-focus-inner { 409 | border: 0; 410 | padding: 0; 411 | } 412 | 413 | 414 | /** 415 | * Restore the focus styles unset by the previous rule. 416 | */ 417 | 418 | button:-moz-focusring, 419 | input:-moz-focusring { 420 | outline: 1px dotted ButtonText; 421 | } 422 | 423 | 424 | /** 425 | * Change the border, margin, and padding in all browsers (opinionated). 426 | */ 427 | 428 | fieldset { 429 | border: 1px solid #c0c0c0; 430 | margin: 0 2px; 431 | padding: 0.35em 0.625em 0.75em; 432 | } 433 | 434 | 435 | /** 436 | * 1. Correct the text wrapping in Edge and IE. 437 | * 2. Correct the color inheritance from `fieldset` elements in IE. 438 | * 3. Remove the padding so developers are not caught out when they zero out 439 | * `fieldset` elements in all browsers. 440 | */ 441 | 442 | legend { 443 | box-sizing: border-box; 444 | /* 1 */ 445 | color: inherit; 446 | /* 2 */ 447 | display: table; 448 | /* 1 */ 449 | max-width: 100%; 450 | /* 1 */ 451 | padding: 0; 452 | /* 3 */ 453 | white-space: normal; 454 | /* 1 */ 455 | } 456 | 457 | 458 | /** 459 | * Remove the default vertical scrollbar in IE. 460 | */ 461 | 462 | textarea { 463 | overflow: auto; 464 | } 465 | 466 | 467 | /** 468 | * 1. Add the correct box sizing in IE 10-. 469 | * 2. Remove the padding in IE 10-. 470 | */ 471 | 472 | [type="checkbox"], 473 | [type="radio"] { 474 | box-sizing: border-box; 475 | /* 1 */ 476 | padding: 0; 477 | /* 2 */ 478 | } 479 | 480 | 481 | /** 482 | * Correct the cursor style of increment and decrement buttons in Chrome. 483 | */ 484 | 485 | [type="number"]::-webkit-inner-spin-button, 486 | [type="number"]::-webkit-outer-spin-button { 487 | height: auto; 488 | } 489 | 490 | 491 | /** 492 | * Correct the odd appearance of search inputs in Chrome and Safari. 493 | */ 494 | 495 | [type="search"] { 496 | -webkit-appearance: textfield; 497 | } 498 | 499 | 500 | /** 501 | * Remove the inner padding and cancel buttons in Chrome on OS X and 502 | * Safari on OS X. 503 | */ 504 | 505 | [type="search"]::-webkit-search-cancel-button, 506 | [type="search"]::-webkit-search-decoration { 507 | -webkit-appearance: none; 508 | } 509 | 510 | 511 | /*! END normalize.css v4.0.0 | MIT License | github.com/necolas/normalize.css */ 512 | 513 | 514 | /* Site's CSS */ 515 | 516 | 517 | /* Nav Bar */ 518 | 519 | .nav { 520 | left: 0; 521 | right: 0; 522 | top: 0; 523 | position: relative; 524 | z-index: 5; 525 | background: white; 526 | text-align: right; 527 | } 528 | 529 | .nav .container { 530 | padding: 15px 0; 531 | position: relative; 532 | height: 39px; 533 | } 534 | 535 | .nav .container:before, 536 | .nav .container:after { 537 | content: " "; 538 | display: table; 539 | } 540 | 541 | .nav .menu { 542 | margin-top: 7px; 543 | } 544 | 545 | .nav .title { 546 | margin-top: 5px; 547 | } 548 | .nav .title a { 549 | text-decoration: none; 550 | color: black; 551 | } 552 | 553 | .chapters { 554 | color: #707070; 555 | padding: 26px 20px 24px; 556 | text-decoration: none; 557 | } 558 | 559 | .chapters .icon-book { 560 | margin-right: 5px; 561 | position: relative; 562 | top: 2px; 563 | } 564 | 565 | .dropdown-menu { 566 | position: absolute; 567 | top: 100%; 568 | left: 0; 569 | z-index: 1000; 570 | display: none; 571 | float: left; 572 | min-width: 160px; 573 | padding: 5px 0; 574 | margin: 2px 0 0; 575 | list-style: none; 576 | font-size: 14px; 577 | text-align: left; 578 | background-color: #fff; 579 | border: 1px solid #ccc; 580 | border: 1px solid rgba(0, 0, 0, .15); 581 | border-radius: 4px; 582 | -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); 583 | box-shadow: 0 6px 12px rgba(0, 0, 0, .175); 584 | background-clip: padding-box; 585 | } 586 | 587 | .dropdown-menu { 588 | background: #f5f5f5; 589 | border-radius: 0; 590 | border: 0; 591 | margin-top: -5px; 592 | padding: 25px 0 15px; 593 | text-align: left; 594 | } 595 | 596 | .pull-right>.dropdown-menu { 597 | right: 0; 598 | left: auto; 599 | } 600 | 601 | .desktop .dropdown-menu .column-menu { 602 | float: left; 603 | } 604 | 605 | .dropdown-menu .column-menu ul { 606 | list-style: none; 607 | } 608 | 609 | .dropdown-menu li { 610 | margin-bottom: 8px; 611 | } 612 | 613 | .dropdown-menu li>a { 614 | border-bottom: 0; 615 | color: #7C7C7C; 616 | display: block; 617 | line-height: 20px; 618 | padding: 5px 20px; 619 | text-decoration: none; 620 | font-family: Georgia, "Times New Roman", Times, serif; 621 | -webkit-font-smoothing: antialiased; 622 | } 623 | 624 | .dropdown-menu li>a:hover { 625 | background: #e9e9e9; 626 | color: inherit; 627 | } 628 | 629 | .nav .menu.open .chapters { 630 | background: #f5f5f5; 631 | color: #333; 632 | } 633 | 634 | .open>.dropdown-menu { 635 | display: block; 636 | } 637 | 638 | .mobile { 639 | display: none; 640 | } 641 | 642 | @media (max-width: 770px) and (min-width: 320px) { 643 | .nav .container { 644 | width: 95%; 645 | } 646 | } 647 | 648 | @media (max-width: 770px) { 649 | .nav .menu { 650 | margin-top: 0; 651 | } 652 | .mobile { 653 | display: block; 654 | } 655 | .desktop { 656 | display: none; 657 | } 658 | .dropdown-desktop { 659 | visibility: hidden; 660 | } 661 | .chapters { 662 | padding: 14px 10px 13px; 663 | } 664 | .mobile .dropdown-mobile { 665 | visibility: visible; 666 | position: absolute; 667 | top: 0; 668 | right: 0; 669 | } 670 | .mobile .icon-book { 671 | margin-right: 0; 672 | font-size: 2em; 673 | } 674 | .mobile .dropdown-menu { 675 | left: 0; 676 | box-shadow: 0 4px 4px rgba(0, 0, 0, .25); 677 | top: 65px; 678 | } 679 | .mobile .dropdown-menu .column-menu ul { 680 | list-style: none; 681 | padding-left: 0; 682 | margin-bottom: 0; 683 | } 684 | .mobile .dropdown-menu li>a { 685 | white-space: inherit; 686 | font-size: 15px; 687 | line-height: 22px; 688 | padding: 8px 25px; 689 | text-align: left; 690 | } 691 | } 692 | 693 | 694 | /* END Nav Bar */ 695 | 696 | 697 | /* Header */ 698 | 699 | .header { 700 | background: white; 701 | /*padding: 100px 0; 702 | padding-bottom: 30px;*/ 703 | margin-bottom: 1em; 704 | } 705 | 706 | .title-container { 707 | width: 100%; 708 | display: table; 709 | position: relative; 710 | } 711 | 712 | .intro-title { 713 | color: black; 714 | position: relative; 715 | z-index: 2; 716 | padding: 2em; 717 | } 718 | 719 | .chapter-title { 720 | color: black; 721 | position: relative; 722 | z-index: 2; 723 | padding: 2em; 724 | border-bottom: 1px solid rgba(0, 0, 0, 0.5); 725 | } 726 | 727 | .chapter-title h1 { 728 | font-size: 2.0em; 729 | border-bottom: 1px solid rgba(0, 0, 0, 0.5); 730 | padding-bottom: 20px; 731 | } 732 | 733 | .chapter-title h3 { 734 | font-size: 1.6em; 735 | } 736 | 737 | 738 | /* END Header */ 739 | 740 | 741 | /* Intro Page */ 742 | 743 | .book-cover { 744 | text-align: center; 745 | } 746 | 747 | .border { 748 | width: 100%; 749 | height: 2px; 750 | background: black; 751 | display: inline-block; 752 | content: ""; 753 | color: #fff; 754 | font-size: 26px; 755 | line-height: 50px; 756 | margin-top: 50px; 757 | } 758 | 759 | .intro-text { 760 | line-height: 1.8em; 761 | text-align: center; 762 | } 763 | 764 | .intro-text p { 765 | text-align: justify; 766 | } 767 | 768 | .button-large { 769 | font-size: 1.375rem; 770 | display: inline-block; 771 | text-align: center; 772 | line-height: 1; 773 | cursor: pointer; 774 | transition: all 0.25s ease-out; 775 | vertical-align: middle; 776 | border: 1px solid transparent; 777 | margin: 0 0 1rem 0; 778 | color: #fff; 779 | background-color: #664534; 780 | font-family: "Lato", "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; 781 | padding: 1.2em 1.3em; 782 | text-transform: uppercase; 783 | font-weight: 900; 784 | border-radius: 0.3125rem; 785 | text-decoration: none; 786 | } 787 | 788 | .changelog-date { 789 | text-align: left; 790 | border-bottom: 1px solid #e2e1e4; 791 | padding-bottom: 5px; 792 | } 793 | 794 | 795 | /* END Intro Page */ 796 | 797 | body { 798 | font-family: "Lato", "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; 799 | color: #0a0a0a; 800 | } 801 | 802 | h1 { 803 | text-align: center; 804 | text-indent: 0; 805 | margin-top: 0; 806 | } 807 | 808 | h2 { 809 | font-size: 2.2em; 810 | } 811 | 812 | h3 { 813 | font-size: 1.5em; 814 | } 815 | 816 | .container { 817 | max-width: 1000px; 818 | margin: 0 auto; 819 | width: 90%; 820 | } 821 | 822 | .container p, ul { 823 | line-height: 1.4em; 824 | } 825 | 826 | .column { 827 | float: none; 828 | margin-left: auto; 829 | margin-right: auto; 830 | padding-left: 0.9375rem; 831 | padding-right: 0.9375rem; 832 | } 833 | 834 | .small { 835 | font-size: 80%; 836 | } 837 | 838 | code { 839 | background-color: #eee; 840 | padding: 1px 5px; 841 | font-size: 0.8em; 842 | } 843 | 844 | pre > code { 845 | padding: 0; /* This removes the padding specifically from block code elements */ 846 | } 847 | 848 | .answers { 849 | text-align: center; 850 | margin: 1.5em; 851 | } 852 | 853 | .book-info { 854 | border-bottom: 1px solid rgba(0, 0, 0, 0.5); 855 | border-top: 1px solid rgba(0, 0, 0, 0.5); 856 | padding: 1.5em; 857 | margin: 2em 1em; 858 | } 859 | 860 | .linkbox { 861 | margin: auto; 862 | font-size: 90%; 863 | margin-bottom: 2em; 864 | } 865 | 866 | .linkbox .previous { 867 | float: left; 868 | width: 40%; 869 | } 870 | 871 | .linkbox .next { 872 | float: right; 873 | width: 40%; 874 | text-align: right; 875 | } 876 | 877 | footer { 878 | padding-top: 1.5rem; 879 | padding-bottom: 1.5rem; 880 | text-align: center; 881 | } 882 | 883 | /* Apply a border to the entire table */ 884 | table { 885 | border-collapse: collapse; 886 | width: 100%; 887 | } 888 | 889 | /* Apply a border to each cell and center text in the second column */ 890 | td, th { 891 | border: 1px solid #000; 892 | padding: 10px; 893 | text-align: left; 894 | } 895 | 896 | /* Center text in the second column */ 897 | td:nth-child(2), th { 898 | text-align: center; 899 | } 900 | 901 | /* Add more space between rows by increasing line height */ 902 | tr { 903 | line-height: 1.5; 904 | } 905 | 906 | .indented { 907 | display: block; 908 | margin-left: 15px; 909 | } 910 | 911 | 912 | /* END Site's CSS */ -------------------------------------------------------------------------------- /intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: chapter 3 | is_intro: true 4 | 5 | title: "Introduction" 6 | subtitle: "" 7 | 8 | previous_link: "" 9 | previous_title: "" 10 | next_link: "/ch01.html" 11 | next_title: "Utilizing Java Object-Oriented Approach - Part 1" 12 | --- 13 | 14 | Java, released by Sun Microsystems in 1995, has become one of the most popular programming languages. How does a programming language stay relevant in the fast-paced world of technology for almost 30 years? 15 | 16 | Several factors contribute to Java's longevity, including its cross-platform compatibility, large and active developer community, and strong emphasis on backward compatibility. 17 | 18 | One factor that stands out is Java's continuous updates and improvements to keep up with the latest technology trends. Oracle, the company that now owns Java, releases a new version of the language every six months, with each release bringing new features, performance improvements, and security enhancements. This ensures Java remains competitive with other programming languages and frameworks, maintaining its popularity for modern application development. 19 | 20 | In this evolving programming landscape, it's essential for you to stay current with the latest technology. Earning a Java 21 certification not only validates your expertise in Java but also signals to employers that you are committed to ongoing professional development and staying ahead of the curve. 21 | 22 | However, a Java certification is not just about passing an exam. It's about building a strong foundation in Java. By studying for and passing the certification exam, you will gain a deeper understanding of the language and its core principles. 23 | 24 | This is my intention with this book. Here you will find clear and concise explanations of the fundamental concepts that you need to grasp in order to pass the Java SE 21 Developer Exam (1Z0-830). 25 | 26 | Here are some details about the exam: 27 | - It consists of 50 multiple-choice questions. 28 | - The time allotted for the exam is 120 minutes. 29 | - The passing score is 68%. 30 | - It is available online through the [Oracle University platform](https://education.oracle.com/buy-exam). 31 | 32 | You can find more information here: [https://education.oracle.com/product/pexam_1Z0-830](https://education.oracle.com/product/pexam_1Z0-830). 33 | 34 | ## Who Should Read This Book 35 | 36 | This book is designed for programmers who are already familiar with Java programming, its core concepts, and perhaps even have some practical experience. It is ideal for: 37 | 38 | - **Java developers** looking to upgrade their skills and knowledge to the Java 21 version. 39 | - **Intermediate Java programmers** who are comfortable with earlier versions of Java and want to deepen their understanding of the features and improvements introduced in Java 21. 40 | - **Certification aspirants** aiming to pass the Java 21 certification exam and requiring a comprehensive resource that covers all necessary topics and provides insights into the exam's structure and expectations. 41 | 42 | However, this book may not be the best starting point for complete beginners to programming or those with no prior experience in Java. While I will explain everything required to understand the objectives covered by the exam, the book assumes a basic understanding of Java concepts and programming principles. If you're new to Java, I recommend starting with introductory materials before this certification guide. 43 | 44 | ## How This Book Is Organized 45 | 46 | The book is divided into 16 chapters and one appendix as follows: 47 | 48 | - **Chapter 1. Utilizing Java Object-Oriented Approach - Part 1**. This chapter introduces fundamental concepts of object-oriented programming in Java, including classes, objects, and their lifecycle. It covers key language features such as keywords, comments, packages, access modifiers, fields, methods, constructors, initializers, and nested classes. 49 | 50 | - **Chapter 2. Utilizing Java Object-Oriented Approach - Part 2**. This chapter goes deeper into Java's object-oriented features, exploring variable scopes, inheritance, polymorphism, and advanced concepts like abstract classes, interfaces, and sealed classes. It covers topics such as method overriding, the `this` and `super` keywords, type casting, and the `instanceof` operator. 51 | 52 | - **Chapter 3. Working with Records and Enums**. This chapter introduces two specialized Java types: records, which provide a concise way to create immutable data carriers with built-in methods, and enums, which define sets of predefined constants. It explores the features, limitations, and best practices for both, including custom constructors, methods, and fields. 53 | 54 | - **Chapter 4. Working with Data**. This chapter provides an overview of Java's data handling capabilities, covering primitive and reference types, wrapper classes, operators, and string manipulation. It explores advanced topics such as autoboxing, operator precedence, bitwise operations, the immutability of strings, the efficiency of `StringBuilder`, text blocks, and mathematical operations using the `Math` class. 55 | 56 | - **Chapter 5. Controlling Program Flow**. This chapter explores Java's control flow structures, including conditional statements (`if`, `else if`, `else`), `switch` statements and expressions, and various loop constructs (`while`, `do-while`, `for`, enhanced `for`). It covers advanced topics such as pattern matching in `if` statements, labeled loops, and the use of `break` and `continue` statements to manage program execution flow efficiently. 57 | 58 | - **Chapter 6. Arrays, Generics, and Collections**. This chapter covers three fundamental concepts in Java: arrays for fixed-size data storage, generics for type-safe programming with different data types, and the Collections Framework for flexible data management. It explores array manipulation, generic classes and methods, wildcard types, and key collection interfaces and utilities, providing a comprehensive understanding of Java's data structure capabilities. 59 | 60 | - **Chapter 7. Error Handling and Exceptions**. This chapter explores Java's exception handling mechanism, covering the hierarchy of exception classes, the difference between checked and unchecked exceptions, and techniques for throwing and catching exceptions. 61 | 62 | - **Chapter 8. Functional Interfaces and Lambda Expressions**. This chapter introduces functional programming concepts, focusing on functional interfaces, lambda expressions, and method references. It covers the definition and use of functional interfaces, the syntax and applications of lambda expressions, built-in functional interfaces from the `java.util.function` package, and the various types of method references. 63 | 64 | - **Chapter 9. Streams**. This chapter explores the Stream API. It covers the creation and manipulation of streams, including intermediate and terminal operations, primitive streams, short-circuiting, and advanced concepts like reduction and collection, while also introducing the `Optional` class for safer `null` handling. 65 | 66 | - **Chapter 10. Concurrency and Multithreading**. This chapter talks about Java's concurrency and multithreading capabilities, covering thread creation, lifecycle, and synchronization mechanisms. It explores advanced topics such as the Concurrency API, thread pools, concurrent collections, parallel streams, and strategies for avoiding common pitfalls like deadlocks and race conditions. 67 | 68 | - **Chapter 11. The Date/Time API**. This chapter explores the Date/Time API, focusing on key classes such as `LocalDate`, `LocalTime`, `LocalDateTime`, `Instant`, `Period`, and `Duration`. It covers date and time manipulation, formatting, parsing, and working with time zones, daylight savings, and offsets. 69 | 70 | - **Chapter 12. File I/O**. This chapter is about Java's file input/output capabilities, focusing on the NIO.2 API and stream-based operations for both byte and character data. It covers essential file operations, including reading, writing, copying, moving, and deleting files, as well as working with file attributes, directory traversal, and object serialization. 71 | 72 | - **Chapter 13. The Java Platform Module System**. This chapter explores the Java Platform Module System (JPMS), covering module creation, dependencies, and encapsulation. It covers module types, service providers, migration strategies, and tools like `jdeps`, `jmod`, and `jlink`. 73 | 74 | - **Chapter 14. Localization**. This chapter reviews Java's localization capabilities, covering `Locale` handling, resource bundles, and internationalization of messages, numbers, dates, and times. It covers key classes like `ResourceBundle`, `MessageFormat`, `NumberFormat`, `DateFormat`, and `DateTimeFormatter`. 75 | 76 | The following table shows the chapter where each exam objective and sub-objective is covered: 77 | 78 | | Exam Objectives | Chapter | 79 | |----------------------------------------------------------------------------------------------------------|---------| 80 | | **Handling Date, Time, Text, Numeric and Boolean Values** | 4 | 81 | |Use primitives and wrapper classes. Evaluate arithmetic and boolean expressions, using the Math API and by applying precedence rules, type conversions, and casting. | 4 | 82 | |Manipulate text, including text blocks, using String and StringBuilder classes. | 4 | 83 | |Manipulate date, time, duration, period, instant and time-zone objects including daylight saving time using Date-Time API. | 11 | 84 | | **Controlling Program Flow** | 5 | 85 | |Create program flow control constructs including if/else, switch statements and expressions, loops, and break and continue statements. | 5 | 86 | | **Using Object-Oriented Concepts in Java** | 1, 2, 3, 5 | 87 | |Declare and instantiate Java objects including nested class objects, and explain the object life-cycle including creation, reassigning references, and garbage collection. | 1 | 88 | |Create classes and records, and define and use instance and static fields and methods, constructors, and instance and static initializers. | 1, 3 | 89 | |Implement overloading, including var-arg methods. | 1 | 90 | |Understand variable scopes, apply encapsulation, and create immutable objects. Use local variable type inference. | 2 | 91 | |Implement inheritance, including abstract and sealed types as well as record classes. Override methods, including that of the Object class. Implement polymorphism and differentiate between object type and reference type. Perform reference type casting, identify object types using the instanceof operator, and pattern matching with the instanceof operator and the switch construct. | 2, 5 | 92 | |Create and use interfaces, identify functional interfaces, and utilize private, static, and default interface methods. | 2 | 93 | |Create and use enum types with fields, methods, and constructors. | 3 | 94 | | **Handling Exceptions** | 7 | 95 | |Handle exceptions using try/catch/finally, try-with-resources, and multi-catch blocks, including custom exceptions. | 7 | 96 | | **Working with Arrays and Collections** | 6 | 97 | |Create arrays, List, Set, Map and Deque collections, and add, remove, update, retrieve and sort their elements. | 6 | 98 | | **Working with Streams and Lambda expressions** | 8, 9 | 99 | |Use Java object and primitive Streams, including lambda expressions implementing functional interfaces, to create, filter, transform, process, and sort data. | 8, 9 | 100 | |Perform decomposition, concatenation, and reduction, and grouping and partitioning on sequential and parallel streams. | 9 | 101 | | **Packaging and Deploying Java Code** | 13 | 102 | |Define modules and expose module content, including that by reflection, and declare module dependencies, define services, providers, and consumers. | 13 | 103 | |Compile Java code, create modular and non-modular jars, runtime images, and implement migration to modules using unnamed and automatic modules. | 13 | 104 | | **Managing Concurrent Code Execution** | 10 | 105 | |Create both platform and virtual threads. Use both Runnable and Callable objects, manage the thread lifecycle, and use different Executor services and concurrent API to run tasks. | 10 | 106 | |Develop thread-safe code, using locking mechanisms and concurrent API. | 10 | 107 | |Process Java collections concurrently and utilize parallel streams. | 10 | 108 | | **Using Java I/O API** | 12 | 109 | |Read and write console and file data using I/O streams. | 12 | 110 | |Serialize and de-serialize Java objects. | 12 | 111 | |Construct, traverse, create, read, and write Path objects and their properties using the java.nio.file API. | 12 | 112 | | **Implementing Localization** | 14 | 113 | |Implement localization using locales and resource bundles. Parse and format messages, dates, times, and numbers, including currency and percentage values. | 14 | 114 | 115 | At the end of each chapter, you will find a set of practice questions to measure your knowledge of the topics covered in the chapter. 116 | 117 | Here are a few strategies to maximize the benefits of these practice questions: 118 | 119 | 1. **Attempt all questions**: Even if you feel confident about a topic, attempting every question ensures comprehensive coverage of the material. 120 | 2. **Review explanations**: For each question, detailed explanations are provided, highlighting why each answer is correct or incorrect. Carefully review these explanations to understand the rationale behind each question, which is important for mastering the material. 121 | 3. **Revisit difficult questions**: If you find certain questions challenging, make a note of them and revisit these topics in the chapters. This iterative process of testing and reviewing will solidify your understanding. 122 | 4. **Track your progress**: Use the practice questions to gauge your understanding and track your progress over time. This can help identify areas where further review is needed. 123 | 124 | As you work through the practice and even the real exam questions, consider these tips to improve your success rate: 125 | 126 | - **Read Carefully:** Take the time read each question and all possible answers, paying attention to keywords and qualifiers like "all," "none," "only," "best," and "most" to understand what the question is really asking. 127 | - **Identify the Core Question:** Focus on on the question's true intent. Questions often aim to test specific facets of a concept, pinpointing this can guide your thought process. 128 | - **Rephrase the Question:** If the question is complex or confusing, try rephrasing it in your own words. This can help clarify what is being asked and make it easier to identify the correct answer. 129 | - **Eliminate Clearly Wrong Answers:** Start by eliminating any answer choices that are clearly incorrect. Even if you're unsure about the correct answer, narrowing down the options increases your chances of choosing the right one. 130 | - **Look for Distinct Patterns:** Sometimes, incorrect answer choices have patterns in common (such as syntactical errors or implausible values) that you can identify and eliminate. 131 | - **Use Partial Knowledge:** Even if you're not 100% sure about an answer, use your partial knowledge of the topic to eliminate choices that don't fit what you know. 132 | - **Manage Your Time:** If you find yourself stuck on a question, it's often better to skip it and move on. This prevents you from spending too much time on a single question and running out of time for others. 133 | - **Mark for Review:** If available, use the exam's feature to mark questions for later review. This allows you to revisit challenging questions if time permits. 134 | - **First Instincts:** If you must guess, go with your first instinct unless you find clear evidence to change your answer upon review. Often, your initial choice is influenced by your subconscious knowledge of the subject. 135 | - **Context Clues:** Use any given context or code snippets to guide your answer. The context can often eliminate answers that are correct in general but not suitable for the specific scenario presented. 136 | 137 | Integrating these tactics with a comprehensive study plan is essential for a thorough preparation. Now, let's explore some tips for creating an effective study strategy that goes beyond merely answering practice questions. 138 | 139 | 140 | ## Tips for Studying 141 | 142 | ### 1. Understand the Exam Objectives 143 | First of all, visit the official [Oracle Certification website](https://education.oracle.com/product/pexam_1Z0-830) to get detailed information on the objectives, the structure, and the topics covered for the 1Z0-830 exam. 144 | 145 | However, understanding the exam objectives is not just about knowing what topics will be on the exam; it's about comprehensively integrating this knowledge into a study plan, ensuring you're well-prepared for the breadth and depth of questions you'll encounter. 146 | 147 | Study guides like this one offer a structured way of learning and often include practice questions, study tips, and detailed explanations of topics. However, there are more resources you can use to prepare for the exam: 148 | - **Oracle Documentation**: [Oracle's official documentation for Java](https://docs.oracle.com/en/java/javase/21/) is another important resource. It provides comprehensive details on the Java language and APIs. Familiarity with Oracle's documentation can also help you in your professional work, beyond passing the exam. 149 | - **Official or Recognized Training Courses**: Oracle offers an official training course for the Java programmer certification. Courses taught by Oracle-certified instructors or recognized professionals can offer deep insights into Java programming and the certification objectives. They can also provide answers to complex questions and clarify difficult concepts. 150 | - **Forums and Discussion Groups**: Online forums and social media groups dedicated to Java certification are excellent places to ask questions, share study tips, and connect with others programmers interested on the Java certification exams. I can recommend [Coderanch](https://coderanch.com/f/24/java-programmer-OCPJP). 151 | 152 | ### 2. Create a Study Plan 153 | 154 | You need to approach your exam preparation strategically. A good plan addresses not only what you need to learn but also how you learn best, ensuring that, when exam day arrives, you're confident in your knowledge and ready to succeed. Here's how to create an effective study plan: 155 | 156 | 1. **Define Your Study Timeline.** Evaluate how familiar you are with the exam topics. This assessment will help you estimate how much time you'll need to prepare for each section and set a target date for taking the exam. Based on your current knowledge and the exam date, allocate a specific number of weeks or months for preparation. Ensure you include extra time for revision and practice exams. 157 | 158 | 2. **Break Down Exam Objectives into Study Sessions.** Divide the exam objectives into manageable sections or topics, which could be based on the official breakdown provided by Oracle or chapters in a study guide. 159 | 160 | 3. **Schedule Regular Study Times.** Establish a daily or weekly routine that dedicates specific times to studying. Consistency is important for long-term retention and staying on track with your study plan. However, remember to incorporate short breaks into your study sessions to prevent burnout and enhance productivity. Techniques like the Pomodoro Technique can be beneficial. 161 | 162 | 4. **Set Milestones and Review Points.** Set specific goals for what you want to achieve each week or month, such as mastering a particular topic or completing a set number of practice questions. Also, schedule regular review sessions to go over previously studied material. This repetition is vital for memory retention. 163 | 164 | 5. **Adjust the Plan as Needed.** Regularly assess your progress against the study plan. Be prepared to adjust your schedule if you're moving faster or slower than anticipated. Life events may require modifications to your study plan. The key is to stay flexible and adapt while keeping your goal in sight. 165 | 166 | ### 3. Practice Coding by Hand 167 | 168 | While programmers heavily rely on Integrated Development Environments (IDEs) for coding, the ability to write code by hand (without the assistance of auto-completion or syntax highlighting) is important, especially in the context of certification exams. Coding by hand compels you to recall syntax and programming constructs from memory, reinforcing your knowledge and understanding of Java fundamentals. 169 | 170 | Begin practicing with simple programs that cover basic concepts, such as loops, conditionals, data types, and array manipulations. Gradually increase the complexity of these programs as you become more comfortable. This practice will not only improve your coding skills but also will deepen your understanding of these concepts. 171 | 172 | Before starting to code, consider outlining your program in pseudocode. This step helps structure your thoughts and approach to problem-solving, allowing you to focus on the logic of your solution without getting bogged down by syntax. Pseudocode is a valuable skill in both exam scenarios and real-world problem-solving. 173 | 174 | After writing your code, review it line by line to check for syntax errors, logical mistakes, and other potential issues. Take the time to understand any errors you encounter and why they occurred. This reflective practice is important for learning and improvement. If possible, have someone else review your handwritten code. A fresh perspective can offer new insights and identify errors that you may have overlooked. 175 | 176 | ### 4. Include Practice Exams in Your Plan 177 | In addition to the sample questions provided by this book, practice exams help you become familiar with the exam's format, including the wording of questions and the time constraints. This approach enables you to identify areas of weakness, allowing for more targeted and efficient study on topics needing improvement. 178 | 179 | Don't postpone taking practice exams until the last minute. Instead, integrate them early and consistently into your study plan to assess your understanding and monitor your progress. Here are some tips: 180 | 181 | - **Timed Sessions:** Simulate exam conditions by taking practice exams within set time limits to improve your time management skills. This practice is important for completing all questions within the given time frame during the actual exam. 182 | - **Study in Blocks:** If tackling a full-length exam is too daunting, consider dividing practice exams into smaller segments focused on specific topics for more concentrated study sessions. 183 | - **Simulate the Exam Environment:** Create an exam-like environment by finding a quiet, distraction-free space where you can concentrate on the practice exam without interruptions. 184 | - **Review Incorrect Answers:** Make it a priority to review and understand the rationale behind each incorrect answer and the logic of the correct ones. This process is key to learning from your mistakes and avoiding them in the future. 185 | - **Take Notes on Mistakes:** Maintain a record of errors and challenging topics in a notebook or digital file. Refer to these notes when revising your study plan, emphasizing these weaker areas. 186 | - **Retake Exams:** Revisiting practice exams can be valuable, particularly after some time has elapsed since your initial attempt. However, avoid over-reliance on rote memorization of questions and answers, as it might lead to a misleading sense of readiness. 187 | - **Diverse Set of Questions:** Engage with a wide array of practice exams to encounter various questions and scenarios. This diversity helps prevent the pitfall of memorization and fosters a genuine comprehension of the underlying concepts. 188 | - **Refine Your Study Plan:** Leverage the insights gained from practice exams to fine-tune your study plan. Dedicate additional time to areas of lower performance and continue practice until you observe consistent score improvements. 189 | 190 | 191 | ### 5. Stay Healthy and Motivated 192 | Studying for the Java certification exam can be a time-consuming and stressful process. Remember, it's important to take breaks, get enough sleep, exercise regularly, and eat a healthy diet to stay focused and energized. 193 | 194 | What you eat significantly affects your brain function and energy levels. Consuming a balanced diet with plenty of fruits, vegetables, lean proteins, and whole grains can give you the steady energy necessary for extended study periods. Try to limit your intake of caffeine and sugar to avoid the inevitable energy crashes they can cause. 195 | 196 | Regular exercise enhances blood flow to the brain, helping in memory retention and stress alleviation. Even brief intervals of physical activity, such as walking or stretching, can offer substantial benefits. Strive for at least 30 minutes of moderate exercise on most days. 197 | 198 | To avoid burnout, incorporate regular breaks into your study plan. Use this time for enjoyable activities, whether it's reading, listening to music, or socializing with friends and family. 199 | 200 | Never underestimate the importance of quality sleep, particularly in the days leading up to the exam. Sleep plays a vital role in memory consolidation and overall cognitive functionality. Try to establish a consistent sleep schedule that allows for 7-9 hours of rest each night. 201 | 202 | Finally, keep a positive and confident outlook as you navigate your exam preparation. Trust in your capabilities and remind yourself of the reasons behind your pursuit of Java certification. Whether motivated by professional growth, personal achievement, or specific career aspirations, focusing on your initial motivations can help keep your spirits high and your motivation intact throughout challenging study periods. 203 | 204 | All right, let's get stated! --------------------------------------------------------------------------------