Table Of ContentJava Coding Problems
Improve your Java Programming skills by solving
real-world coding challenges
Anghel Leonard
BIRMINGHAM - MUMBAI
Java Coding Problems
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in
any form or by any means, without the prior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express or
implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any
damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the
accuracy of this information.
Commissioning Editor: Richa Tripathi
Acquisition Editor: Alok Dhuri
Content Development Editor: Zeeyan Pinheiro
Senior Editor: Afshaan Khan
Technical Editor: Pradeep Sahu
Copy Editor: Safis Editing
Project Coordinator: Prajakta Naik
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Aparna Bhagat
First published: September 2019
Production reference: 1200919
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78980-141-5
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos,
as well as industry leading tools to help you plan your personal development and
advance your career. For more information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical eBooks and
Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.packt.com and
as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at customercare@packtpub.com for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for
a range of free newsletters, and receive exclusive discounts and offers on Packt books
and eBooks.
Contributors
About the author
Anghel Leonard is a Chief Technology Strategist with more than 20 years of
experience in the Java ecosystem. In his daily work, he is focused on architecting and
developing Java distributed applications that empower robust architectures, clean
code, and high performance. He is also passionate about coaching, mentoring, and
technical leadership.
He is the author of several books, videos, and dozens of articles related to Java
technologies.
About the reviewers
Cristian Stancalau has an MSc and BSc in computer science and engineering from
Babes-Bolyai University, where he has contributed as an assistant lecturer since 2018.
Currently, he works as chief software architect, focused on enterprise code review at
DevFactory.
Previously, he co-founded and lead a video technology start-up as technical director.
Cristian has proven mentoring and teaching expertise in both the commercial and
academic sectors, advising on Java technologies and product architecture.
I would like to thank Anghel Leonard for the honor of entrusting me to perform the
technical review for Java Coding Problems. Reading it was a real pleasure for me
and I am sure it will also be for his readers.
Vishnu Govindrao Kulkarni is an enthusiastic freelancer solutions provider (with
Fortune Consulting). He has a wide range of experience in various domains, with 8
years of experience working with full-stack Java, Java Spring, Spring Boot, the
Hibernate REST API, and Oracle. He has also had the opportunity to work with
several organizations to build enterprise solutions using Java and Java frameworks.
Today, he continues to design and develop solutions while closely working with
clients to help them derive value from these solutions.
Previously, he worked as the technical reviewer for the book Java Fundamentals for
Packt Publishing.
Packt is searching for authors like you
If you're interested in becoming an author for Packt, please visit
authors.packtpub.com and apply today. We have worked with thousands of
developers and tech professionals, just like you, to help them share their insight with
the global tech community. You can make a general application, apply for a specific
hot topic that we are recruiting an author for, or submit your own idea.
Table of Contents
Preface 1
Chapter 1: Strings, Numbers, and Math 8
Problems 8
Solutions 11
1. Counting duplicate characters 11
What about Unicode characters? 12
2. Finding the first non-repeated character 14
3. Reversing letters and words 17
4. Checking whether a string contains only digits 18
5. Counting vowels and consonants 19
6. Counting the occurrences of a certain character 21
7. Converting a string into an int, long, float, or double 23
8. Removing white spaces from a string 24
9. Joining multiple strings with a delimiter 24
10. Generating all permutations 26
11. Checking whether a string is a palindrome 28
12. Removing duplicate characters 30
13. Removing a given character 32
14. Finding the character with the most appearances 33
15. Sorting an array of strings by length 36
16. Checking that a string contains a substring 37
17. Counting substring occurrences in a string 38
18. Checking whether two strings are anagrams 40
19. Declaring multiline strings (text blocks) 41
20. Concatenating the same string n times 43
21. Removing leading and trailing spaces 45
22. Finding the longest common prefix 45
23. Applying indentation 47
24. Transforming strings 49
25. Computing the minimum and maximum of two numbers 50
26. Summing two large int/long values and operation overflow 51
27. String as an unsigned number in the radix 52
28. Converting into a number by an unsigned conversion 53
29. Comparing two unsigned numbers 54
30. Division and modulo of unsigned values 55
31. double/float is a finite floating-point value 56
32. Applying logical AND/OR/XOR to two boolean expressions 57
33. Converting BigInteger into a primitive type 58
34. Converting long into int 59
Table of Contents
35. Computing the floor of a division and modulus 60
36. Next floating-point value 61
37. Multiplying two large int/long values and operation overflow 62
38. Fused Multiply Add 64
39. Compact number formatting 65
Formatting 65
Parsing 68
Summary 69
Chapter 2: Objects, Immutability, and Switch Expressions 70
Problems 70
Solutions 72
40. Checking null references in functional style and imperative code 72
41. Checking null references and throwing customized
NullPointerException 75
42. Checking null references and throwing the specified exception 77
43. Checking null references and returning non-null default references 79
44. Checking the index in the range from 0 to length 80
45. Checking the subrange in the range from 0 to length 83
46. equals() and hashCode() 85
47. Immutable objects in a nutshell 91
48. Immutable string 91
Pros of string immutability 92
String constant pool or cached pool 92
Security 94
Thread safety 94
Hash code caching 94
Class loading 94
Cons of string immutability 95
String cannot be extended 95
Sensitive data in memory for a long time 95
OutOfMemoryError 95
Is String completely immutable? 95
49. Writing an immutable class 96
50. Passing/returning mutable objects to/from an immutable class 97
51. Writing an immutable class via the Builder pattern 100
52. Avoiding bad data in immutable objects 103
53. Cloning objects 105
Manual cloning 105
Cloning via clone() 106
Cloning via a constructor 107
Cloning via the Cloning library 108
Cloning via serialization 109
Cloning via JSON 110
54. Overriding toString() 110
55. Switch expressions 112
56. Multiple case labels 115
57. Statement blocks 116
[ ii ]
Table of Contents
Summary 117
Chapter 3: Working with Date and Time 118
Problems 118
Solutions 120
58. Converting a string to date and time 120
Before JDK 8 120
Starting with JDK 8 120
59. Formatting date and time 124
60. Getting the current date/time without time/date 128
61. LocalDateTime from LocalDate and LocalTime 128
62. Machine time via an Instant class 129
Converting String to Instant 130
Adding or subtracting time to/from Instant 130
Comparing Instant objects 130
Converting between Instant and LocalDateTime, ZonedDateTime, and
OffsetDateTime 131
63. Defining a period of time using date-based values and a duration
of time using time-based values 132
Period of time using date-based values 132
Duration of time using time-based values 134
64. Getting date and time units 137
65. Adding and subtracting to/from date-time 138
Working with Date 139
Working with LocalDateTime 139
66. Getting all time zones with UTC and GMT 140
Before JDK 8 140
Starting with JDK 8 140
67. Getting local date-time in all available time zones 142
Before JDK 8 142
Starting with JDK 8 143
68. Displaying date-time information about a flight 144
69. Converting a Unix timestamp to date-time 145
70. Finding the first/last day of the month 146
71. Defining/extracting zone offsets 149
Before JDK 8 150
Starting with JDK 8 150
72. Converting between Date and Temporal 151
Date – Instant 152
Date – LocalDate 153
Date – DateLocalTime 154
Date – ZonedDateTime 154
Date – OffsetDateTime 155
Date – LocalTime 155
Date – OffsetTime 156
73. Iterating a range of dates 156
Before JDK 8 156
Starting with JDK 8 157
[ iii ]
Table of Contents
Starting with JDK 9 157
74. Calculating age 158
Before JDK 8 158
Starting with JDK 8 158
75. Start and end of a day 159
76. Difference between two dates 162
Before JDK 8 162
Starting with JDK 8 162
77. Implementing a chess clock 164
Summary 169
Chapter 4: Type Inference 170
Problems 170
Solutions 172
78. Simple var example 172
79. Using var with primitive types 175
80. Using var and implicit type casting to sustain the code's
maintainability 176
81. Explicit downcast or better avoid var 178
82. Avoid using var if the called names don't contain enough type
information for humans 179
83. Combining LVTI and programming to the interface technique 180
84. Combining LVTI and the diamond operator 181
85. Assigning an array to var 183
86. Using LVTI in compound declarations 184
87. LVTI and variable scope 184
88. LVTI and the ternary operator 186
89. LVTI and for loops 187
90. LVTI and streams 188
91. Using LVTI to break up nested/large chains of expressions 189
92. LVTI and the method return and argument types 190
93. LVTI and anonymous classes 191
94. LVTI can be final and effectively final 192
95. LVTI and lambdas 193
96. LVTI and null initializers, instance variables, and catch blocks
variables 194
Try-with-resource 195
97. LVTI and generic types, T 195
98. LVTI, wildcards, covariants, and contravariants 196
LVTI and wildcards 197
LVTI and covariants/contravariants 197
Summary 198
Chapter 5: Arrays, Collections, and Data Structures 199
Problems 199
Solutions 201
99. Sorting an array 201
[ iv ]