Java Programming Exercises Volume One Language Fundamentals and Core Concepts (Christian Ullenboom) (z-library.sk, 1lib.sk, z-lib.sk)
Author: Christian Ullenboom
Java
This book is the first of two volumes which provide you with everything you need to excel in your Java journey, including tricks that you should know in detail as a professional, as well as intensive training for clean code and thoughtful design that carries even complex software.
📄 File Format:
PDF
💾 File Size:
15.7 MB
8
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
Java Programming Exercises Take the first step in raising your coding skills to the next level, and test your Java knowledge on tricky programming tasks, with the help of the pirate Captain CiaoCiao. This is the first of two volumes which provide you with everything you need to excel in your Java journey, including tricks that you should know in detail as a professional, as well as intensive training for clean code and thoughtful design that carries even complex software. Features: • About 200 tasks with commented solutions on different levels • For all paradigms: object‑oriented, imperative, and functional • Clean code, reading foreign code, and object‑oriented modeling With numerous best practices and extensively commented solutions to the tasks, these books provide the perfect workout for professional software development with Java.
📄 Page
3
Java Programming Exercises Volume One: Language Fundamentals and Core Concepts Christian Ullenboom
📄 Page
4
Designed cover image: Mai Loan Nguyen Duy, Rheinwerk Verlag GmbH First edition published 2025 by CRC Press 2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431 and by CRC Press 4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC ©2023 Christian Ullenboom. First published in the German language under the title “Captain CiaoCiao erobert Java” (ISBN 978‑3‑8362‑8427‑1) by Rheinwerk Verlag GmbH, Bonn, Germany. Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978‑750‑8400. For works that are not available on CCC please contact mpkbookspermissions@tandf.co.uk Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. ISBN: 978‑1‑032‑59397‑5 (hbk) ISBN: 978‑1‑032‑57984‑9 (pbk) ISBN: 978‑1‑003‑45450‑2 (ebk) DOI: 10.1201/9781003454502 Typeset in Times by codeMantra Access the Support Material: https://routledge.com/9781032579849
📄 Page
5
v Contents About the Author xv Introduction 1 Previous Knowledge and Target Audience 1 Working with This Book 2 The Suggested Solutions 2 Use of This Book 3 Required Software 3 Used Java Version in the Book 4 JVM 4 Development Environment 4 Conventions 4 Helping Captain CiaoCiao and Bonny Brain 5 1 Introduction to the Java Ecosystem 6 Bytecode and JVM 6 Porting Java Programs ⭑ 6 Tools for Java Developers 7 Get to Know Error Messages of the IDE ⭑ 7 Suggested Solutions 8 Porting Java Programs ⭑ 8 Get to Know Error Messages of the IDE ⭑ 8 2 Imperative Programming 9 Screen Output 9 Learn about the SVG Specification 9 Write an SVG Circle on the Console ⭑ 10 Variables and Data Types 11 Access Variables and Output Their Assignments ⭑ 12 Quiz: Value Ranges ⭑ 12 Quiz: Does This Add Up? ⭑⭑⭑ 12 Generate Random Circles ⭑ 13 Quiz: Dazed and Confused ⭑ 14 Process User Input ⭑ 14 Expressions, Operands, and Operators 14 Quiz: Check In-Between ⭑ 14 Check If Loot Can Be Shared Fairly ⭑ 15 Do Two Numbers Share the Same Digit? ⭑⭑ 15 Convert Currency Amount to Coins ⭑⭑ 15 One Bottle of Rum, Ten Bottles of Rum ⭑ 16 Quiz: The Zero Effect ⭑ 17
📄 Page
6
vi Contents Control Flow 18 Payday ⭑ 18 Quiz: Wrong Branching ⭑ 18 Convert Liters ⭑⭑ 19 Create SVG Circles with Random Colors ⭑ 19 Quiz: To Which Block Does the Else Belong? ⭑⭑ 20 Quiz: Recognize Negative Days and Hours ⭑ 20 Evaluate Input Strings for Approval ⭑ 20 Rewrite Switch Statement to Switch Expression ⭑ 21 Loops 21 Create Rotated SVG Rectangles ⭑ 21 Create SVG-Pearl-Chain ⭑ 22 Sum Numbers from the Command Line ⭑ 23 Go through a Mathematical Phenomenon ⭑ 24 Quiz: How Many Stars? ⭑ 24 Calculate Products for Faculties ⭑ 25 Determine If a Number Is Formed by Factorial ⭑ 25 Find the Smallest and Largest Digit of a Number ⭑ 26 Quiz: Not Like This from 1 to 100 ⭑⭑ 27 A Flag in the Wind through Nested Loops ⭑ 28 Output Simple Chessboard ⭑ 28 It’s Christmastime: Displaying Trees with Ornaments ⭑ 29 Draw Fishy Stitching Motifs ⭑ 30 Trying Instead of Thinking ⭑⭑ 31 Get the Number of Digits of a Number ⭑⭑ 32 Methods 33 Drawing Hearts ⭑ 33 Implement Overloaded Line Methods ⭑ 34 Standing Straight ⭑ 34 Create a Multiplication Table ⭑ 35 Cistercian Numerals Script ⭑⭑⭑ 36 Quiz: What Does Ding-Dong Do? (Recursion) ⭑⭑ 37 Quiz: Repdigit (Recursion) ⭑⭑ 37 Calculate Collatz Sequence (Recursion) ⭑ 38 Ancient Egyptian Multiplication (Recursion) ⭑⭑ 38 Suggested Solutions 40 Write an SVG Circle on the Console ⭑ 40 Access Variables and Output Their Assignments 41 Quiz: Value Ranges 42 Quiz: Does This Add Up? 43 Generate Random Circles 43 Quiz: Dazed and Confused 44 Process User Input 44 Quiz: Check In-Between 44 Check If Loot Can Be Shared Fairly 45 Do Two Numbers Share the Same Digit? 45 Convert Currency Amount to Coins 46 One Bottle of Rum, Ten Bottles of Rum 47 Quiz: The Zero Effect 47 Payday 47 Quiz: Wrong Branching 48
📄 Page
7
Contents vii Convert Liters 48 Create SVG Circles with Random Colors 49 Quiz: To Which Block Does the Else Belong? 50 Quiz: Recognize Negative Days and Hours 50 Evaluate Input Strings for Approval 51 Rewrite Switch Statement to Switch Expression 52 Create Rotated SVG Rectangles 52 Create SVG-Pearl-Chain 53 Sum Numbers from the Command Line 53 Go through a Mathematical Phenomenon 54 Quiz: How Many Stars? 55 Calculate Products for Faculties 55 Determine If a Number Is Formed by Factorial 57 Find the Smallest and Largest Digit of a Number 58 Quiz: Not Like This from 1 to 100 58 A Flag in the Wind through Nested Loops 59 Output Simple Chessboard 60 It’s Christmastime: Displaying Trees with Ornaments 60 Draw Fishy Stitching Motifs 61 Trying Instead of Thinking 62 Get the Number of Digits of a Number 63 Drawing Hearts 65 Implement Overloaded Line Methods 65 Standing Straight 66 Create a Multiplication Table 68 Cistercian Numerals Script 69 Quiz: What Does Ding-Dong Do? (Recursion) 72 Quiz: Repdigit (Recursion) 72 Calculate Collatz Sequence (Recursion) 73 Ancient Egyptian Multiplication (Recursion) 75 3 Classes, Objects, and Packages 78 Creating Objects 78 Draw Polygons ⭑ 78 Working with References 80 Quiz: The Short Life of Points ⭑ 80 Build Triangles ⭑ 80 Quiz: == vs. equals(…) ⭑ 81 Quiz: Protect against NullPointerException ⭑ 81 Suggested Solutions 82 Draw Polygons 82 Quiz: The Short Life of Points 83 Build Triangles 83 Quiz: == vs. equals(…) 84 Quiz: Protect against NullPointerException 84 Note 85 4 Arrays 86 Everything Has a Type 86 Quiz: Array Types ⭑ 86 One-Dimensional Arrays 87
📄 Page
8
viii Contents Loop Arrays and Output Wind Speed, Wind Direction ⭑ 87 Detect Continuous Revenue Growth ⭑ 88 Array of Points ⭑ 88 Search Consecutive Strings and Determine If Salty Snook Is Coming ⭑ 89 Reverse an Array ⭑ 89 Find the Nearest Cinema ⭑⭑ 90 Raid the Candy Store and Share Fairly ⭑⭑ 90 Enhanced for Loop 91 Numbers Well Shuffled ⭑⭑ 92 Draw Mountains ⭑⭑ 93 Two- and Multidimensional Arrays 94 Check Mini-Sudoku for Valid Solution ⭑⭑ 94 Enlarge Image ⭑⭑ 95 Variable Argument Lists 96 Create SVG Polygons with a Variable Number of Coordinates ⭑ 96 Check for Approval ⭑ 97 Help, Tetraphobia! Put All Fours Last ⭑⭑ 97 The Utility Class Arrays 98 Quiz: Copy Arrays ⭑ 98 Quiz: Compare Arrays ⭑ 98 Suggested Solutions 99 Quiz: Array Types 99 Loop Arrays and Output Wind Speed, Wind Direction 99 Reverse an Array 100 Array of Points 101 Search Consecutive Strings and Determine if Salty Snook is Coming 102 Reverse an Array 103 Find the Nearest Cinema 104 Raid the Candy Store and Share Fairly 105 Draw Mountains 106 Check Mini-Sudoku for Valid Solution 107 Enlarge Image 109 Create SVG Polygons with Variable Number of Coordinates 109 Check for Approval 110 Help, Tetraphobia! Put All Fours Last 111 Quiz: Copy Arrays 112 Quiz: Compare Arrays 112 5 Character and String Processing 114 The String Class and Its Members 114 Quiz: Is String a Built-In Keyword? ⭑ 114 Building HTML Elements with Simple Concatenation ⭑ 114 Check Safe Transmission by Doubling Characters ⭑ 115 Swap Y and Z ⭑ 116 Give Defiant Answers ⭑ 117 Quiz: String Comparisons with == and Equals(…) ⭑ 117 Quiz: Is Equals(…) Symmetric? ⭑ 118 Test Strings for Palindrome Property ⭑ 118 Check if Captain CiaoCiao is in the Middle ⭑ 119 Find the Shortest Name in the Array ⭑ 120 Count String Occurrences ⭑ 120
📄 Page
9
Contents ix Determine the Larger Crew Size ⭑ 121 Build Diamonds ⭑⭑ 122 Check for a Good Password ⭑ 123 Bake Peanut Butter Cookies ⭑⭑ 123 Calculate Sum of Digits ⭑ 124 Decolumnize Texts ⭑⭑ 125 Draw a Meadow with Favorite Flowers ⭑⭑ 126 Detect Repetitions ⭑⭑⭑ 128 Constrain Line Boundaries and Wrap Lines ⭑⭑ 128 Quiz: How Many String Objects? ⭑ 129 Test If the Fruit Is Wrapped in Chocolate ⭑⭑ 129 From Top to Bottom, from Left to Right ⭑⭑⭑ 130 Dynamic Strings with StringBuilder 131 Fill Strings ⭑ 131 Practicing the Alphabet with a Parrot ⭑ 132 Quiz: Lightly Attached ⭑ 133 Convert Number to Textual Unary Encoding ⭑ 133 Lose Weight by Moving Digits ⭑ 134 Remove Vowels ⭑ 135 Don’t Shoot the Messenger ⭑ 136 Compress Repeated Spaces ⭑⭑ 137 Insert and Remove Crackles and Pops ⭑ 137 Split CamelCase Strings ⭑ 138 Underline Words ⭑⭑ 138 Implement Caesar Encryption ⭑⭑⭑ 138 Suggested Solutions 140 Quiz: Is String a Built-In Keyword? 140 Building HTML Elements with Simple Concatenation 140 Check Safe Transmission by Doubling Characters 140 Swap Y and Z 141 Give Defiant Answers 143 Quiz: String Comparisons with == and Equals(…) 143 Quiz: Is Equals(…) Symmetric? 143 Test Strings for Palindrome Property 144 Check if Captain CiaoCiao is in the Middle 146 Find the Shortest Name in the Array 146 Count String Occurrences 147 Determine the Larger Crew Size 148 Build Diamonds 149 Check for a Good Password 151 Bake Peanut Butter Cookies 152 Calculate Sum of Digits 153 Decolumnize Texts 154 Draw a Meadow with Favorite Flowers 156 Detect Repetitions 158 Constrain Line Boundaries and Wrap Lines 159 Quiz: How Many String Objects? 160 Test if the Fruit is Wrapped in Chocolate 160 From Top to Bottom, from Left to Right 161 Fill Strings 162 Practicing the Alphabet with a Parrot 163
📄 Page
10
x Contents Quiz: Lightly Attached 164 Convert Number to Textual Unary Encoding 165 Lose Weight by Moving Digits 166 Remove Vowels 167 Don’t Shoot the Messenger 169 Compress Repeated Spaces 170 Insert and Remove Crackles and Pops 171 Split CamelCase Strings 172 Underline Words 173 Implement Caesar Encryption 174 6 Writing Your Own Classes 176 Class Declaration and Object Properties 177 Declare Radio with Instance Variables and a Main Program ⭑ 177 Implementing Methods of a Radio ⭑ 177 Private Parts: Make Instance Variables Private ⭑ 178 Create Setters and Getters ⭑ 178 Static Variables Methods 178 Convert Station Names to Frequencies ⭑ 178 Write Log Output with a Tracer Class ⭑ 179 Quiz: Nothing Stolen ⭑ 180 Simple Enumerations 181 Give Radio an AM–FM Modulation ⭑ 181 Set Valid Start and End Frequency for Modulation ⭑ 181 Constructors 181 Writing Radio Constructors ⭑ 182 Implement Copy Constructor ⭑ 182 Realize Factory Methods ⭑ 182 Associations 183 Connect Monitor Tube with TV ⭑ 183 Quiz: Association, Composition, and Aggregation ⭑ 184 Add Radios with a 1:n Association to the Ship ⭑⭑ 184 Inheritance 185 Introduce Abstraction into Electrical Devices via Inheritance ⭑ 185 Quiz: Three, Two, and One ⭑ 185 Quiz: Private and Protected Constructor ⭑ 186 Determine the Number of Switched on Electrical Devices ⭑ 186 Ship Should Hold Any Electronic Device ⭑ 186 Take Working Radios on the Ship ⭑ 187 Solve Equivalence Test with Pattern Variable ⭑ 187 Fire Alarm Does Not Go Off: Overriding Methods ⭑ 188 Calling the Methods of the Superclass ⭑⭑ 188 Polymorphism and Dynamic Binding 189 Holiday! Switch Off All Devices ⭑ 189 The Big Move ⭑ 190 Quiz: Bumbo Is a Great Drink ⭑⭑ 191 Quiz: Vodka with Taste ⭑ 192 Quiz: Rum-Paradise ⭑⭑ 192 Abstract Classes and Abstract Methods 192 Quiz: Consumer Devices as an Abstract Superclass? ⭑ 193 TimerTask as an Example for an Abstract Class ⭑⭑ 193
📄 Page
11
Contents xi Suggested Solutions 194 Declare Radio with Instance Variables and a Main Program 194 Implementing Methods of a Radio 195 Private Parts: Make Instance Variables Private 196 Create Setters and Getters 197 Convert Station Names to Frequencies 198 Write Log Output with a Tracer Class 198 Quiz: Nothing Stolen 199 Give Radio an AM–FM Modulation 199 Set Valid Start and End Frequency for Modulation 200 Writing Radio Constructors 201 Implement Copy Constructor 202 Realize Factory Methods 202 Connect Monitor Tube with TV 204 Quiz: Association, Composition, and Aggregation 205 Add Radios with a 1:n Association to the Ship 205 Introduce Abstraction into Electrical Devices via Inheritance 206 Quiz: Three, Two, and One 207 Quiz: Private and Protected Constructor 208 Determine Number of Switched on Electrical Devices 208 Ship Should Hold Any Electronic Device 209 Take Working Radios on the Ship 209 Solve Equivalence Test with Pattern Variable 210 Fire Alarm Does Not Go Off: Overriding Methods 210 Calling the Methods of the Superclass 211 Holiday! Switch Off All Devices 212 The Big Move 212 Quiz: Bumbo Is a Great Drink 212 Quiz: Vodka with Taste 213 Quiz: Rum-Paradise 213 Quiz: Consumer Devices as an Abstract Superclass? 214 TimerTask as an Example for an Abstract Class 214 Note 215 7 Records, Interfaces, Enumerations, and Sealed Classes 216 Records 216 Quiz: Which Statements Are True for Records? ⭑ 216 Develop Record for Complex Numbers ⭑ 216 Quiz: Records with Static Variables ⭑ 217 Record Patterns ⭑ 217 Interfaces 218 Compare Consumption of Electrical Devices ⭑ 218 Find Electronic Devices with the Highest Power Consumption ⭑ 219 Use Comparator Interface for Sorting ⭑ 220 Static and Default Methods in Interfaces ⭑⭑⭑ 220 Delete Selected Elements with Predicate ⭑⭑ 220 Enumeration Types (enum) 221 Enumeration for Candy ⭑ 221 Deliver Random Candies ⭑ 222 Tagging Candy with Addictive Value ⭑⭑ 223 Interface Implementations via an enum ⭑⭑ 224
📄 Page
12
xii Contents Quiz: Aviso and Brig ⭑ 225 Suggested Solutions 225 Quiz: Which Statements Are True for Records? 225 Quiz: Records with Static Variables 226 Quiz: Records with Static Variables 227 Compare Consumption of Electrical Devices 228 Find Electronic Devices with the Highest Power Consumption 229 Use Comparator Interface for Sorting 230 Static and Default Methods in Interfaces 230 Delete Selected Elements with Predicate 231 Enumeration for Candy 232 Deliver Random Candies 233 Tagging Candy with Addictive Value 233 Interface Implementations via an enum 236 Quiz: Aviso and Brig 237 8 Nested Types 238 Declare Nested Types 238 Set AM–FM Modulation to Radio Type ⭑ 238 Write Three Kinds of Watt-Comparator Implementations ⭑ 239 Nested Types Quiz 239 Quiz: Pirate Could Have Waved ⭑ 239 Quiz: Name in a Bottle ⭑⭑ 240 Quiz: Get Me Another Bottle of Rum ⭑ 240 Suggested Solutions 241 Set AM–FM Modulation to Radio Type 241 Write Three Kinds of Watt-Comparator Implementations 242 Quiz: Pirate Could Have Waved 243 Quiz: Name in a Bottle 243 Quiz: Get Me another Bottle of Rum 243 9 Exception Handling 244 Catching Exceptions 244 Get the Longest Line of a File ⭑ 244 Identify Exceptions, Laughing All the Time ⭑ 245 Convert String Array to Int Array and Be Lenient on Nonnumbers ⭑ 245 Quiz: And Finally ⭑ 246 Quiz: A Lonely Try ⭑ 246 Quiz: Well Caught ⭑ 246 Quiz: Too Much of a Good Thing ⭑ 247 Quiz: Try-Catch in Inheritance ⭑⭑ 247 Throwing Custom Exceptions 247 Quiz: Throw and Throws ⭑ 247 Quiz: The Division Fails ⭑ 248 Writing Your Own Exception Classes 248 Show Impossible Watt with Own Exception ⭑ 248 Quiz: Potatoes or Other Vegetables ⭑ 248 Try-with-Resources 249 Write Current Date to File ⭑ 249 Read Notes and Write Them to a New ABC File ⭑⭑ 249
📄 Page
13
Contents xiii Quiz: Excluded ⭑ 250 Suggested Solutions 251 Get the Longest Line of a File 251 Identify Exceptions, Laughing All the Time 252 Convert String Array to Int Array and Be Lenient on Nonnumbers 254 Quiz: And Finally 255 Quiz: A Lonely Try 255 Quiz: Well Caught 256 Quiz: Too Much of a Good Thing 256 Quiz: Try-Catch in Inheritance 257 Quiz: Throw and Throws 257 Quiz: The Division Fails 257 Show Impossible Watt with Own Exception 258 Quiz: Potatoes or Other Vegetables 260 Write Current Date to File 260 Read Notes and Write Them to a New ABC File 261 Quiz: Excluded 262 10 Lambda Expressions and Functional Programming 263 Lambda Expressions 264 Quiz: Recognize Valid Functional Interfaces ⭑ 264 Quiz: From Interface Implementation to Lambda Expression ⭑ 264 Write Lambda Expressions for Functional Interfaces ⭑ 265 Quiz: Write Lambda Expressions Like This? ⭑ 266 Developing Lambda Expressions ⭑ 266 Quiz: Contents of the Package java.util.function ⭑ 266 Quiz: Know Functional Interfaces for Mappings ⭑ 266 Method and Constructor References 268 Rewriting Lambda Expressions ⭑⭑ 268 Selected Functional Interfaces 268 Delete Entries, Remove Comments, Convert to CSV ⭑ 268 Suggested Solutions 269 Quiz: Recognize Valid Functional Interfaces 269 Quiz: From Interface Implementation to Lambda Expression 270 Write Lambda Expressions for Functional Interfaces 271 Quiz: Write Lambda Expressions Like This? 271 Developing Lambda Expressions 271 Quiz: Contents of the Package java.util.function 271 Quiz: Know Functional Interfaces for Mappings 272 Rewriting Lambda Expressions 273 Delete Entries, Remove Comments, and Convert to CSV 273 Note 274 11 Special Types from the Java Class Library 275 Absolute Superclass java.lang.Object 275 Generate equals(Object) and hashCode() ⭑ 276 Existing equals(Object) Implementations ⭑⭑ 276 Interfaces Comparator and Comparable 277 Quiz: Natural Order Or Not? ⭑ 277 Handle Superheroes 277
📄 Page
14
xiv Contents Compare Superheroes ⭑⭑ 279 Concatenate Hero Comparators ⭑ 280 Using a Key Extractor to Easily Create a Comparator ⭑⭑ 280 Sort Points by Distance to Center ⭑ 282 Find Stores Nearby ⭑⭑ 283 Autoboxing 283 Quiz: Handling Null Reference in Unboxing ⭑ 283 Quiz: Unboxing Surprise ⭑⭑ 284 Suggested Solutions 284 Generate equals(Object) and hashCode() 284 Existing equals(Object) Implementations 287 Quiz: Natural Order Or Not? 289 Compare Superheroes 289 Concatenate Hero Comparators 290 Using a Key Extractor to Easily Create a Comparator 291 Sort Points by Distance to Center 291 Find Stores Nearby 292 Quiz: Handling Null Reference in Unboxing 293 Quiz: Unboxing Surprise 294 Notes 294 Appendix A: Most Frequent Types and Methods in the Java Universe 295 A.1 Packages with the Most Common Types 295 A.2 100 Most Common Types 296 A.3 100 Most Common Methods 299 A.4 100 Most Common Methods Including Parameter List 302
📄 Page
15
xv About the Author Christian Ullenboom started his programming journey at the tender age of ten, typing his first lines of code into a C64. After mastering assembler programming and early BASIC extensions, he found his call‑ ing on the island of Java, following his studies in computer science and psychology. Despite indulging in Python, JavaScript, TypeScript, and Kotlin vacations, he remains a savant of all things Java. For over 20 years, Ullenboom has been a passionate software architect, Java trainer (check out http:// www.tutego.com), and IT specialist instructor. His expertise has resulted in a number of online video courses and reference books: • Java: The Comprehensive Guide (ISBN‑13: 978‑1493222957) • Spring Boot 3 and Spring Framework 6 (ISBN‑13: 978‑1493224753) • Java ist auch eine Insel: Java programmieren lernen mit dem umfassenden Standardwerk für Java‑Entwickler (ISBN‑13: 978‑3836287456) • Java SE 9 Standard‑Bibliothek: Das Handbuch für Java‑Entwickler (ISBN‑13: 978‑3836258746) • Captain CiaoCiao erobert Java: Das Trainingsbuch für besseres Java (ISBN‑13: 978‑3836284271) Christian Ullenboom has been spreading Java love through his books for years, earning him the coveted title of Java Champion from Sun (now Oracle) way back in 2005. Only a select few—about 300 world‑ wide—have achieved this status, making him a true Java superstar. As an instructor, Ullenboom understands that learning by doing is the most effective way to master a skill. So, he has compiled a comprehensive catalog of exercises that accompany his training courses. This book features a selection of those exercises, complete with documented solutions. His roots are in Sonsbeck, a small town in the Lower Rhine region of Germany.
📄 Page
16
(This page has no text content)
📄 Page
17
DOI: 10.1201/9781003454502-1 1 Introduction Many beginners in programming often ask themselves, “How can I strengthen my skills as a developer? How can I become a better programmer?” The answer is simple: study, attend webinars, learn, repeat, practice, and discuss your work with others. Many aspects of programming are similar to learning new skills. Just as a book can’t teach you how to play a musical instrument, watching the Fast and the Furious movie series won’t teach you how to drive. The brain develops patterns and structures through repeated practice. Learning a programming language and a natural language have many similarities. Consistent use of the language and the desire and need to express and communicate in it (just as you need to do so to order a burger or a beer) lead to gradual improvement in skills. Books and webinars on learning a programming language are available, but reading, learning, practicing, and repeating are just one aspect of becoming a successful software developer. To cre‑ ate effective software solutions, you need to creatively combine your knowledge, just as a musician regularly practices finger exercises and maintains their repertoire. The more effective your exercises are, the faster you will become a master. This book aims to help you progress and gain more hands‑on experience. Java 21 declares more than 2,300 classes, about 1,400 interfaces, close to 140 enumerations, around 50 exceptions, and a few annotation types and records are included as well. However, only a fraction of these types are relevant in practice. This book selects the most important types and methods for tasks, making them motivating and following Java conventions. Alternative solutions and approaches are also presented repeatedly. The goal is to make nonfunctional requirements clear because the quality of pro‑ grams is not just about “doing what it should”. Issues such as correct indentation, following naming con‑ ventions, proper use of modifiers, best practices, and design patterns are essential. The proposed solutions aim to demonstrate these principles, with the keyword being Clean Code. PREVIOUS KNOWLEDGE AND TARGET AUDIENCE The book is aimed at Java developers who are either new to Java or are already advanced and wish to learn more about the core language features. The intended audience includes: • Computer science students. • IT specialists. • Java programmers. • Software developers. • Job applicants. The book is centered around tasks and fully documented solutions, with detailed explanations of Java peculiarities, good object‑oriented programming practices, best practices, and design patterns. The exercises are best solved with a textbook, as this exercise book is not a traditional textbook. A useful approach is to work through a topic with a preferred textbook before attempting the exercises that cor‑ respond to it.
📄 Page
18
2 Java Programming Exercises The first set of tasks is designed for programming beginners who are new to Java. As you gain more experience with Java, the tasks become more challenging. Therefore, there are tasks for both beginners and advanced developers. Additionally, this book does not require the use of tools like profiling tools, as these are beyond the scope of this book. WORKING WITH THIS BOOK The task book is organized into different sections. The first section covers the Java language, followed by selected areas of the Java standard library, such as data structures or file processing. Each area is accompanied by programming tasks and “quiz” questions that contain surprises. Each section starts with a small motivation and characterization of the topic, followed by the exercises. Additional tips and hints are provided for particularly challenging assignments, while other exercises offer optional extensions for further exploration. The majority of exercises are independent of each other, making it easy for readers to dive in anywhere. However, in the chapter on imperative programming, some tasks build on each other to develop a larger program, and the same goes for the chapter on object‑oriented programming. The problem definitions make this clear, and more complex programs help to provide context for under‑ standing different language characteristics. Furthermore, a more complex program can motivate read‑ ers to continue. The exercises are rated with one, two, or three stars to indicate their complexity, although this rating is subjective to the author. 1 star ★: Simple exercises, suitable for beginners. They should be easy to solve without much effort. Often only transfer of knowledge is required, for example, by writing down things that are in a textbook differently. 2 stars ★★: The effort is higher here. Different techniques have to be combined. Greater creativity is required. 3 stars ★★★: Assignments with three stars are more complex, require recourse to more prior knowledge, and sometimes require research. Frequently, the tasks can no longer be solved with a single method, but require multiple classes that must work together. THE SUGGESTED SOLUTIONS The task book provides at least one suggested solution for each problem. The term “sample solution” is not used to avoid implying that the given solution is the best one and that all other solutions are useless. Readers are encouraged to compare their solutions with the proposed solution and can be satisfied if their solution is more refined. All proposed solutions are commented, making it possible to follow all steps well. The suggested solutions are compiled at the end of each chapter to reduce the temptation to look into a solution directly after the task, which takes the fun out of solving the task. The suggested solu‑ tions can also be found on the website https://github.com/ullenboom/captain‑ciaociao. Some solu‑ tions contain comments of the type //tag::solution[], which marks the parts of the solutions printed in the book.
📄 Page
19
• Introduction 3 USE OF THIS BOOK To become a software developer, you must master the art of turning problems into code, and that’s where practice and role models come in. While there are plenty of exercises available online, they’re often disorganized, poorly documented, and outdated. That’s where this book shines, by offering a systematic approach to tasks and well‑thought‑out solutions. Studying these solutions and reading code in general helps the brain develop patterns and solutions that can be applied to future coding challenges. It’s like reading the Bible; you need to read to understand and learn. Surprisingly, many software developers write code without bothering to read others’ code, which can lead to confusion and misunderstand‑ ing. Reading good code elevates our writing skills by building patterns and solutions that our brains unconsciously transfer to our own code. Our brains form neuronal structures independently based on templates, and the quality of the input we receive matters greatly. Therefore, we should only feed our brains with good code, as bad solutions make for bad models. The book covers important topics such as exception handling or error handling, discussing the correct input values, identifying erroneous states, and how to handle them. In software, things can and will go wrong, and we must be prepared to deal with the less‑than‑perfect world. It’s easy for developers to get stuck in their ways of writing code, which is why it’s important to explore new approaches and “expand our vocabulary”, so to speak. For Java developers, libraries are their vocabulary, but too many enterprise Java developers write massive, non‑object‑oriented code. The solu‑ tion is to continuously improve object‑oriented modeling, which is precisely what this book demonstrates. It introduces new methods, creates new data types, and minimizes complexity. Additionally, functional programming is becoming increasingly important in Java development, and all solutions in this book take advantage of modern language features. While some solutions may appear overly complex, the tasks and proposed solutions in this book can help developers improve their ability to concentrate and follow through with steps. In practice, the ability to concentrate and quickly comprehend code is crucial for developers. Often, developers must join a new team and be able to understand and modify unfamiliar source code, and possibly fix bugs. Those who wish to expand upon existing open‑source solutions can also benefit from honing their concentration skills through these exercises. In addition to its emphasis on the Java programming language, syntax, libraries, and object orien‑ tation, this book provides numerous side notes on topics such as algorithms, the historical evolution of programming, comparisons to other programming languages, and data formats. These additional insights and perspectives offer readers a more well‑rounded understanding of software development beyond just the technical aspects. If you’re looking for one more reason to add this book to your collection, it doubles as a fantastic sleep aid! REQUIRED SOFTWARE While solving a task with just a pen and paper is possible in theory, modern software development requires the proper use of tools. Knowing programming language syntax, object‑oriented modeling, and libraries is just the tip of the iceberg. Understanding the JVM (Java Virtual Machine), using tools like Maven and Git for version management, and becoming proficient in an IDE (Integrated Development Environment) are all crucial aspects of professional software development. Some developers can even perform magic in their IDE, generating code and fixing bugs automatically.
📄 Page
20
4 Java Programming Exercises USED JAVA VERSION IN THE BOOK While Java version 8 remains still strong in enterprise settings, it’s crucial for learners to become acquainted with the latest language features. Accordingly, whenever feasible, the suggested solutions in this book leverage Java 21. Not only is this version equipped with long‑term support (LTS), but runtime environment providers also offer extensive support, ensuring that the release retains its relevance for an extended period. JVM If we want to run Java programs, we need a JVM. In the early days, this was easy. The runtime environ‑ ment first came from Sun Microsystems, later from Oracle, which took over Sun. Today, it is much more confusing. Although a runtime environment can still be obtained from Oracle, the licensing terms have changed, at least for Java 8 up to Java 16. Testing and development are possible with the Oracle JDK, but not in production. In this case, Oracle charges license fees. As a consequence, various institutions compile their own runtime environments from the OpenJDK, the original sources. The best known are Eclipse Adoptium (https://adoptium.net/), Amazon Corretto (https://aws.amazon.com/de/corretto), Red Hat OpenJDK (https://developers.redhat.com/products/openjdk/overview), and others such as those from Azul Systems or Bellsoft. There is no specific distribution that readers are required to follow. Development Environment Java source code is just plain text, so technically a simple text editor is all you need. However, relying solely on Notepad or vi for productivity is like trying to win a race on a tricycle. Modern integrated development environments support us with many tasks: color highlighting of keywords, automatic code completion, intelligent error correction, insertion of code blocks, visualization of states in the debugger, and much more. It is therefore advisable to use a full development environment. Four popular IDEs are: IntelliJ, Eclipse, Visual Studio Code, and (Apache) NetBeans. Just like with Java runtime environments, the choice of IDE is left to the reader. Eclipse, NetBeans, and Visual Studio Code are all free and open‑source, while IntelliJ Community Edition is also free, but the more advanced IntelliJ Ultimate Edition will cost you some cash. Halfway through the book, we delve into implementing project dependencies using Maven in a few places. CONVENTIONS Code is written in fix width font, filenames are italicized. To distinguish methods from attributes, methods always have a pair of parentheses, such as in “the variable max contains the maximum” or “it returns max() the maximum”. Since methods can be overloaded, either the parameter list is named, as in equals(Object), or an ellipsis abbreviates it, such as in “various println(…) methods”. If a group of identifiers is addressed, * is written, like print*(...) prints something on the screen. In the suggested solutions, there are usually only the relevant code snippets, so as not to blow up the book volume. The name of the file is mentioned in the listing caption, like this: VanillaJava.java class VanillaJava { }
The above is a preview of the first 20 pages. Register to read the complete e-book.
Recommended for You
Loading recommended books...
Failed to load, please try again later