📄 Page
1
Java Notes for ProfessionalsJava® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial Java® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 900+ pages of professional hints and tricks
📄 Page
2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with Java Language 2 .......................................................................................... Section 1.1: Creating Your First Java Program 2 ........................................................................................................... Chapter 2: Type Conversion 8 .................................................................................................................................... Section 2.1: Numeric primitive casting 8 ......................................................................................................................... Section 2.2: Basic Numeric Promotion 8 ........................................................................................................................ Section 2.3: Non-numeric primitive casting 8 ................................................................................................................ Section 2.4: Object casting 9 ........................................................................................................................................... Section 2.5: Testing if an object can be cast using instanceof 9 ................................................................................. Chapter 3: Getters and Setters 10 ........................................................................................................................... Section 3.1: Using a setter or getter to implement a constraint 10 ............................................................................. Section 3.2: Why Use Getters and Setters? 10 .............................................................................................................. Section 3.3: Adding Getters and Setters 11 ................................................................................................................... Chapter 4: Reference Data Types 13 .................................................................................................................... Section 4.1: Dereferencing 13 .......................................................................................................................................... Section 4.2: Instantiating a reference type 13 ............................................................................................................... Chapter 5: Java Compiler - 'javac' 14 .................................................................................................................... Section 5.1: The 'javac' command - getting started 14 ................................................................................................ Section 5.2: Compiling for a dierent version of Java 16 ............................................................................................ Chapter 6: Documenting Java Code 18 ................................................................................................................. Section 6.1: Building Javadocs From the Command Line 18 ....................................................................................... Section 6.2: Class Documentation 18 ............................................................................................................................. Section 6.3: Method Documentation 19 ......................................................................................................................... Section 6.4: Package Documentation 20 ....................................................................................................................... Section 6.5: Links 20 ......................................................................................................................................................... Section 6.6: Code snippets inside documentation 21 ................................................................................................... Section 6.7: Field Documentation 22 .............................................................................................................................. Section 6.8: Inline Code Documentation 22 ................................................................................................................... Chapter 7: Command line Argument Processing 24 ....................................................................................... Section 7.1: Argument processing using GWT ToolBase 24 ......................................................................................... Section 7.2: Processing arguments by hand 24 ............................................................................................................ Chapter 8: The Java Command - 'java' and 'javaw' 27 ................................................................................. Section 8.1: Entry point classes 27 .................................................................................................................................. Section 8.2: Troubleshooting the 'java' command 27 .................................................................................................. Section 8.3: Running a Java application with library dependencies 29 ..................................................................... Section 8.4: Java Options 30 ........................................................................................................................................... Section 8.5: Spaces and other special characters in arguments 31 ........................................................................... Section 8.6: Running an executable JAR file 33 ............................................................................................................ Section 8.7: Running a Java applications via a "main" class 33 ................................................................................. Chapter 9: Date Class 35 ............................................................................................................................................... Section 9.1: Convert java.util.Date to java.sql.Date 35 .................................................................................................. Section 9.2: A basic date output 35 ................................................................................................................................ Section 9.3: Java 8 LocalDate and LocalDateTime objects 36 ................................................................................... Section 9.4: Creating a Specific Date 37 ........................................................................................................................ Section 9.5: Converting Date to a certain String format 37 ......................................................................................... Section 9.6: LocalTime 38 ................................................................................................................................................
📄 Page
3
Section 9.7: Convert formatted string representation of date to Date object 38 ..................................................... Section 9.8: Creating Date objects 39 ............................................................................................................................ Section 9.9: Comparing Date objects 39 ........................................................................................................................ Section 9.10: Converting String into Date 42 ................................................................................................................. Section 9.11: Time Zones and java.util.Date 42 .............................................................................................................. Chapter 10: Dates and Time (java.time.*) 44 ...................................................................................................... Section 10.1: Calculate Dierence between 2 LocalDates 44 ....................................................................................... Section 10.2: Date and time 44 ........................................................................................................................................ Section 10.3: Operations on dates and times 44 ........................................................................................................... Section 10.4: Instant 44 ..................................................................................................................................................... Section 10.5: Usage of various classes of Date Time API 45 ....................................................................................... Section 10.6: Date Time Formatting 47 .......................................................................................................................... Section 10.7: Simple Date Manipulations 47 ................................................................................................................... Chapter 11: LocalTime 49 ............................................................................................................................................... Section 11.1: Amount of time between two LocalTime 49 ............................................................................................. Section 11.2: Intro 50 ......................................................................................................................................................... Section 11.3: Time Modification 50 ................................................................................................................................... Section 11.4: Time Zones and their time dierence 50 ................................................................................................. Chapter 12: Literals 52 .................................................................................................................................................... Section 12.1: Using underscore to improve readability 52 ............................................................................................ Section 12.2: Hexadecimal, Octal and Binary literals 52 ............................................................................................... Section 12.3: Boolean literals 53 ...................................................................................................................................... Section 12.4: String literals 53 .......................................................................................................................................... Section 12.5: The Null literal 54 ........................................................................................................................................ Section 12.6: Escape sequences in literals 54 ................................................................................................................ Section 12.7: Character literals 55 ................................................................................................................................... Section 12.8: Decimal Integer literals 55 ......................................................................................................................... Section 12.9: Floating-point literals 56 ............................................................................................................................ Chapter 13: Operators 59 .............................................................................................................................................. Section 13.1: The Increment/Decrement Operators (++/--) 59 .................................................................................... Section 13.2: The Conditional Operator (? :) 59 ............................................................................................................. Section 13.3: The Bitwise and Logical Operators (~, &, |, ^) 61 ..................................................................................... Section 13.4: The String Concatenation Operator (+) 62 .............................................................................................. Section 13.5: The Arithmetic Operators (+, -, *, /, %) 64 ................................................................................................ Section 13.6: The Shift Operators (<<, >> and >>>) 66 ................................................................................................... Section 13.7: The Instanceof Operator 67 ...................................................................................................................... Section 13.8: The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=) 68 ................................. Section 13.9: The conditional-and and conditional-or Operators ( && and || ) 70 ..................................................... Section 13.10: The Relational Operators (<, <=, >, >=) 71 ............................................................................................... Section 13.11: The Equality Operators (==, !=) 72 ............................................................................................................. Section 13.12: The Lambda operator ( -> ) 74 ................................................................................................................ Chapter 14: Primitive Data Types 75 ...................................................................................................................... Section 14.1: The char primitive 75 .................................................................................................................................. Section 14.2: Primitive Types Cheatsheet 75 .................................................................................................................. Section 14.3: The float primitive 76 ................................................................................................................................. Section 14.4: The int primitive 77 ..................................................................................................................................... Section 14.5: Converting Primitives 78 ............................................................................................................................ Section 14.6: Memory consumption of primitives vs. boxed primitives 78 .................................................................. Section 14.7: The double primitive 79 ............................................................................................................................. Section 14.8: The long primitive 80 ..................................................................................................................................
📄 Page
4
Section 14.9: The boolean primitive 81 ........................................................................................................................... Section 14.10: The byte primitive 81 ................................................................................................................................ Section 14.11: Negative value representation 82 ............................................................................................................ Section 14.12: The short primitive 83 ............................................................................................................................... Chapter 15: Constructors 84 ........................................................................................................................................ Section 15.1: Default Constructor 84 ............................................................................................................................... Section 15.2: Call parent constructor 85 ......................................................................................................................... Section 15.3: Constructor with Arguments 86 ................................................................................................................ Chapter 16: Object Class Methods and Constructor 88 ................................................................................. Section 16.1: hashCode() method 88 ............................................................................................................................... Section 16.2: toString() method 90 .................................................................................................................................. Section 16.3: equals() method 91 .................................................................................................................................... Section 16.4: wait() and notify() methods 93 ................................................................................................................. Section 16.5: getClass() method 95 ................................................................................................................................. Section 16.6: clone() method 96 ...................................................................................................................................... Section 16.7: Object constructor 97 ................................................................................................................................. Section 16.8: finalize() method 98 ................................................................................................................................... Chapter 17: Annotations 100 ........................................................................................................................................ Section 17.1: The idea behind Annotations 100 .............................................................................................................. Section 17.2: Defining annotation types 100 .................................................................................................................. Section 17.3: Runtime annotation checks via reflection 102 ........................................................................................ Section 17.4: Built-in annotations 102 ............................................................................................................................. Section 17.5: Compile time processing using annotation processor 105 .................................................................... Section 17.6: Repeating Annotations 109 ....................................................................................................................... Section 17.7: Inherited Annotations 110 .......................................................................................................................... Section 17.8: Getting Annotation values at run-time 111 ............................................................................................. Section 17.9: Annotations for 'this' and receiver parameters 112 ............................................................................... Section 17.10: Add multiple annotation values 113 ....................................................................................................... Chapter 18: Immutable Class 114 .............................................................................................................................. Section 18.1: Example without mutable refs 114 ............................................................................................................ Section 18.2: What is the advantage of immutability? 114 .......................................................................................... Section 18.3: Rules to define immutable classes 114 .................................................................................................... Section 18.4: Example with mutable refs 115 ................................................................................................................. Chapter 19: Immutable Objects 116 ......................................................................................................................... Section 19.1: Creating an immutable version of a type using defensive copying 116 .............................................. Section 19.2: The recipe for an immutable class 116 .................................................................................................... Section 19.3: Typical design flaws which prevent a class from being immutable 117 .............................................. Chapter 20: Visibility (controlling access to members of a class) 121 .................................................. Section 20.1: Private Visibility 121 ................................................................................................................................... Section 20.2: Public Visibility 121 .................................................................................................................................... Section 20.3: Package Visibility 122 ............................................................................................................................... Section 20.4: Protected Visibility 122 .............................................................................................................................. Section 20.5: Summary of Class Member Access Modifiers 123 ................................................................................. Section 20.6: Interface members 123 ............................................................................................................................ Chapter 21: Generics 124 ................................................................................................................................................ Section 21.1: Creating a Generic Class 124 ..................................................................................................................... Section 21.2: Deciding between `T`, `? super T`, and `? extends T` 126 ........................................................................ Section 21.3: The Diamond 128 ....................................................................................................................................... Section 21.4: Declaring a Generic Method 128 ..............................................................................................................
📄 Page
5
Section 21.5: Requiring multiple upper bounds ("extends A & B") 129 ....................................................................... Section 21.6: Obtain class that satisfies generic parameter at runtime 129 .............................................................. Section 21.7: Benefits of Generic class and interface 130 ............................................................................................ Section 21.8: Instantiating a generic type 131 ............................................................................................................... Section 21.9: Creating a Bounded Generic Class 131 ................................................................................................... Section 21.10: Referring to the declared generic type within its own declaration 133 .............................................. Section 21.11: Binding generic parameter to more than 1 type 134 ............................................................................. Section 21.12: Using Generics to auto-cast 135 ............................................................................................................. Section 21.13: Use of instanceof with Generics 135 ....................................................................................................... Section 21.14: Dierent ways for implementing a Generic Interface (or extending a Generic Class) 137 .............. Chapter 22: Classes and Objects 139 ...................................................................................................................... Section 22.1: Overloading Methods 139 ......................................................................................................................... Section 22.2: Explaining what is method overloading and overriding 140 ................................................................ Section 22.3: Constructors 142 ........................................................................................................................................ Section 22.4: Initializing static final fields using a static initializer 143 ........................................................................ Section 22.5: Basic Object Construction and Use 144 .................................................................................................. Section 22.6: Simplest Possible Class 146 ...................................................................................................................... Section 22.7: Object Member vs Static Member 146 .................................................................................................... Chapter 23: Local Inner Class 148 ............................................................................................................................. Section 23.1: Local Inner Class 148 ................................................................................................................................. Chapter 24: Nested and Inner Classes 149 .......................................................................................................... Section 24.1: A Simple Stack Using a Nested Class 149 ............................................................................................... Section 24.2: Static vs Non Static Nested Classes 149 ................................................................................................. Section 24.3: Access Modifiers for Inner Classes 151 ................................................................................................... Section 24.4: Anonymous Inner Classes 152 ................................................................................................................. Section 24.5: Create instance of non-static inner class from outside 153 ................................................................. Section 24.6: Method Local Inner Classes 154 .............................................................................................................. Section 24.7: Accessing the outer class from a non-static inner class 154 ................................................................ Chapter 25: The java.util.Objects Class 156 ......................................................................................................... Section 25.1: Basic use for object null check 156 .......................................................................................................... Section 25.2: Objects.nonNull() method reference use in stream api 156 ................................................................. Chapter 26: Default Methods 157 ............................................................................................................................. Section 26.1: Basic usage of default methods 157 ........................................................................................................ Section 26.2: Accessing overridden default methods from implementing class 157 ............................................... Section 26.3: Why use Default Methods? 158 ............................................................................................................... Section 26.4: Accessing other interface methods within default method 158 ........................................................... Section 26.5: Default method multiple inheritance collision 159 ................................................................................. Section 26.6: Class, Abstract class and Interface method precedence 160 .............................................................. Chapter 27: Packages 162 ............................................................................................................................................ Section 27.1: Using Packages to create classes with the same name 162 ................................................................. Section 27.2: Using Package Protected Scope 162 ...................................................................................................... Chapter 28: Inheritance 164 ......................................................................................................................................... Section 28.1: Inheritance 164 ........................................................................................................................................... Section 28.2: Abstract Classes 165 ................................................................................................................................. Section 28.3: Using 'final' to restrict inheritance and overriding 167 .......................................................................... Section 28.4: The Liskov Substitution Principle 168 ...................................................................................................... Section 28.5: Abstract class and Interface usage: "Is-a" relation vs "Has-a" capability 169 ................................... Section 28.6: Static Inheritance 172 ................................................................................................................................ Section 28.7: Programming to an interface 173 ...........................................................................................................
📄 Page
6
Section 28.8: Overriding in Inheritance 175 ................................................................................................................... Section 28.9: Variable shadowing 176 ........................................................................................................................... Section 28.10: Narrowing and Widening of object references 176 ............................................................................. Section 28.11: Inheritance and Static Methods 177 ........................................................................................................ Chapter 29: Reference Types 179 ............................................................................................................................. Section 29.1: Dierent Reference Types 179 ................................................................................................................. Chapter 30: Strings 181 .................................................................................................................................................. Section 30.1: Comparing Strings 181 .............................................................................................................................. Section 30.2: Changing the case of characters within a String 183 ............................................................................ Section 30.3: Finding a String Within Another String 185 ............................................................................................. Section 30.4: String pool and heap storage 186 ........................................................................................................... Section 30.5: Splitting Strings 187 ................................................................................................................................... Section 30.6: Joining Strings with a delimiter 189 ......................................................................................................... Section 30.7: String concatenation and StringBuilders 190 ......................................................................................... Section 30.8: Substrings 191 ............................................................................................................................................ Section 30.9: Platform independent new line separator 192 ....................................................................................... Section 30.10: Reversing Strings 192 .............................................................................................................................. Section 30.11: Adding toString() method for custom objects 193 ................................................................................ Section 30.12: Remove Whitespace from the Beginning and End of a String 194 .................................................... Section 30.13: Case insensitive switch 194 ..................................................................................................................... Section 30.14: Replacing parts of Strings 195 ................................................................................................................ Section 30.15: Getting the length of a String 196 .......................................................................................................... Section 30.16: Getting the nth character in a String 196 .............................................................................................. Section 30.17: Counting occurrences of a substring or character in a string 196 ..................................................... Chapter 31: StringBuer 198 ....................................................................................................................................... Section 31.1: String Buer class 198 ................................................................................................................................ Chapter 32: StringBuilder 199 ..................................................................................................................................... Section 32.1: Comparing StringBuer, StringBuilder, Formatter and StringJoiner 199 ............................................ Section 32.2: Repeat a String n times 200 ..................................................................................................................... Chapter 33: String Tokenizer 201 .............................................................................................................................. Section 33.1: StringTokenizer Split by space 201 ........................................................................................................... Section 33.2: StringTokenizer Split by comma ',' 201 .................................................................................................... Chapter 34: Splitting a string into fixed length parts 202 ........................................................................... Section 34.1: Break a string up into substrings all of a known length 202 ................................................................. Section 34.2: Break a string up into substrings all of variable length 202 ................................................................. Chapter 35: BigInteger 203 ........................................................................................................................................... Section 35.1: Initialization 203 .......................................................................................................................................... Section 35.2: BigInteger Mathematical Operations Examples 204 ............................................................................. Section 35.3: Comparing BigIntegers 206 ...................................................................................................................... Section 35.4: Binary Logic Operations on BigInteger 207 ............................................................................................ Section 35.5: Generating random BigIntegers 208 ....................................................................................................... Chapter 36: Console I/O 210 ........................................................................................................................................ Section 36.1: Reading user input from the console 210 ................................................................................................ Section 36.2: Aligning strings in console 211 ................................................................................................................. Section 36.3: Implementing Basic Command-Line Behavior 212 ................................................................................ Chapter 37: BigDecimal 214 ......................................................................................................................................... Section 37.1: Comparing BigDecimals 214 ..................................................................................................................... Section 37.2: Using BigDecimal instead of float 214 .................................................................................................... Section 37.3: BigDecimal.valueOf() 215 .........................................................................................................................
📄 Page
7
Section 37.4: Mathematical operations with BigDecimal 215 ...................................................................................... Section 37.5: Initialization of BigDecimals with value zero, one or ten 218 ................................................................ Section 37.6: BigDecimal objects are immutable 218 .................................................................................................. Chapter 38: NumberFormat 220 ................................................................................................................................ Section 38.1: NumberFormat 220 .................................................................................................................................... Chapter 39: Bit Manipulation 221 .............................................................................................................................. Section 39.1: Checking, setting, clearing, and toggling individual bits. Using long as bit mask 221 ........................ Section 39.2: java.util.BitSet class 221 ............................................................................................................................ Section 39.3: Checking if a number is a power of 2 222 .............................................................................................. Section 39.4: Signed vs unsigned shift 224 .................................................................................................................... Section 39.5: Expressing the power of 2 224 ................................................................................................................. Section 39.6: Packing / unpacking values as bit fragments 225 ................................................................................ Chapter 40: Arrays 226 .................................................................................................................................................. Section 40.1: Creating and Initializing Arrays 226 ......................................................................................................... Section 40.2: Creating a List from an Array 232 ........................................................................................................... Section 40.3: Creating an Array from a Collection 234 ................................................................................................ Section 40.4: Multidimensional and Jagged Arrays 234 .............................................................................................. Section 40.5: ArrayIndexOutOfBoundsException 236 .................................................................................................. Section 40.6: Array Covariance 237 ............................................................................................................................... Section 40.7: Arrays to Stream 238 ................................................................................................................................ Section 40.8: Iterating over arrays 238 .......................................................................................................................... Section 40.9: Arrays to a String 240 ............................................................................................................................... Section 40.10: Sorting arrays 241 ................................................................................................................................... Section 40.11: Getting the Length of an Array 243 ........................................................................................................ Section 40.12: Finding an element in an array 243 ....................................................................................................... Section 40.13: How do you change the size of an array? 244 ..................................................................................... Section 40.14: Converting arrays between primitives and boxed types 245 ............................................................. Section 40.15: Remove an element from an array 246 ................................................................................................ Section 40.16: Comparing arrays for equality 247 ........................................................................................................ Section 40.17: Copying arrays 247 .................................................................................................................................. Section 40.18: Casting Arrays 248 ................................................................................................................................... Chapter 41: Streams 250 ............................................................................................................................................... Section 41.1: Using Streams 250 ...................................................................................................................................... Section 41.2: Consuming Streams 252 ............................................................................................................................ Section 41.3: Creating a Frequency Map 254 ................................................................................................................ Section 41.4: Infinite Streams 254 ................................................................................................................................... Section 41.5: Collect Elements of a Stream into a Collection 255 ................................................................................ Section 41.6: Using Streams to Implement Mathematical Functions 258 ................................................................... Section 41.7: Flatten Streams with flatMap() 258 .......................................................................................................... Section 41.8: Parallel Stream 259 .................................................................................................................................... Section 41.9: Creating a Stream 260 ............................................................................................................................... Section 41.10: Finding Statistics about Numerical Streams 261 ................................................................................... Section 41.11: Converting an iterator to a stream 261 ................................................................................................... Section 41.12: Using IntStream to iterate over indexes 261 .......................................................................................... Section 41.13: Concatenate Streams 262 ........................................................................................................................ Section 41.14: Reduction with Streams 262 .................................................................................................................... Section 41.15: Using Streams of Map.Entry to Preserve Initial Values after Mapping 265 ........................................ Section 41.16: IntStream to String 265 ............................................................................................................................. Section 41.17: Finding the First Element that Matches a Predicate 265 ...................................................................... Section 41.18: Using Streams and Method References to Write Self-Documenting Processes 266 ........................
📄 Page
8
Section 41.19: Converting a Stream of Optional to a Stream of Values 267 .............................................................. Section 41.20: Get a Slice of a Stream 267 ..................................................................................................................... Section 41.21: Create a Map based on a Stream 267 .................................................................................................... Section 41.22: Joining a stream to a single String 268 ................................................................................................. Section 41.23: Sort Using Stream 269 ............................................................................................................................. Section 41.24: Streams of Primitives 270 ........................................................................................................................ Section 41.25: Stream operations categories 270 ......................................................................................................... Section 41.26: Collect Results of a Stream into an Array 271 ...................................................................................... Section 41.27: Generating random Strings using Streams 271 .................................................................................... Chapter 42: InputStreams and OutputStreams 273 ....................................................................................... Section 42.1: Closing Streams 273 .................................................................................................................................. Section 42.2: Reading InputStream into a String 273 ................................................................................................... Section 42.3: Wrapping Input/Output Streams 274 ..................................................................................................... Section 42.4: DataInputStream Example 275 ................................................................................................................ Section 42.5: Writing bytes to an OutputStream 275 ................................................................................................... Section 42.6: Copying Input Stream to Output Stream 275 ......................................................................................... Chapter 43: Readers and Writers 277 .................................................................................................................... Section 43.1: BueredReader 277 ................................................................................................................................... Section 43.2: StringWriter Example 278 ......................................................................................................................... Chapter 44: Preferences 279 ...................................................................................................................................... Section 44.1: Using preferences 279 ............................................................................................................................... Section 44.2: Adding event listeners 279 ....................................................................................................................... Section 44.3: Getting sub-nodes of Preferences 280 .................................................................................................... Section 44.4: Coordinating preferences access across multiple application instances 281 .................................... Section 44.5: Exporting preferences 281 ....................................................................................................................... Section 44.6: Importing preferences 282 ....................................................................................................................... Section 44.7: Removing event listeners 283 .................................................................................................................. Section 44.8: Getting preferences values 284 ............................................................................................................... Section 44.9: Setting preferences values 284 ................................................................................................................ Chapter 45: Collections 285 ......................................................................................................................................... Section 45.1: Removing items from a List within a loop 285 ........................................................................................ Section 45.2: Constructing collections from existing data 287 .................................................................................... Section 45.3: Declaring an ArrayList and adding objects 289 ..................................................................................... Section 45.4: Iterating over Collections 289 ................................................................................................................... Section 45.5: Immutable Empty Collections 291 ........................................................................................................... Section 45.6: Sub Collections 291 ................................................................................................................................... Section 45.7: Unmodifiable Collection 292 ..................................................................................................................... Section 45.8: Pitfall: concurrent modification exceptions 293 ..................................................................................... Section 45.9: Removing matching items from Lists using Iterator 293 ...................................................................... Section 45.10: Join lists 294 ............................................................................................................................................. Section 45.11: Creating your own Iterable structure for use with Iterator or for-each loop 294 .............................. Section 45.12: Collections and Primitive Values 296 ..................................................................................................... Chapter 46: Queues and Deques 298 ...................................................................................................................... Section 46.1: The usage of the PriorityQueue 298 ......................................................................................................... Section 46.2: Deque 298 .................................................................................................................................................. Section 46.3: Stacks 299 .................................................................................................................................................. Section 46.4: BlockingQueue 300 .................................................................................................................................... Section 46.5: LinkedList as a FIFO Queue 301 ............................................................................................................... Section 46.6: Queue Interface 302 .................................................................................................................................. Chapter 47: Collection Factory Methods 303 .....................................................................................................
📄 Page
9
Section 47.1: List<E> Factory Method Examples 303 .................................................................................................... Section 47.2: Set<E> Factory Method Examples 303 .................................................................................................... Section 47.3: Map<K, V> Factory Method Examples 303 ............................................................................................. Chapter 48: Alternative Collections 304 ................................................................................................................ Section 48.1: Multimap in Guava, Apache and Eclipse Collections 304 ....................................................................... Section 48.2: Apache HashBag, Guava HashMultiset and Eclipse HashBag 306 ...................................................... Section 48.3: Compare operation with collections - Create collections 308 .............................................................. Chapter 49: Concurrent Collections 313 ............................................................................................................... Section 49.1: Thread-safe Collections 313 ..................................................................................................................... Section 49.2: Insertion into ConcurrentHashMap 313 .................................................................................................. Section 49.3: Concurrent Collections 314 ....................................................................................................................... Chapter 50: Choosing Collections 316 .................................................................................................................... Section 50.1: Java Collections Flowchart 316 ................................................................................................................ Chapter 51: super keyword 317 .................................................................................................................................. Section 51.1: Super keyword use with examples 317 ..................................................................................................... Chapter 52: Serialization 320 ...................................................................................................................................... Section 52.1: Basic Serialization in Java 320 .................................................................................................................. Section 52.2: Custom Serialization 321 .......................................................................................................................... Section 52.3: Versioning and serialVersionUID 324 ...................................................................................................... Section 52.4: Serialization with Gson 325 ....................................................................................................................... Section 52.5: Custom JSON Deserialization with Jackson 326 ................................................................................... Chapter 53: Enums 329 ................................................................................................................................................... Section 53.1: Declaring and using a basic enum 329 .................................................................................................... Section 53.2: Enums with constructors 332 ................................................................................................................... Section 53.3: Enums with Abstract Methods 333 ........................................................................................................... Section 53.4: Implements Interface 334 ......................................................................................................................... Section 53.5: Implement Singleton pattern with a single-element enum 335 ............................................................ Section 53.6: Using methods and static blocks 336 ...................................................................................................... Section 53.7: Zero instance enum 336 ........................................................................................................................... Section 53.8: Enum as a bounded type parameter 337 ............................................................................................... Section 53.9: Documenting enums 337 .......................................................................................................................... Section 53.10: Enum constant specific body 338 ........................................................................................................... Section 53.11: Getting the values of an enum 339 ......................................................................................................... Section 53.12: Enum Polymorphism Pattern 340 ........................................................................................................... Section 53.13: Compare and Contains for Enum values 341 ........................................................................................ Section 53.14: Get enum constant by name 341 ........................................................................................................... Section 53.15: Enum with properties (fields) 342 ........................................................................................................... Section 53.16: Convert enum to String 343 .................................................................................................................... Section 53.17: Enums with static fields 343 ..................................................................................................................... Chapter 54: Enum Map 345 .......................................................................................................................................... Section 54.1: Enum Map Book Example 345 .................................................................................................................. Chapter 55: EnumSet class 346 .................................................................................................................................. Section 55.1: Enum Set Example 346 .............................................................................................................................. Chapter 56: Enum starting with number 347 ...................................................................................................... Section 56.1: Enum with name at beginning 347 ........................................................................................................... Chapter 57: Lists 348 ....................................................................................................................................................... Section 57.1: Sorting a generic list 348 ........................................................................................................................... Section 57.2: Convert a list of integers to a list of strings 349 ..................................................................................... Section 57.3: Classes implementing List - Pros and Cons 349 .....................................................................................
📄 Page
10
Section 57.4: Finding common elements between 2 lists 352 ..................................................................................... Section 57.5: In-place replacement of a List element 352 ........................................................................................... Section 57.6: Making a list unmodifiable 353 ................................................................................................................ Section 57.7: Moving objects around in the list 353 ...................................................................................................... Section 57.8: Creating, Adding and Removing element from an ArrayList 354 ........................................................ Section 57.9: Creating a List 354 ..................................................................................................................................... Section 57.10: Positional Access Operations 355 ........................................................................................................... Section 57.11: Iterating over elements in a list 357 ........................................................................................................ Section 57.12: Removing elements from list B that are present in the list A 357 ....................................................... Chapter 58: Sets 359 ........................................................................................................................................................ Section 58.1: Initialization 359 .......................................................................................................................................... Section 58.2: Basics of Set 359 ........................................................................................................................................ Section 58.3: Types and Usage of Sets 360 ................................................................................................................... Section 58.4: Create a list from an existing Set 361 ..................................................................................................... Section 58.5: Eliminating duplicates using Set 361 ....................................................................................................... Section 58.6: Declaring a HashSet with values 362 ...................................................................................................... Chapter 59: List vs Set 363 ........................................................................................................................................... Section 59.1: List vs Set 363 ............................................................................................................................................. Chapter 60: Maps 364 ..................................................................................................................................................... Section 60.1: Iterating Map Entries Eciently 364 ......................................................................................................... Section 60.2: Usage of HashMap 366 ............................................................................................................................ Section 60.3: Using Default Methods of Map from Java 8 367 ................................................................................... Section 60.4: Iterating through the contents of a Map 369 ......................................................................................... Section 60.5: Merging, combine and composing Maps 370 ........................................................................................ Section 60.6: Add multiple items 371 .............................................................................................................................. Section 60.7: Creating and Initializing Maps 373 ........................................................................................................... Section 60.8: Check if key exists 374 .............................................................................................................................. Section 60.9: Add an element 374 .................................................................................................................................. Section 60.10: Clear the map 375 .................................................................................................................................... Section 60.11: Use custom object as key 375 ................................................................................................................. Chapter 61: LinkedHashMap 377 ................................................................................................................................ Section 61.1: Java LinkedHashMap class 377 ................................................................................................................ Chapter 62: TreeMap and TreeSet 378 .................................................................................................................. Section 62.1: TreeMap of a simple Java type 378 ........................................................................................................ Section 62.2: TreeSet of a simple Java Type 378 ......................................................................................................... Section 62.3: TreeMap/TreeSet of a custom Java type 379 ....................................................................................... Section 62.4: TreeMap and TreeSet Thread Safety 380 .............................................................................................. Chapter 63: SortedMap 382 ......................................................................................................................................... Section 63.1: Introduction to sorted Map 382 ................................................................................................................ Chapter 64: WeakHashMap 383 ................................................................................................................................ Section 64.1: Concepts of WeakHashmap 383 .............................................................................................................. Chapter 65: Hashtable 384 ........................................................................................................................................... Section 65.1: Hashtable 384 ............................................................................................................................................. Chapter 66: Optional 385 ............................................................................................................................................... Section 66.1: Map 385 ....................................................................................................................................................... Section 66.2: Return default value if Optional is empty 386 ........................................................................................ Section 66.3: Throw an exception, if there is no value 386 .......................................................................................... Section 66.4: Lazily provide a default value using a Supplier 386 .............................................................................. Section 66.5: Filter 387 .....................................................................................................................................................
📄 Page
11
Section 66.6: Using Optional containers for primitive number types 387 .................................................................. Section 66.7: Run code only if there is a value present 388 ......................................................................................... Section 66.8: FlatMap 388 ................................................................................................................................................ Chapter 67: Object References 389 ......................................................................................................................... Section 67.1: Object References as method parameters 389 ...................................................................................... Chapter 68: Exceptions and exception handling 392 ...................................................................................... Section 68.1: Catching an exception with try-catch 392 ............................................................................................... Section 68.2: The try-with-resources statement 393 .................................................................................................... Section 68.3: Custom Exceptions 396 ............................................................................................................................. Section 68.4: Handling InterruptedException 398 ......................................................................................................... Section 68.5: Return statements in try catch block 399 ............................................................................................... Section 68.6: Introduction 400 ......................................................................................................................................... Section 68.7: The Java Exception Hierarchy - Unchecked and Checked Exceptions 401 ........................................ Section 68.8: Creating and reading stacktraces 404 .................................................................................................... Section 68.9: Throwing an exception 407 ...................................................................................................................... Section 68.10: Advanced features of Exceptions 409 ................................................................................................... Section 68.11: The try-finally and try-catch-finally statements 410 ............................................................................ Section 68.12: The 'throws' clause in a method declaration 412 ................................................................................. Chapter 69: Calendar and its Subclasses 414 ..................................................................................................... Section 69.1: Creating Calendar objects 414 ................................................................................................................. Section 69.2: Increasing / Decreasing calendar fields 414 .......................................................................................... Section 69.3: Subtracting calendars 414 ........................................................................................................................ Section 69.4: Finding AM/PM 414 ................................................................................................................................... Chapter 70: Using the static keyword 416 ........................................................................................................... Section 70.1: Reference to non-static member from static context 416 .................................................................... Section 70.2: Using static to declare constants 416 ..................................................................................................... Chapter 71: Properties Class 418 ............................................................................................................................... Section 71.1: Loading properties 418 ............................................................................................................................... Section 71.2: Saving Properties as XML 418 ................................................................................................................... Section 71.3: Property files caveat: trailing whitespace 419 ......................................................................................... Chapter 72: Lambda Expressions 422 ..................................................................................................................... Section 72.1: Introduction to Java lambdas 422 ........................................................................................................... Section 72.2: Using Lambda Expressions to Sort a Collection 425 ............................................................................. Section 72.3: Method References 426 ............................................................................................................................ Section 72.4: Implementing multiple interfaces 428 ..................................................................................................... Section 72.5: Lambda - Listener Example 428 .............................................................................................................. Section 72.6: Java Closures with lambda expressions 429 .......................................................................................... Section 72.7: Lambdas and memory utilization 430 ..................................................................................................... Section 72.8: Using lambda expression with your own functional interface 431 ...................................................... Section 72.9: Traditional style to Lambda style 431 ..................................................................................................... Section 72.10: `return` only returns from the lambda, not the outer method 432 ..................................................... Section 72.11: Lambdas and Execute-around Pattern 434 ........................................................................................... Section 72.12: Using lambda expressions & predicates to get a certain value(s) from a list 434 ........................... Chapter 73: Basic Control Structures 436 ............................................................................................................. Section 73.1: Switch statement 436 ................................................................................................................................. Section 73.2: do...while Loop 437 ..................................................................................................................................... Section 73.3: For Each 438 ............................................................................................................................................... Section 73.4: Continue Statement in Java 439 .............................................................................................................. Section 73.5: If / Else If / Else Control 439 .....................................................................................................................
📄 Page
12
Section 73.6: For Loops 439 ............................................................................................................................................. Section 73.7: Ternary Operator 440 ............................................................................................................................... Section 73.8: Try ... Catch ... Finally 441 ........................................................................................................................... Section 73.9: Break 441 .................................................................................................................................................... Section 73.10: While Loops 442 ....................................................................................................................................... Section 73.11: If / Else 442 ................................................................................................................................................ Section 73.12: Nested break / continue 442 .................................................................................................................. Chapter 74: BueredWriter 444 ............................................................................................................................... Section 74.1: Write a line of text to File 444 .................................................................................................................... Chapter 75: New File I/O 445 ...................................................................................................................................... Section 75.1: Creating paths 445 ..................................................................................................................................... Section 75.2: Manipulating paths 445 ............................................................................................................................. Section 75.3: Retrieving information about a path 445 ................................................................................................ Section 75.4: Retrieving information using the filesystem 446 .................................................................................... Section 75.5: Reading files 447 ........................................................................................................................................ Section 75.6: Writing files 447 .......................................................................................................................................... Chapter 76: File I/O 448 ................................................................................................................................................. Section 76.1: Migrating from java.io.File to Java 7 NIO (java.nio.file.Path) 448 .......................................................... Section 76.2: Reading an image from a file 450 ........................................................................................................... Section 76.3: File Read/Write Using FileInputStream/FileOutputStream 450 ........................................................... Section 76.4: Reading all bytes to a byte[] 451 ............................................................................................................ Section 76.5: Copying a file using Channel 452 ............................................................................................................. Section 76.6: Writing a byte[] to a file 452 .................................................................................................................... Section 76.7: Stream vs Writer/Reader API 453 ............................................................................................................ Section 76.8: Reading a file with a Scanner 454 ........................................................................................................... Section 76.9: Copying a file using InputStream and OutputStream 455 .................................................................... Section 76.10: Reading from a binary file 455 ............................................................................................................... Section 76.11: Reading a file using Channel and Buer 455 ......................................................................................... Section 76.12: Adding Directories 456 ............................................................................................................................. Section 76.13: Blocking or redirecting standard output / error 457 ............................................................................ Section 76.14: Reading a whole file at once 458 ............................................................................................................ Section 76.15: Locking 458 ............................................................................................................................................... Section 76.16: Reading a file using BueredInputStream 458 ..................................................................................... Section 76.17: Iterate over a directory printing subdirectories in it 459 ...................................................................... Section 76.18: Writing a file using Channel and Buer 459 .......................................................................................... Section 76.19: Writing a file using PrintStream 460 ....................................................................................................... Section 76.20: Iterating over a directory and filter by file extension 460 ................................................................... Section 76.21: Accessing the contents of a ZIP file 461 ................................................................................................ Chapter 77: Scanner 462 ............................................................................................................................................... Section 77.1: General Pattern that does most commonly asked about tasks 462 .................................................... Section 77.2: Using custom delimiters 464 .................................................................................................................... Section 77.3: Reading system input using Scanner 464 ............................................................................................... Section 77.4: Reading file input using Scanner 464 ...................................................................................................... Section 77.5: Read the entire input as a String using Scanner 465 ............................................................................. Section 77.6: Carefully Closing a Scanner 465 .............................................................................................................. Section 77.7: Read an int from the command line 466 ................................................................................................ Chapter 78: Interfaces 467 ........................................................................................................................................... Section 78.1: Implementing multiple interfaces 467 ...................................................................................................... Section 78.2: Declaring and Implementing an Interface 468 ...................................................................................... Section 78.3: Extending an interface 468 .......................................................................................................................
📄 Page
13
Section 78.4: Usefulness of interfaces 469 .................................................................................................................... Section 78.5: Default methods 471 ................................................................................................................................. Section 78.6: Modifiers in Interfaces 473 ........................................................................................................................ Section 78.7: Using Interfaces with Generics 473 .......................................................................................................... Section 78.8: Strengthen bounded type parameters 476 ............................................................................................ Section 78.9: Implementing interfaces in an abstract class 476 ................................................................................. Chapter 79: Regular Expressions 478 ..................................................................................................................... Section 79.1: Using capture groups 478 ......................................................................................................................... Section 79.2: Using regex with custom behaviour by compiling the Pattern with flags 479 .................................... Section 79.3: Escape Characters 479 ............................................................................................................................. Section 79.4: Not matching a given string 480 .............................................................................................................. Section 79.5: Matching with a regex literal 480 ............................................................................................................. Section 79.6: Matching a backslash 480 ........................................................................................................................ Chapter 80: Comparable and Comparator 482 ................................................................................................ Section 80.1: Sorting a List using Comparable<T> or a Comparator<T> 482 ............................................................ Section 80.2: The compareTo and compare Methods 485 ......................................................................................... Section 80.3: Natural (comparable) vs explicit (comparator) sorting 486 ................................................................ Section 80.4: Creating a Comparator using comparing method 487 ........................................................................ Section 80.5: Sorting Map entries 487 ............................................................................................................................ Chapter 81: Java Floating Point Operations 489 .............................................................................................. Section 81.1: Comparing floating point values 489 ........................................................................................................ Section 81.2: OverFlow and UnderFlow 491 .................................................................................................................. Section 81.3: Formatting the floating point values 492 ................................................................................................ Section 81.4: Strict Adherence to the IEEE Specification 492 ....................................................................................... Chapter 82: Currency and Money 494 .................................................................................................................... Section 82.1: Add custom currency 494 ......................................................................................................................... Chapter 83: Object Cloning 495 .................................................................................................................................. Section 83.1: Cloning performing a deep copy 495 ...................................................................................................... Section 83.2: Cloning using a copy factory 496 ............................................................................................................ Section 83.3: Cloning using a copy constructor 496 ..................................................................................................... Section 83.4: Cloning by implementing Clonable interface 496 .................................................................................. Section 83.5: Cloning performing a shallow copy 497 ................................................................................................. Chapter 84: Recursion 499 ........................................................................................................................................... Section 84.1: The basic idea of recursion 499 ................................................................................................................ Section 84.2: Deep recursion is problematic in Java 499 ............................................................................................ Section 84.3: Types of Recursion 501 ............................................................................................................................ Section 84.4: Computing the Nth Fibonacci Number 501 ............................................................................................ Section 84.5: StackOverflowError & recursion to loop 502 .......................................................................................... Section 84.6: Computing the Nth power of a number 504 ........................................................................................... Section 84.7: Traversing a Tree data structure with recursion 504 ............................................................................ Section 84.8: Reverse a string using Recursion 505 ..................................................................................................... Section 84.9: Computing the sum of integers from 1 to N 505 .................................................................................... Chapter 85: Converting to and from Strings 506 ............................................................................................. Section 85.1: Converting String to other datatypes 506 ............................................................................................... Section 85.2: Conversion to / from bytes 507 ............................................................................................................... Section 85.3: Base64 Encoding / Decoding 507 ........................................................................................................... Section 85.4: Converting other datatypes to String 508 .............................................................................................. Section 85.5: Getting a `String` from an `InputStream` 509 .......................................................................................... Chapter 86: Random Number Generation 510 ...................................................................................................
📄 Page
14
Section 86.1: Pseudo Random Numbers 510 ................................................................................................................. Section 86.2: Pseudo Random Numbers in Specific Range 510 ................................................................................. Section 86.3: Generating cryptographically secure pseudorandom numbers 511 ................................................... Section 86.4: Generating Random Numbers with a Specified Seed 511 .................................................................... Section 86.5: Select random numbers without duplicates 512 .................................................................................... Section 86.6: Generating Random number using apache-common lang3 513 ........................................................ Chapter 87: Singletons 514 .......................................................................................................................................... Section 87.1: Enum Singleton 514 .................................................................................................................................... Section 87.2: Singleton without use of Enum (eager initialization) 514 ...................................................................... Section 87.3: Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation 515 ............ Section 87.4: Thread safe Singleton with double checked locking 515 ...................................................................... Section 87.5: Extending singleton (singleton inheritance) 516 .................................................................................... Chapter 88: Autoboxing 519 ........................................................................................................................................ Section 88.1: Using int and Integer interchangeably 519 ............................................................................................. Section 88.2: Auto-unboxing may lead to NullPointerException 520 .......................................................................... Section 88.3: Using Boolean in if statement 520 ........................................................................................................... Section 88.4: Dierent Cases When Integer and int can be used interchangeably 520 .......................................... Section 88.5: Memory and Computational Overhead of Autoboxing 522 ................................................................. Chapter 89: 2D Graphics in Java 523 ...................................................................................................................... Section 89.1: Example 1: Draw and Fill a Rectangle Using Java 523 ........................................................................... Section 89.2: Example 2: Drawing and Filling Oval 525 ................................................................................................ Chapter 90: JAXB 526 ...................................................................................................................................................... Section 90.1: Reading an XML file (unmarshalling) 526 ............................................................................................... Section 90.2: Writing an XML file (marshalling an object) 526 .................................................................................... Section 90.3: Manual field/property XML mapping configuration 527 ...................................................................... Section 90.4: Binding an XML namespace to a serializable Java class 528 .............................................................. Section 90.5: Using XmlAdapter to generate desired xml format 528 ....................................................................... Section 90.6: Using XmlAdapter to trim string 530 ....................................................................................................... Section 90.7: Automatic field/property XML mapping configuration (@XmlAccessorType) 530 ........................... Section 90.8: Specifying a XmlAdapter instance to (re)use existing data 532 .......................................................... Chapter 91: Class - Java Reflection 535 ................................................................................................................. Section 91.1: getClass() method of Object class 535 ..................................................................................................... Chapter 92: Networking 536 ........................................................................................................................................ Section 92.1: Basic Client and Server Communication using a Socket 536 ................................................................ Section 92.2: Basic Client/Server Communication using UDP (Datagram) 538 ....................................................... Section 92.3: Loading TrustStore and KeyStore from InputStream 539 .................................................................... Section 92.4: Socket example - reading a web page using a simple socket 540 ...................................................... Section 92.5: Temporarily disable SSL verification (for testing purposes) 541 ......................................................... Section 92.6: Downloading a file using Channel 541 .................................................................................................... Section 92.7: Multicasting 542 ......................................................................................................................................... Chapter 93: NIO - Networking 545 ............................................................................................................................ Section 93.1: Using Selector to wait for events (example with OP_CONNECT) 545 .................................................. Chapter 94: HttpURLConnection 547 ...................................................................................................................... Section 94.1: Get response body from a URL as a String 547 ..................................................................................... Section 94.2: POST data 548 ........................................................................................................................................... Section 94.3: Delete resource 548 .................................................................................................................................. Section 94.4: Check if resource exists 549 ..................................................................................................................... Chapter 95: JAX-WS 551 ................................................................................................................................................ Section 95.1: Basic Authentication 551 ...........................................................................................................................
📄 Page
15
Chapter 96: Nashorn JavaScript engine 552 ....................................................................................................... Section 96.1: Execute JavaScript file 552 ....................................................................................................................... Section 96.2: Intercept script output 552 ....................................................................................................................... Section 96.3: Hello Nashorn 553 ..................................................................................................................................... Section 96.4: Evaluate Arithmetic Strings 553 ............................................................................................................... Section 96.5: Set global variables 553 ............................................................................................................................ Section 96.6: Set and get global variables 554 ............................................................................................................. Section 96.7: Usage of Java objects in JavaScript in Nashorn 554 ............................................................................ Section 96.8: Implementing an interface from script 555 ............................................................................................ Chapter 97: Java Native Interface 556 .................................................................................................................. Section 97.1: Calling C++ methods from Java 556 ........................................................................................................ Section 97.2: Calling Java methods from C++ (callback) 557 ..................................................................................... Section 97.3: Loading native libraries 559 ..................................................................................................................... Chapter 98: Functional Interfaces 561 ................................................................................................................... Section 98.1: List of standard Java Runtime Library functional interfaces by signature 561 .................................. Chapter 99: Fluent Interface 563 .............................................................................................................................. Section 99.1: Fluent programming style 563 ................................................................................................................. Section 99.2: Truth - Fluent Testing Framework 564 .................................................................................................... Chapter 100: Dequeue Interface 565 ....................................................................................................................... Section 100.1: Adding Elements to Deque 565 ............................................................................................................... Section 100.2: Removing Elements from Deque 565 .................................................................................................... Section 100.3: Retrieving Element without Removing 565 ........................................................................................... Section 100.4: Iterating through Deque 565 .................................................................................................................. Chapter 101: Remote Method Invocation (RMI) 567 ......................................................................................... Section 101.1: Callback: invoking methods on a "client" 567 ......................................................................................... Section 101.2: Simple RMI example with Client and Server implementation 571 ....................................................... Section 101.3: Client-Server: invoking methods in one JVM from another 573 .......................................................... Chapter 102: Iterator and Iterable 576 .................................................................................................................. Section 102.1: Removing elements using an iterator 576 ............................................................................................. Section 102.2: Creating your own Iterable 576 .............................................................................................................. Section 102.3: Using Iterable in for loop 577 .................................................................................................................. Section 102.4: Using the raw iterator 578 ...................................................................................................................... Chapter 103: Reflection API 579 ................................................................................................................................. Section 103.1: Dynamic Proxies 579 ................................................................................................................................ Section 103.2: Introduction 580 ....................................................................................................................................... Section 103.3: Evil Java hacks with Reflection 581 ....................................................................................................... Section 103.4: Misuse of Reflection API to change private and final variables 583 ................................................... Section 103.5: Getting and Setting fields 584 ................................................................................................................. Section 103.6: Call constructor 585 ................................................................................................................................. Section 103.7: Call constructor of nested class 586 ...................................................................................................... Section 103.8: Invoking a method 586 ............................................................................................................................ Section 103.9: Get Class given its (fully qualified) name 587 ....................................................................................... Section 103.10: Getting the Constants of an Enumeration 587 .................................................................................... Section 103.11: Call overloaded constructors using reflection 588 ............................................................................... Chapter 104: ByteBuer 590 ....................................................................................................................................... Section 104.1: Basic Usage - Using DirectByteBuer 590 ............................................................................................ Section 104.2: Basic Usage - Creating a ByteBuer 590 ............................................................................................. Section 104.3: Basic Usage - Write Data to the Buer 591 .......................................................................................... Chapter 105: Applets 592 ...............................................................................................................................................
📄 Page
16
Section 105.1: Minimal Applet 592 ................................................................................................................................... Section 105.2: Creating a GUI 593 ................................................................................................................................... Section 105.3: Open links from within the applet 593 ................................................................................................... Section 105.4: Loading images, audio and other resources 594 ................................................................................. Chapter 106: Expressions 596 ...................................................................................................................................... Section 106.1: Operator Precedence 596 ........................................................................................................................ Section 106.2: Expression Basics 597 .............................................................................................................................. Section 106.3: Expression evaluation order 598 ............................................................................................................ Section 106.4: Constant Expressions 599 ....................................................................................................................... Chapter 107: JSON in Java 601 .................................................................................................................................. Section 107.1: Using Jackson Object Mapper 601 ......................................................................................................... Section 107.2: JSON To Object (Gson Library) 602 ....................................................................................................... Section 107.3: JSONObject.NULL 602 ............................................................................................................................. Section 107.4: JSON Builder - chaining methods 603 ................................................................................................... Section 107.5: Object To JSON (Gson Library) 603 ....................................................................................................... Section 107.6: JSON Iteration 603 ................................................................................................................................... Section 107.7: optXXX vs getXXX methods 604 ............................................................................................................. Section 107.8: Extract single element from JSON 604 .................................................................................................. Section 107.9: JsonArray to Java List (Gson Library) 604 ........................................................................................... Section 107.10: Encoding data as JSON 605 .................................................................................................................. Section 107.11: Decoding JSON data 605 ....................................................................................................................... Chapter 108: XML Parsing using the JAXP APIs 607 ......................................................................................... Section 108.1: Parsing a document using the StAX API 607 .......................................................................................... Section 108.2: Parsing and navigating a document using the DOM API 608 ............................................................. Chapter 109: XML XPath Evaluation 610 ................................................................................................................ Section 109.1: Parsing multiple XPath Expressions in a single XML 610 ...................................................................... Section 109.2: Parsing single XPath Expression multiple times in an XML 610 .......................................................... Section 109.3: Evaluating a NodeList in an XML document 611 .................................................................................. Chapter 110: XOM - XML Object Model 612 ........................................................................................................... Section 110.1: Reading a XML file 612 .............................................................................................................................. Section 110.2: Writing to a XML File 614 ......................................................................................................................... Chapter 111: Polymorphism 617 .................................................................................................................................. Section 111.1: Method Overriding 617 ............................................................................................................................... Section 111.2: Method Overloading 618 ........................................................................................................................... Section 111.3: Polymorphism and dierent types of overriding 619 ............................................................................ Section 111.4: Virtual functions 622 .................................................................................................................................. Section 111.5: Adding behaviour by adding classes without touching existing code 623 .......................................... Chapter 112: Encapsulation 625 .................................................................................................................................. Section 112.1: Encapsulation to maintain invariants 625 ............................................................................................... Section 112.2: Encapsulation to reduce coupling 626 .................................................................................................... Chapter 113: Java Agents 627 ...................................................................................................................................... Section 113.1: Modifying classes with agents 627 ........................................................................................................... Section 113.2: Adding an agent at runtime 627 ............................................................................................................. Section 113.3: Setting up a basic agent 628 .................................................................................................................... Chapter 114: Varargs (Variable Argument) 629 ................................................................................................ Section 114.1: Working with Varargs parameters 629 ................................................................................................... Section 114.2: Specifying a varargs parameter 629 ...................................................................................................... Chapter 115: Logging (java.util.logging) 630 ....................................................................................................... Section 115.1: Logging complex messages (eciently) 630 .........................................................................................
📄 Page
17
Section 115.2: Using the default logger 631 ................................................................................................................... Section 115.3: Logging levels 632 .................................................................................................................................... Chapter 116: log4j / log4j2 634 .................................................................................................................................. Section 116.1: Properties-File to log to DB 634 ............................................................................................................... Section 116.2: How to get Log4j 634 ................................................................................................................................ Section 116.3: Setting up property file 635 ...................................................................................................................... Section 116.4: Basic log4j2.xml configuration file 636 ................................................................................................... Section 116.5: How to use Log4j in Java code 636 ........................................................................................................ Section 116.6: Migrating from log4j 1.x to 2.x 637 ........................................................................................................... Section 116.7: Filter Logoutput by level (log4j 1.x) 638 ................................................................................................... Chapter 117: Oracle Ocial Code Standard 639 ............................................................................................... Section 117.1: Naming Conventions 639 .......................................................................................................................... Section 117.2: Class Structure 640 ................................................................................................................................... Section 117.3: Annotations 641 ......................................................................................................................................... Section 117.4: Import statements 641 ............................................................................................................................. Section 117.5: Braces 642 ................................................................................................................................................. Section 117.6: Redundant Parentheses 643 .................................................................................................................... Section 117.7: Modifiers 643 .............................................................................................................................................. Section 117.8: Indentation 644 .......................................................................................................................................... Section 117.9: Literals 644 ................................................................................................................................................. Section 117.10: Package declaration 644 ........................................................................................................................ Section 117.11: Lambda Expressions 644 ......................................................................................................................... Section 117.12: Java Source Files 645 .............................................................................................................................. Section 117.13: Wrapping statements 645 ....................................................................................................................... Section 117.14: Wrapping Method Declarations 646 ...................................................................................................... Section 117.15: Wrapping Expressions 646 ...................................................................................................................... Section 117.16: Whitespace 647 ........................................................................................................................................ Section 117.17: Special Characters 647 ............................................................................................................................ Section 117.18: Variable Declarations 648 ....................................................................................................................... Chapter 118: Character encoding 649 ..................................................................................................................... Section 118.1: Reading text from a file encoded in UTF-8 649 ..................................................................................... Section 118.2: Writing text to a file in UTF-8 649 ............................................................................................................ Section 118.3: Getting byte representation of a string in UTF-8 650 ........................................................................... Chapter 119: Apache Commons Lang 651 ............................................................................................................. Section 119.1: Implement equals() method 651 .............................................................................................................. Section 119.2: Implement hashCode() method 651 ....................................................................................................... Section 119.3: Implement toString() method 652 ........................................................................................................... Chapter 120: Localization and Internationalization 654 ................................................................................ Section 120.1: Locale 654 .................................................................................................................................................. Section 120.2: Automatically formatted Dates using "locale" 655 .............................................................................. Section 120.3: String Comparison 655 ............................................................................................................................ Chapter 121: Parallel programming with Fork/Join framework 656 ...................................................... Section 121.1: Fork/Join Tasks in Java 656 .................................................................................................................... Chapter 122: Non-Access Modifiers 658 ................................................................................................................. Section 122.1: final 658 ...................................................................................................................................................... Section 122.2: static 659 ................................................................................................................................................... Section 122.3: abstract 660 .............................................................................................................................................. Section 122.4: strictfp 661 ................................................................................................................................................ Section 122.5: volatile 661 ................................................................................................................................................
📄 Page
18
Section 122.6: synchronized 662 ..................................................................................................................................... Section 122.7: transient 663 ............................................................................................................................................. Chapter 123: Process 664 ............................................................................................................................................... Section 123.1: Pitfall: Runtime.exec, Process and ProcessBuilder don't understand shell syntax 664 ...................... Section 123.2: Simple example (Java version < 1.5) 666 ............................................................................................... Chapter 124: Java Native Access 667 ..................................................................................................................... Section 124.1: Introduction to JNA 667 ........................................................................................................................... Chapter 125: Modules 668 .............................................................................................................................................. Section 125.1: Defining a basic module 668 ................................................................................................................... Chapter 126: Concurrent Programming (Threads) 669 .................................................................................. Section 126.1: Callable and Future 669 ........................................................................................................................... Section 126.2: CountDownLatch 670 ............................................................................................................................... Section 126.3: Basic Multithreading 672 ......................................................................................................................... Section 126.4: Locks as Synchronisation aids 673 ......................................................................................................... Section 126.5: Semaphore 674 ........................................................................................................................................ Section 126.6: Synchronization 675 ................................................................................................................................. Section 126.7: Runnable Object 676 ................................................................................................................................ Section 126.8: Creating basic deadlocked system 677 ................................................................................................. Section 126.9: Creating a java.lang.Thread instance 679 ............................................................................................. Section 126.10: Atomic operations 680 ........................................................................................................................... Section 126.11: Exclusive write / Concurrent read access 681 ...................................................................................... Section 126.12: Producer-Consumer 682 ........................................................................................................................ Section 126.13: Visualizing read/write barriers while using synchronized / volatile 684 ........................................... Section 126.14: Get status of all threads started by your program excluding system threads 685 ........................ Section 126.15: Using ThreadLocal 686 ........................................................................................................................... Section 126.16: Multiple producer/consumer example with shared global queue 687 ............................................. Section 126.17: Add two `int` arrays using a Threadpool 688 ....................................................................................... Section 126.18: Pausing Execution 689 ............................................................................................................................ Section 126.19: Thread Interruption / Stopping Threads 690 ....................................................................................... Chapter 127: Executor, ExecutorService and Thread pools 693 ................................................................ Section 127.1: ThreadPoolExecutor 693 .......................................................................................................................... Section 127.2: Retrieving value from computation - Callable 694 ............................................................................... Section 127.3: submit() vs execute() exception handling dierences 695 .................................................................. Section 127.4: Handle Rejected Execution 697 .............................................................................................................. Section 127.5: Fire and Forget - Runnable Tasks 697 ................................................................................................... Section 127.6: Use cases for dierent types of concurrency constructs 698 ............................................................. Section 127.7: Wait for completion of all tasks in ExecutorService 699 ...................................................................... Section 127.8: Use cases for dierent types of ExecutorService 701 .......................................................................... Section 127.9: Scheduling tasks to run at a fixed time, after a delay or repeatedly 703 .......................................... Section 127.10: Using Thread Pools 704 ......................................................................................................................... Chapter 128: ThreadLocal 705 .................................................................................................................................... Section 128.1: Basic ThreadLocal usage 705 .................................................................................................................. Section 128.2: ThreadLocal Java 8 functional initialization 706 .................................................................................. Section 128.3: Multiple threads with one shared object 707 ........................................................................................ Chapter 129: Using ThreadPoolExecutor in MultiThreaded applications. 709 .................................... Section 129.1: Performing Asynchronous Tasks Where No Return Value Is Needed Using a Runnable Class Instance 709 .............................................................................................................................................................. Section 129.2: Performing Asynchronous Tasks Where a Return Value Is Needed Using a Callable Class Instance 710 .............................................................................................................................................................. Section 129.3: Defining Asynchronous Tasks Inline using Lambdas 713 ....................................................................
📄 Page
19
Chapter 130: Common Java Pitfalls 715 ................................................................................................................ Section 130.1: Pitfall: using == to compare primitive wrappers objects such as Integer 715 ..................................... Section 130.2: Pitfall: using == to compare strings 715 ................................................................................................. Section 130.3: Pitfall: forgetting to free resources 717 ................................................................................................. Section 130.4: Pitfall: testing a file before attempting to open it 718 .......................................................................... Section 130.5: Pitfall: thinking of variables as objects 719 ........................................................................................... Section 130.6: Pitfall: memory leaks 722 ........................................................................................................................ Section 130.7: Pitfall: Not understanding that String is an immutable class 723 ....................................................... Section 130.8: Pitfall: combining assignment and side-eects 724 ............................................................................. Chapter 131: Java Pitfalls - Exception usage 725 .............................................................................................. Section 131.1: Pitfall - Catching Throwable, Exception, Error or RuntimeException 725 ............................................ Section 131.2: Pitfall - Ignoring or squashing exceptions 726 ....................................................................................... Section 131.3: Pitfall - Throwing Throwable, Exception, Error or RuntimeException 727 ........................................... Section 131.4: Pitfall - Using exceptions for normal flowcontrol 728 ........................................................................... Section 131.5: Pitfall - Directly subclassing `Throwable` 729 ......................................................................................... Section 131.6: Pitfall - Catching InterruptedException 729 ............................................................................................ Section 131.7: Pitfall - Excessive or inappropriate stacktraces 731 .............................................................................. Chapter 132: Java Pitfalls - Language syntax 732 ........................................................................................... Section 132.1: Pitfall - Missing a ‘break’ in a 'switch' case 732 ...................................................................................... Section 132.2: Pitfall - Declaring classes with the same names as standard classes 732 ........................................ Section 132.3: Pitfall - Leaving out braces: the "dangling if" and "dangling else" problems 733 ............................. Section 132.4: Pitfall - Octal literals 735 .......................................................................................................................... Section 132.5: Pitfall - Using '==' to test a boolean 735 ................................................................................................. Section 132.6: Pitfall - Ignoring method visibility 736 .................................................................................................... Section 132.7: Pitfall: Using 'assert' for argument or user input validation 736 ......................................................... Section 132.8: Pitfall - Wildcard imports can make your code fragile 737 ................................................................. Section 132.9: Pitfall - Misplaced semicolons and missing braces 738 ....................................................................... Section 132.10: Pitfall - Overloading instead of overriding 739 .................................................................................... Section 132.11: Pitfall of Auto-Unboxing Null Objects into Primitives 740 .................................................................... Chapter 133: Java Pitfalls - Threads and Concurrency 741 ......................................................................... Section 133.1: Pitfall - Extending 'java.lang.Thread' 741 ................................................................................................ Section 133.2: Pitfall - Too many threads makes an application slower 742 ............................................................. Section 133.3: Pitfall: incorrect use of wait() / notify() 743 ........................................................................................... Section 133.4: Pitfall: Shared variables require proper synchronization 743 .............................................................. Section 133.5: Pitfall - Thread creation is relatively expensive 746 ............................................................................. Chapter 134: Java Pitfalls - Nulls and NullPointerException 749 ............................................................. Section 134.1: Pitfall - "Making good" unexpected nulls 749 ......................................................................................... Section 134.2: Pitfall - Using null to represent an empty array or collection 750 ...................................................... Section 134.3: Pitfall - Not checking if an I/O stream isn't even initialized when closing it 751 ............................... Section 134.4: Pitfall - Returning null instead of throwing an exception 751 .............................................................. Section 134.5: Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions 752 ................ Section 134.6: Pitfall - Using "Yoda notation" to avoid NullPointerException 753 ...................................................... Chapter 135: Java Pitfalls - Performance Issues 754 ...................................................................................... Section 135.1: Pitfall - String concatenation in a loop does not scale 754 .................................................................. Section 135.2: Pitfall - Using size() to test if a collection is empty is inecient 755 .................................................. Section 135.3: Pitfall - Interning strings so that you can use == is a bad idea 755 ..................................................... Section 135.4: Pitfall - Using 'new' to create primitive wrapper instances is inecient 757 ..................................... Section 135.5: Pitfall - Eciency concerns with regular expressions 757 ................................................................... Section 135.6: Pitfall - Small reads / writes on unbuered streams are inecient 760 ........................................... Section 135.7: Pitfall - Over-use of primitive wrapper types is inecient 762 ............................................................
📄 Page
20
Section 135.8: Pitfall - The overheads of creating log messages 763 ......................................................................... Section 135.9: Pitfall - Iterating a Map's keys can be inecient 764 ........................................................................... Section 135.10: Pitfall - Calling System.gc() is inecient 764 ....................................................................................... Section 135.11: Pitfall - Calling 'new String(String)' is inecient 765 ............................................................................ Chapter 136: ServiceLoader 766 ................................................................................................................................ Section 136.1: Simple ServiceLoader Example 766 ........................................................................................................ Section 136.2: Logger Service 767 ................................................................................................................................... Chapter 137: Classloaders 769 .................................................................................................................................... Section 137.1: Implementing a custom classLoader 769 ............................................................................................... Section 137.2: Loading an external .class file 769 .......................................................................................................... Section 137.3: Instantiating and using a classloader 770 ............................................................................................. Chapter 138: Creating Images Programmatically 772 ................................................................................... Section 138.1: Creating a simple image programmatically and displaying it 772 ..................................................... Section 138.2: Save an Image to disk 773 ...................................................................................................................... Section 138.3: Setting individual pixel's color in BueredImage 773 ........................................................................... Section 138.4: Specifying image rendering quality 774 ................................................................................................ Section 138.5: Creating an image with BueredImage class 776 ............................................................................... Section 138.6: Editing and re-using image with BueredImage 777 ........................................................................... Section 138.7: How to scale a BueredImage 778 ........................................................................................................ Chapter 139: Atomic Types 779 .................................................................................................................................. Section 139.1: Creating Atomic Types 779 ...................................................................................................................... Section 139.2: Motivation for Atomic Types 779 ............................................................................................................ Chapter 140: RSA Encryption 783 ............................................................................................................................. Section 140.1: An example using a hybrid cryptosystem consisting of OAEP and GCM 783 .................................... Chapter 141: Secure objects 788 ................................................................................................................................ Section 141.1: SealedObject (javax.crypto.SealedObject) 788 ...................................................................................... Section 141.2: SignedObject (java.security.SignedObject) 788 ..................................................................................... Chapter 142: Security & Cryptography 790 ......................................................................................................... Section 142.1: Compute Cryptographic Hashes 790 ...................................................................................................... Section 142.2: Encrypt and Decrypt Data with Public / Private Keys 790 .................................................................. Section 142.3: Generate Cryptographically Random Data 791 ................................................................................... Section 142.4: Generate Public / Private Key Pairs 791 ................................................................................................ Section 142.5: Compute and Verify Digital Signatures 792 .......................................................................................... Chapter 143: Security & Cryptography 793 ......................................................................................................... Section 143.1: The JCE 793 ............................................................................................................................................... Section 143.2: Keys and Key Management 793 ............................................................................................................ Section 143.3: Common Java vulnerabilities 793 .......................................................................................................... Section 143.4: Networking Concerns 793 ....................................................................................................................... Section 143.5: Randomness and You 793 ....................................................................................................................... Section 143.6: Hashing and Validation 793 .................................................................................................................... Chapter 144: SecurityManager 795 ......................................................................................................................... Section 144.1: Sandboxing classes loaded by a ClassLoader 795 ............................................................................... Section 144.2: Enabling the SecurityManager 796 ........................................................................................................ Section 144.3: Implementing policy deny rules 796 ...................................................................................................... Chapter 145: JNDI 804 .................................................................................................................................................... Section 145.1: RMI through JNDI 804 .............................................................................................................................. Chapter 146: sun.misc.Unsafe 808 ............................................................................................................................ Section 146.1: Instantiating sun.misc.Unsafe via reflection 808 .................................................................................... Section 146.2: Instantiating sun.misc.Unsafe via bootclasspath 808 ...........................................................................