Book description
Develop your coding skills by exploring Java concepts and techniques such as Strings, Objects and Types, Data Structures and Algorithms, Concurrency, and Functional programming
Key Features
- Solve Java programming challenges and get interview-ready by using the power of modern Java 11
- Test your Java skills using language features, algorithms, data structures, and design patterns
- Explore areas such as web development, mobile development, and GUI programming
Book Description
The super-fast evolution of the JDK between versions 8 and 12 has increased the learning curve of modern Java, therefore has increased the time needed for placing developers in the Plateau of Productivity. Its new features and concepts can be adopted to solve a variety of modern-day problems. This book enables you to adopt an objective approach to common problems by explaining the correct practices and decisions with respect to complexity, performance, readability, and more.
Java Coding Problems will help you complete your daily tasks and meet deadlines. You can count on the 300+ applications containing 1,000+ examples in this book to cover the common and fundamental areas of interest: strings, numbers, arrays, collections, data structures, date and time, immutability, type inference, Optional, Java I/O, Java Reflection, functional programming, concurrency and the HTTP Client API. Put your skills on steroids with problems that have been carefully crafted to highlight and cover the core knowledge that is accessed in daily work. In other words (no matter if your task is easy, medium or complex) having this knowledge under your tool belt is a must, not an option.
By the end of this book, you will have gained a strong understanding of Java concepts and have the confidence to develop and choose the right solutions to your problems.
What you will learn
- Adopt the latest JDK 11 and JDK 12 features in your applications
- Solve cutting-edge problems relating to collections and data structures
- Get to grips with functional-style programming using lambdas
- Perform asynchronous communication and parallel data processing
- Solve strings and number problems using the latest Java APIs
- Become familiar with different aspects of object immutability in Java
- Implement the correct practices and clean code techniques
Who this book is for
If you are a Java developer who wants to level-up by solving real-world problems, then this book is for you. Working knowledge of Java is required to get the most out of this book.
Table of contents
- Title Page
- Copyright and Credits
- About Packt
- Contributors
- Preface
-
Strings, Numbers, and Math
- Problems
-
Solutions
- 1. Counting duplicate characters
- 2. Finding the first non-repeated character
- 3. Reversing letters and words
- 4. Checking whether a string contains only digits
- 5. Counting vowels and consonants
- 6. Counting the occurrences of a certain character
- 7. Converting a string into an int, long, float, or double
- 8. Removing white spaces from a string
- 9. Joining multiple strings with a delimiter
- 10. Generating all permutations
- 11. Checking whether a string is a palindrome
- 12. Removing duplicate characters
- 13. Removing a given character
- 14. Finding the character with the most appearances
- 15. Sorting an array of strings by length
- 16. Checking that a string contains a substring
- 17. Counting substring occurrences in a string
- 18. Checking whether two strings are anagrams
- 19. Declaring multiline strings (text blocks)
- 20. Concatenating the same string n times
- 21. Removing leading and trailing spaces
- 22. Finding the longest common prefix
- 23. Applying indentation
- 24. Transforming strings
- 25. Computing the minimum and maximum of two numbers
- 26. Summing two large int/long values and operation overflow
- 27. String as an unsigned number in the radix
- 28. Converting into a number by an unsigned conversion
- 29. Comparing two unsigned numbers
- 30. Division and modulo of unsigned values
- 31. double/float is a finite floating-point value
- 32. Applying logical AND/OR/XOR to two boolean expressions
- 33. Converting BigInteger into a primitive type
- 34. Converting long into int
- 35. Computing the floor of a division and modulus
- 36. Next floating-point value
- 37. Multiplying two large int/long values and operation overflow
- 38. Fused Multiply Add
- 39. Compact number formatting
- Summary
-
Objects, Immutability, and Switch Expressions
- Problems
-
Solutions
- 40. Checking null references in functional style and imperative code
- 41. Checking null references and throwing customized NullPointerException
- 42. Checking null references and throwing the specified exception
- 43. Checking null references and returning non-null default references
- 44. Checking the index in the range from 0 to length
- 45. Checking the subrange in the range from 0 to length
- 46. equals() and hashCode()
- 47. Immutable objects in a nutshell
- 48. Immutable string
- 49. Writing an immutable class
- 50. Passing/returning mutable objects to/from an immutable class
- 51. Writing an immutable class via the Builder pattern
- 52. Avoiding bad data in immutable objects
- 53. Cloning objects
- 54. Overriding toString()
- 55. Switch expressions
- 56. Multiple case labels
- 57. Statement blocks
- Summary
-
Working with Date and Time
- Problems
-
Solutions
- 58. Converting a string to date and time
- 59. Formatting date and time
- 60. Getting the current date/time without time/date
- 61. LocalDateTime from LocalDate and LocalTime
- 62. Machine time via an Instant class
- 63. Defining a period of time using date-based values and a duration of time using time-based values
- 64. Getting date and time units
- 65. Adding and subtracting to/from date-time
- 66. Getting all time zones with UTC and GMT
- 67. Getting local date-time in all available time zones
- 68. Displaying date-time information about a flight
- 69. Converting a Unix timestamp to date-time
- 70. Finding the first/last day of the month
- 71. Defining/extracting zone offsets
- 72. Converting between Date and Temporal
- 73. Iterating a range of dates
- 74. Calculating age
- 75. Start and end of a day
- 76. Difference between two dates
- 77. Implementing a chess clock
- Summary
-
Type Inference
- Problems
-
Solutions
- 78. Simple var example
- 79. Using var with primitive types
- 80. Using var and implicit type casting to sustain the code's maintainability
- 81. Explicit downcast or better avoid var
- 82. Avoid using var if the called names don't contain enough type information for humans
- 83. Combining LVTI and programming to the interface technique
- 84. Combining LVTI and the diamond operator
- 85. Assigning an array to var
- 86. Using LVTI in compound declarations
- 87. LVTI and variable scope
- 88. LVTI and the ternary operator
- 89. LVTI and for loops
- 90. LVTI and streams
- 91. Using LVTI to break up nested/large chains of expressions
- 92. LVTI and the method return and argument types
- 93. LVTI and anonymous classes
- 94. LVTI can be final and effectively final
- 95. LVTI and lambdas
- 96. LVTI and null initializers, instance variables, and catch blocks variables
- 97. LVTI and generic types, T
- 98. LVTI, wildcards, covariants, and contravariants
- Summary
-
Arrays, Collections, and Data Structures
- Problems
-
Solutions
- 99. Sorting an array
- 100. Finding an element in an array
- 101. Checking whether two arrays are equal or mismatches
- 102. Comparing two arrays lexicographically
- 103. Creating a Stream from an array
- 104. Minimum, maximum, and average of an array
- 105. Reversing an array
- 106. Filling and setting an array
- 107. Next Greater Element
- 108. Changing array size
- 109. Creating unmodifiable/immutable collections
- 110. Mapping a default value
- 111. Computing whether absent/present in a map
- 112. Removal from a Map
- 113. Replacing entries from a Map
- 114. Comparing two maps
- 115. Sorting a Map
- 116. Copying HashMap
- 117. Merging two maps
- 118. Removing all elements of a collection that match a predicate
- 119. Converting a collection into an array
- 120. Filtering a Collection by a List
- 121. Replacing elements of a List
- 122. Thread-safe collections, stacks, and queues
- 123. Breadth-first search
- 124. Trie
- 125. Tuple
- 126. Union Find
- 127. Fenwick Tree or Binary Indexed Tree
- 128. Bloom filter
- Summary
-
Java I/O Paths, Files, Buffers, Scanning, and Formatting
- Problems
-
Solutions
- 129. Creating file paths
- 130. Converting file paths
- 131. Joining file paths
- 132. Constructing a path between two locations
- 133. Comparing file paths
- 134. Walking paths
- 135. Watching paths
- 136. Streaming a file's content
- 137. Searching for files/folders in a file tree
- 138. Reading/writing text files efficiently
- 139. Reading/writing binary files efficiently
- 140. Searching in big files
- 141. Reading a JSON/CSV file as an object
- 142. Working with temporary files/folders
- 143. Filtering files
- 144. Discovering mismatches between two files
- 145. Circular byte buffer
- 146. Tokenizing files
- 147. Writing formatted output directly to a file
- 148. Working with Scanner
- Summary
-
Java Reflection Classes, Interfaces, Constructors, Methods, and Fields
- Problems
-
Solutions
- 149. Inspecting packages
-
150. Inspecting classes
- Get the name of the Pair class via an instance
- Getting the Pair class modifiers
- Getting the Pair class implemented interfaces
- Getting the Pair class constructors
- Getting the Pair class fields
- Getting the Pair class methods
- Getting the Pair class module
- Getting the Pair class superclass
- Getting the name of a certain type
- Getting a string that describes the class
- Getting the type descriptor string for a class
- Getting the component type of an array
- Getting a class for an array type whose component type is described by Pair
- 151. Instantiating via a reflected constructor
- 152. Getting the annotation of a receiver type
- 153. Getting synthetic and bridge constructs
- 154. Checking the variable number of arguments
- 155. Checking default methods
- 156. Nest-based access control via reflection
- 157. Reflection for getters and setters
-
158. Reflecting annotations
- Inspecting package annotations
- Inspecting class annotations
- Inspecting methods annotations
- Inspecting annotations of the thrown exceptions
- Inspecting annotations of the return type
- Inspecting annotations of the method's parameters
- Inspecting annotations of fields
- Inspecting annotations of the superclass
- Inspecting annotations of interfaces
- Get annotations by type
- Get a declared annotation
- 159. Invoking an instance method
- 160. Getting static methods
- 161. Getting generic types of method, fields, and exceptions
- 162. Getting public and private fields
- 163. Working with arrays
- 164. Inspecting modules
- 165. Dynamic proxies
- Summary
-
Functional Style Programming - Fundamentals and Design Patterns
- Problems
-
Solutions
- 166. Writing functional interfaces
- 167. Lambdas in a nutshell
- 168. Implementing the Execute Around pattern
- 169. Implementing the Factory pattern
- 170. Implementing the Strategy pattern
- 171. Implementing the Template Method pattern
- 172. Implementing the Observer pattern
- 173. Implementing the Loan pattern
- 174. Implementing the Decorator pattern
- 175. Implementing the Cascaded Builder pattern
- 176. Implementing the Command pattern
- Summary
-
Functional Style Programming - a Deep Dive
- Problems
-
Solutions
- 177. Testing high-order functions
- 178. Testing methods that use lambdas
- 179. Debugging lambdas
- 180. Filtering the non-zero elements of a stream
- 181. Infinite streams, takeWhile(), and dropWhile()
- 182. Mapping the elements of a stream
- 183. Finding elements in a stream
- 184. Matching elements in a stream
- 185. Sum, max, and min in a stream
- 186. Collecting the result of a stream
- 187. Joining the results of a stream
- 188. Summarization collectors
- 189. Grouping
- 190. Partitioning
- 191. Filtering, flattening, and mapping collectors
- 192. Teeing
-
193. Writing a custom collector
- The supplier – Supplier<A> supplier();
- Accumulating elements – BiConsumer<A, T> accumulator();
- Applying the final transformation – Function<A, R> finisher();
- Parallelizing the collector – BinaryOperator<A> combiner();
- Returning the final result – Function<A, R> finisher();
- Characteristics – Set<Characteristics> characteristics();
- Testing time
- Custom collecting via collect()
- 194. Method reference
- 195. Parallel processing of streams
- 196. Null-safe streams
- 197. Composing functions, predicates, and comparators
- 198. Default methods
- Summary
-
Concurrency - Thread Pools, Callables, and Synchronizers
- Problems
-
Solutions
- 199. Thread life cycle states
- 200. Object- versus class-level locking
- 201. Thread pools in Java
- 202. Thread pool with a single thread
- 203. Thread pool with a fixed number of threads
- 204. Cached and scheduled thread pools
- 205. Work-stealing thread pool
- 206. Callable and Future
- 207. Invoking multiple Callable tasks
- 208. Latches
- 209. Barrier
- 210. Exchanger
- 211. Semaphores
- 212. Phasers
- Summary
-
Concurrency - Deep Dive
- Problems
-
Solutions
- 213. Interruptible methods
- 214. Fork/join framework
- 215. Fork/join framework and compareAndSetForkJoinTaskTag()
-
216. CompletableFuture
- Running asynchronous task and return void
- Running an asynchronous task and returning a result
- Running an asynchronous task and returning a result via an explicit thread pool
- Attaching a callback that processes the result of an asynchronous task and returns a result
- Attaching a callback that processes the result of an asynchronous task and returns void
- Attaching a callback that runs after an asynchronous task and returns void
- Handling exceptions of an asynchronous task via exceptionally()
- JDK 12 exceptionallyCompose()
- Handling exceptions of an asynchronous task via handle()
- Explicitly complete a CompletableFuture
- 217. Combining multiple CompletableFuture instances
- 218. Optimizing busy waiting
- 219. Task Cancellation
- 220. ThreadLocal
- 221. Atomic variables
- 222. ReentrantLock
- 223. ReentrantReadWriteLock
- 224. StampedLock
- 225. Deadlock (dining philosophers)
- Summary
-
Optional
- Problems
-
Solutions
- 226. Initializing Optional
- 227. Optional.get() and missing value
- 228. Returning an already-constructed default value
- 229. Returning a non-existent default value
- 230. Throwing NoSuchElementException
- 231. Optional and null references
- 232. Consuming a present Optional class
- 233. Returning a present Optional class or another one
- 234. Chaining lambdas via orElseFoo()
- 235. Do not use Optional just for getting a value
- 236. Do not use Optional for fields
- 237. Do not use Optional in constructor args
- 238. Do not use Optional in setter args
- 239. Do not use Optional in method args
- 240. Do not use Optional to return empty or null collections or arrays
- 241. Avoiding Optional in collections
- 242. Confusing of() with ofNullable()
- 243. Optional<T> versus OptionalInt
- 244. Asserting equality of Optionals
- 245. Transforming values via Map() and flatMap()
- 246. Filter values via Optional.filter()
- 247. Chaining the Optional and Stream APIs
- 248. Optional and identity-sensitive operations
- 249. Returning a boolean if the Optional class is empty
- Summary
-
The HTTP Client and WebSocket APIs
- Problems
-
Solutions
- 250. HTTP/2
- 251. Triggering an asynchronous GET request
- 252. Setting a proxy
- 253. Setting/getting headers
- 254. Specifying the HTTP method
- 255. Setting a request body
- 256. Setting connection authentication
- 257. Setting a timeout
- 258. Setting the redirect policy
- 259. Sending sync and async requests
- 260. Handling cookies
- 261. Getting response information
- 262. Handling response body types
- 263. Getting, updating, and saving a JSON
- 264. Compression
- 265. Handling form data
- 266. Downloading a resource
- 267. Uploading with multipart
- 268. HTTP/2 server push
- 269. WebSocket
- Summary
- Other Books You May Enjoy
Product information
- Title: Java Coding Problems
- Author(s):
- Release date: September 2019
- Publisher(s): Packt Publishing
- ISBN: 9781789801415
You might also like
book
The Well-Grounded Java Developer, Second Edition
Understanding Java from the JVM up gives you a solid foundation to grow your expertise and …
book
Learning Java, 6th Edition
Ideal for working programmers new to Java, this best-selling book guides you through the language features …
book
Learning Java, 4th Edition
Java is the preferred language for many of today’s leading-edge technologies—everything from smartphones and game consoles …
book
Java in a Nutshell, 7th Edition
This updated edition of Java in a Nutshell not only helps experienced Java programmers get the …