JavaNotesForProfessionals (1).pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

DazzledEuclid1156

Uploaded by DazzledEuclid1156

Tags

Java programming software development programming languages

Full Transcript

Java Java Notes for Professionals ® Notes for Professionals 900+ pages...

Java Java Notes for Professionals ® Notes for Professionals 900+ pages of professional hints and tricks Disclaimer GoalKicker.com This is an unocial free book created for educational purposes and is not aliated with ocial Java® group(s) or company(s). Free Programming Books All trademarks and registered trademarks are the property of their respective owners 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 dierent 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: Literals...................................................................................................................................................... 35 Section 9.1: Using underscore to improve readability............................................................................................. 35 Section 9.2: Hexadecimal, Octal and Binary literals................................................................................................ 35 Section 9.3: Boolean literals....................................................................................................................................... 36 Section 9.4: String literals........................................................................................................................................... 36 Section 9.5: The Null literal......................................................................................................................................... 37 Section 9.6: Escape sequences in literals.................................................................................................................. 37 Section 9.7: Character literals.................................................................................................................................... 38 Section 9.8: Decimal Integer literals.......................................................................................................................... 38 Section 9.9: Floating-point literals............................................................................................................................. 39 Chapter 10: Primitive Data Types....................................................................................................................... 42 Section 10.1: The char primitive.................................................................................................................................. 42 Section 10.2: Primitive Types Cheatsheet................................................................................................................. 42 Section 10.3: The float primitive................................................................................................................................. 43 Section 10.4: The int primitive..................................................................................................................................... 44 Section 10.5: Converting Primitives............................................................................................................................ 45 Section 10.6: Memory consumption of primitives vs. boxed primitives.................................................................. 45 Section 10.7: The double primitive............................................................................................................................. 46 Section 10.8: The long primitive................................................................................................................................. 47 Section 10.9: The boolean primitive........................................................................................................................... 48 Section 10.10: The byte primitive................................................................................................................................ 48 Section 10.11: Negative value representation............................................................................................................ 49 Section 10.12: The short primitive............................................................................................................................... 50 Chapter 11: Strings...................................................................................................................................................... 51 Section 11.1: Comparing Strings.................................................................................................................................. 51 Section 11.2: Changing the case of characters within a String............................................................................... 53 Section 11.3: Finding a String Within Another String................................................................................................. 55 Section 11.4: String pool and heap storage............................................................................................................... 56 Section 11.5: Splitting Strings....................................................................................................................................... 57 Section 11.6: Joining Strings with a delimiter............................................................................................................ 59 Section 11.7: String concatenation and StringBuilders............................................................................................. 60 Section 11.8: Substrings............................................................................................................................................... 61 Section 11.9: Platform independent new line separator........................................................................................... 62 Section 11.10: Reversing Strings.................................................................................................................................. 62 Section 11.11: Adding toString() method for custom objects.................................................................................... 63 Section 11.12: Remove Whitespace from the Beginning and End of a String........................................................ 64 Section 11.13: Case insensitive switch......................................................................................................................... 64 Section 11.14: Replacing parts of Strings................................................................................................................... 65 Section 11.15: Getting the length of a String.............................................................................................................. 66 Section 11.16: Getting the nth character in a String.................................................................................................. 66 Section 11.17: Counting occurrences of a substring or character in a string......................................................... 66 Chapter 12: StringBuer......................................................................................................................................... 68 Section 12.1: String Buer class.................................................................................................................................. 68 Chapter 13: StringBuilder........................................................................................................................................ 69 Section 13.1: Comparing StringBuer, StringBuilder, Formatter and StringJoiner............................................... 69 Section 13.2: Repeat a String n times........................................................................................................................ 70 Chapter 14: String Tokenizer................................................................................................................................ 71 Section 14.1: StringTokenizer Split by space............................................................................................................. 71 Section 14.2: StringTokenizer Split by comma ','...................................................................................................... 71 Chapter 15: Splitting a string into fixed length parts............................................................................... 72 Section 15.1: Break a string up into substrings all of a known length.................................................................... 72 Section 15.2: Break a string up into substrings all of variable length.................................................................... 72 Chapter 16: Date Class............................................................................................................................................. 73 Section 16.1: Convert java.util.Date to java.sql.Date................................................................................................. 73 Section 16.2: A basic date output............................................................................................................................... 73 Section 16.3: Java 8 LocalDate and LocalDateTime objects.................................................................................. 74 Section 16.4: Creating a Specific Date....................................................................................................................... 75 Section 16.5: Converting Date to a certain String format....................................................................................... 75 Section 16.6: LocalTime............................................................................................................................................... 76 Section 16.7: Convert formatted string representation of date to Date object.................................................... 76 Section 16.8: Creating Date objects........................................................................................................................... 77 Section 16.9: Comparing Date objects...................................................................................................................... 77 Section 16.10: Converting String into Date................................................................................................................ 80 Section 16.11: Time Zones and java.util.Date............................................................................................................. 80 Chapter 17: Dates and Time (java.time.*)....................................................................................................... 82 Section 17.1: Calculate Dierence between 2 LocalDates....................................................................................... 82 Section 17.2: Date and time........................................................................................................................................ 82 Section 17.3: Operations on dates and times........................................................................................................... 82 Section 17.4: Instant..................................................................................................................................................... 82 Section 17.5: Usage of various classes of Date Time API........................................................................................ 83 Section 17.6: Date Time Formatting........................................................................................................................... 85 Section 17.7: Simple Date Manipulations................................................................................................................... 85 Chapter 18: LocalTime.............................................................................................................................................. 87 Section 18.1: Amount of time between two LocalTime............................................................................................ 87 Section 18.2: Intro........................................................................................................................................................ 88 Section 18.3: Time Modification.................................................................................................................................. 88 Section 18.4: Time Zones and their time dierence................................................................................................. 88 Chapter 19: BigDecimal............................................................................................................................................ 90 Section 19.1: Comparing BigDecimals........................................................................................................................ 90 Section 19.2: Using BigDecimal instead of float....................................................................................................... 90 Section 19.3: BigDecimal.valueOf()............................................................................................................................ 91 Section 19.4: Mathematical operations with BigDecimal......................................................................................... 91 Section 19.5: Initialization of BigDecimals with value zero, one or ten................................................................... 94 Section 19.6: BigDecimal objects are immutable..................................................................................................... 94 Chapter 20: BigInteger............................................................................................................................................ 96 Section 20.1: Initialization............................................................................................................................................ 96 Section 20.2: BigInteger Mathematical Operations Examples............................................................................... 97 Section 20.3: Comparing BigIntegers........................................................................................................................ 99 Section 20.4: Binary Logic Operations on BigInteger........................................................................................... 100 Section 20.5: Generating random BigIntegers....................................................................................................... 101 Chapter 21: NumberFormat................................................................................................................................. 103 Section 21.1: NumberFormat.................................................................................................................................... 103 Chapter 22: Bit Manipulation.............................................................................................................................. 104 Section 22.1: Checking, setting, clearing, and toggling individual bits. Using long as bit mask........................ 104 Section 22.2: java.util.BitSet class............................................................................................................................ 104 Section 22.3: Checking if a number is a power of 2.............................................................................................. 105 Section 22.4: Signed vs unsigned shift.................................................................................................................... 107 Section 22.5: Expressing the power of 2................................................................................................................. 107 Section 22.6: Packing / unpacking values as bit fragments................................................................................ 108 Chapter 23: Arrays................................................................................................................................................... 109 Section 23.1: Creating and Initializing Arrays......................................................................................................... 109 Section 23.2: Creating a List from an Array........................................................................................................... 115 Section 23.3: Creating an Array from a Collection................................................................................................ 117 Section 23.4: Multidimensional and Jagged Arrays.............................................................................................. 117 Section 23.5: ArrayIndexOutOfBoundsException.................................................................................................. 119 Section 23.6: Array Covariance............................................................................................................................... 120 Section 23.7: Arrays to Stream................................................................................................................................ 121 Section 23.8: Iterating over arrays.......................................................................................................................... 121 Section 23.9: Arrays to a String............................................................................................................................... 123 Section 23.10: Sorting arrays.................................................................................................................................... 124 Section 23.11: Getting the Length of an Array........................................................................................................ 126 Section 23.12: Finding an element in an array....................................................................................................... 126 Section 23.13: How do you change the size of an array?..................................................................................... 127 Section 23.14: Converting arrays between primitives and boxed types.............................................................. 128 Section 23.15: Remove an element from an array................................................................................................ 129 Section 23.16: Comparing arrays for equality........................................................................................................ 130 Section 23.17: Copying arrays.................................................................................................................................. 130 Section 23.18: Casting Arrays................................................................................................................................... 131 Chapter 24: Collections......................................................................................................................................... 133 Section 24.1: Removing items from a List within a loop........................................................................................ 133 Section 24.2: Constructing collections from existing data.................................................................................... 135 Section 24.3: Declaring an ArrayList and adding objects..................................................................................... 137 Section 24.4: Iterating over Collections.................................................................................................................. 137 Section 24.5: Immutable Empty Collections........................................................................................................... 139 Section 24.6: Sub Collections................................................................................................................................... 139 Section 24.7: Unmodifiable Collection..................................................................................................................... 140 Section 24.8: Pitfall: concurrent modification exceptions..................................................................................... 141 Section 24.9: Removing matching items from Lists using Iterator...................................................................... 141 Section 24.10: Join lists............................................................................................................................................. 142 Section 24.11: Creating your own Iterable structure for use with Iterator or for-each loop.............................. 142 Section 24.12: Collections and Primitive Values..................................................................................................... 144 Chapter 25: Lists....................................................................................................................................................... 146 Section 25.1: Sorting a generic list........................................................................................................................... 146 Section 25.2: Convert a list of integers to a list of strings..................................................................................... 147 Section 25.3: Classes implementing List - Pros and Cons..................................................................................... 147 Section 25.4: Finding common elements between 2 lists..................................................................................... 150 Section 25.5: In-place replacement of a List element........................................................................................... 150 Section 25.6: Making a list unmodifiable................................................................................................................ 151 Section 25.7: Moving objects around in the list...................................................................................................... 151 Section 25.8: Creating, Adding and Removing element from an ArrayList........................................................ 152 Section 25.9: Creating a List..................................................................................................................................... 152 Section 25.10: Positional Access Operations.......................................................................................................... 153 Section 25.11: Iterating over elements in a list........................................................................................................ 155 Section 25.12: Removing elements from list B that are present in the list A....................................................... 155 Chapter 26: Sets........................................................................................................................................................ 157 Section 26.1: Initialization.......................................................................................................................................... 157 Section 26.2: Basics of Set........................................................................................................................................ 157 Section 26.3: Types and Usage of Sets................................................................................................................... 158 Section 26.4: Create a list from an existing Set...................................................................................................... 159 Section 26.5: Eliminating duplicates using Set....................................................................................................... 159 Section 26.6: Declaring a HashSet with values...................................................................................................... 160 Chapter 27: List vs Set........................................................................................................................................... 161 Section 27.1: List vs Set............................................................................................................................................. 161 Chapter 28: Maps...................................................................................................................................................... 162 Section 28.1: Iterating Map Entries Eciently......................................................................................................... 162 Section 28.2: Usage of HashMap............................................................................................................................ 164 Section 28.3: Using Default Methods of Map from Java 8................................................................................... 165 Section 28.4: Iterating through the contents of a Map......................................................................................... 167 Section 28.5: Merging, combine and composing Maps........................................................................................ 168 Section 28.6: Add multiple items.............................................................................................................................. 169 Section 28.7: Creating and Initializing Maps........................................................................................................... 171 Section 28.8: Check if key exists.............................................................................................................................. 172 Section 28.9: Add an element.................................................................................................................................. 172 Section 28.10: Clear the map.................................................................................................................................... 173 Section 28.11: Use custom object as key................................................................................................................. 173 Chapter 29: LinkedHashMap............................................................................................................................... 175 Section 29.1: Java LinkedHashMap class............................................................................................................... 175 Chapter 30: WeakHashMap................................................................................................................................. 176 Section 30.1: Concepts of WeakHashmap.............................................................................................................. 176 Chapter 31: SortedMap.......................................................................................................................................... 177 Section 31.1: Introduction to sorted Map................................................................................................................. 177 Chapter 32: TreeMap and TreeSet.................................................................................................................. 178 Section 32.1: TreeMap of a simple Java type........................................................................................................ 178 Section 32.2: TreeSet of a simple Java Type......................................................................................................... 178 Section 32.3: TreeMap/TreeSet of a custom Java type....................................................................................... 179 Section 32.4: TreeMap and TreeSet Thread Safety.............................................................................................. 180 Chapter 33: Queues and Deques...................................................................................................................... 182 Section 33.1: The usage of the PriorityQueue......................................................................................................... 182 Section 33.2: Deque................................................................................................................................................... 182 Section 33.3: Stacks................................................................................................................................................... 183 Section 33.4: BlockingQueue.................................................................................................................................... 184 Section 33.5: LinkedList as a FIFO Queue............................................................................................................... 185 Section 33.6: Queue Interface.................................................................................................................................. 186 Chapter 34: Dequeue Interface........................................................................................................................ 187 Section 34.1: Adding Elements to Deque................................................................................................................. 187 Section 34.2: Removing Elements from Deque...................................................................................................... 187 Section 34.3: Retrieving Element without Removing............................................................................................. 187 Section 34.4: Iterating through Deque.................................................................................................................... 187 Chapter 35: Enums................................................................................................................................................... 189 Section 35.1: Declaring and using a basic enum.................................................................................................... 189 Section 35.2: Enums with constructors................................................................................................................... 192 Section 35.3: Enums with Abstract Methods........................................................................................................... 193 Section 35.4: Implements Interface......................................................................................................................... 194 Section 35.5: Implement Singleton pattern with a single-element enum............................................................ 195 Section 35.6: Using methods and static blocks...................................................................................................... 196 Section 35.7: Zero instance enum........................................................................................................................... 196 Section 35.8: Enum as a bounded type parameter............................................................................................... 197 Section 35.9: Documenting enums.......................................................................................................................... 197 Section 35.10: Enum constant specific body........................................................................................................... 198 Section 35.11: Getting the values of an enum......................................................................................................... 199 Section 35.12: Enum Polymorphism Pattern........................................................................................................... 200 Section 35.13: Compare and Contains for Enum values........................................................................................ 201 Section 35.14: Get enum constant by name........................................................................................................... 201 Section 35.15: Enum with properties (fields)........................................................................................................... 202 Section 35.16: Convert enum to String.................................................................................................................... 203 Section 35.17: Enums with static fields..................................................................................................................... 203 Chapter 36: Enum Map........................................................................................................................................... 205 Section 36.1: Enum Map Book Example.................................................................................................................. 205 Chapter 37: EnumSet class.................................................................................................................................. 206 Section 37.1: Enum Set Example.............................................................................................................................. 206 Chapter 38: Enum starting with number...................................................................................................... 207 Section 38.1: Enum with name at beginning........................................................................................................... 207 Chapter 39: Hashtable........................................................................................................................................... 208 Section 39.1: Hashtable............................................................................................................................................. 208 Chapter 40: Operators.......................................................................................................................................... 209 Section 40.1: The Increment/Decrement Operators (++/--)................................................................................ 209 Section 40.2: The Conditional Operator (? :).......................................................................................................... 209 Section 40.3: The Bitwise and Logical Operators (~, &, |, ^).................................................................................. 211 Section 40.4: The String Concatenation Operator (+)........................................................................................... 212 Section 40.5: The Arithmetic Operators (+, -, *, /, %)............................................................................................. 214 Section 40.6: The Shift Operators ( and >>>)............................................................................................... 216 Section 40.7: The Instanceof Operator................................................................................................................... 217 Section 40.8: The Assignment Operators (=, +=, -=, *=, /=, %=, = , >>>=, &=, |= and ^=)............................. 218 Section 40.9: The conditional-and and conditional-or Operators ( && and || ).................................................. 220 Section 40.10: The Relational Operators (=)............................................................................................ 221 Section 40.11: The Equality Operators (==, !=)......................................................................................................... 222 Section 40.12: The Lambda operator ( -> )............................................................................................................. 224 Chapter 41: Constructors..................................................................................................................................... 225 Section 41.1: Default Constructor............................................................................................................................. 225 Section 41.2: Call parent constructor....................................................................................................................... 226 Section 41.3: Constructor with Arguments.............................................................................................................. 227 Chapter 42: Object Class Methods and Constructor............................................................................. 229 Section 42.1: hashCode() method............................................................................................................................ 229 Section 42.2: toString() method............................................................................................................................... 231 Section 42.3: equals() method................................................................................................................................. 232 Section 42.4: wait() and notify() methods.............................................................................................................. 234 Section 42.5: getClass() method.............................................................................................................................. 236 Section 42.6: clone() method................................................................................................................................... 237 Section 42.7: Object constructor.............................................................................................................................. 238 Section 42.8: finalize() method................................................................................................................................ 239 Chapter 43: Annotations...................................................................................................................................... 241 Section 43.1: The idea behind Annotations............................................................................................................. 241 Section 43.2: Defining annotation types................................................................................................................. 241 Section 43.3: Runtime annotation checks via reflection....................................................................................... 243 Section 43.4: Built-in annotations............................................................................................................................ 243 Section 43.5: Compile time processing using annotation processor................................................................... 246 Section 43.6: Repeating Annotations...................................................................................................................... 250 Section 43.7: Inherited Annotations......................................................................................................................... 251 Section 43.8: Getting Annotation values at run-time............................................................................................. 252 Section 43.9: Annotations for 'this' and receiver parameters.............................................................................. 253 Section 43.10: Add multiple annotation values....................................................................................................... 254 Chapter 44: Immutable Class............................................................................................................................ 255 Section 44.1: Example without mutable refs........................................................................................................... 255 Section 44.2: What is the advantage of immutability?......................................................................................... 255 Section 44.3: Rules to define immutable classes................................................................................................... 255 Section 44.4: Example with mutable refs................................................................................................................ 256 Chapter 45: Immutable Objects....................................................................................................................... 257 Section 45.1: Creating an immutable version of a type using defensive copying.............................................. 257 Section 45.2: The recipe for an immutable class................................................................................................... 257 Section 45.3: Typical design flaws which prevent a class from being immutable............................................. 258 Chapter 46: Visibility (controlling access to members of a class)................................................. 262 Section 46.1: Private Visibility................................................................................................................................... 262 Section 46.2: Public Visibility.................................................................................................................................... 262 Section 46.3: Package Visibility................................................................................................................................ 263 Section 46.4: Protected Visibility.............................................................................................................................. 263 Section 46.5: Summary of Class Member Access Modifiers................................................................................. 264 Section 46.6: Interface members............................................................................................................................. 264 Chapter 47: Generics.............................................................................................................................................. 265 Section 47.1: Creating a Generic Class.................................................................................................................... 265 Section 47.2: Deciding between `T`, `? super T`, and `? extends T`........................................................................ 267 Section 47.3: The Diamond....................................................................................................................................... 269 Section 47.4: Declaring a Generic Method.............................................................................................................. 269 Section 47.5: Requiring multiple upper bounds ("extends A & B")....................................................................... 270 Section 47.6: Obtain class that satisfies generic parameter at runtime............................................................. 270 Section 47.7: Benefits of Generic class and interface........................................................................................... 271 Section 47.8: Instantiating a generic type.............................................................................................................. 272 Section 47.9: Creating a Bounded Generic Class................................................................................................... 272 Section 47.10: Referring to the declared generic type within its own declaration............................................. 274 Section 47.11: Binding generic parameter to more than 1 type............................................................................ 275 Section 47.12: Using Generics to auto-cast............................................................................................................. 276 Section 47.13: Use of instanceof with Generics...................................................................................................... 276 Section 47.14: Dierent ways for implementing a Generic Interface (or extending a Generic Class)............. 278 Chapter 48: Classes and Objects..................................................................................................................... 280 Section 48.1: Overloading Methods......................................................................................................................... 280 Section 48.2: Explaining what is method overloading and overriding................................................................ 281 Section 48.3: Constructors........................................................................................................................................ 283 Section 48.4: Initializing static final fields using a static initializer........................................................................ 284 Section 48.5: Basic Object Construction and Use.................................................................................................. 285 Section 48.6: Simplest Possible Class...................................................................................................................... 287 Section 48.7: Object Member vs Static Member.................................................................................................... 287 Chapter 49: Local Inner Class............................................................................................................................ 289 Section 49.1: Local Inner Class................................................................................................................................. 289 Chapter 50: Nested and Inner Classes.......................................................................................................... 290 Section 50.1: A Simple Stack Using a Nested Class............................................................................................... 290 Section 50.2: Static vs Non Static Nested Classes................................................................................................. 290 Section 50.3: Access Modifiers for Inner Classes................................................................................................... 292 Section 50.4: Anonymous Inner Classes................................................................................................................. 293 Section 50.5: Create instance of non-static inner class from outside................................................................. 294 Section 50.6: Method Local Inner Classes.............................................................................................................. 295 Section 50.7: Accessing the outer class from a non-static inner class................................................................ 295 Chapter 51: The java.util.Objects Class......................................................................................................... 297 Section 51.1: Basic use for object null check........................................................................................................... 297 Section 51.2: Objects.nonNull() method reference use in stream api.................................................................. 297 Chapter 52: Default Methods............................................................................................................................. 298 Section 52.1: Basic usage of default methods........................................................................................................ 298 Section 52.2: Accessing overridden default methods from implementing class............................................... 298 Section 52.3: Why use Default Methods?............................................................................................................... 299 Section 52.4: Accessing other interface methods within default method........................................................... 299 Section 52.5: Default method multiple inheritance collision................................................................................. 300 Section 52.6: Class, Abstract class and Interface method precedence.............................................................. 301 Chapter 53: Packages............................................................................................................................................ 303 Section 53.1: Using Packages to create classes with the same name................................................................. 303 Section 53.2: Using Package Protected Scope...................................................................................................... 303 Chapter 54: Inheritance........................................................................................................................................ 305 Section 54.1: Inheritance........................................................................................................................................... 305 Section 54.2: Abstract Classes................................................................................................................................. 306 Section 54.3: Using 'final' to restrict inheritance and overriding.......................................................................... 308 Section 54.4: The Liskov Substitution Principle...................................................................................................... 309 Section 54.5: Abstract class and Interface usage: "Is-a" relation vs "Has-a" capability................................... 310 Section 54.6: Static Inheritance................................................................................................................................ 313 Section 54.7: Programming to an interface........................................................................................................... 314 Section 54.8: Overriding in Inheritance................................................................................................................... 316 Section 54.9: Variable shadowing........................................................................................................................... 317 Section 54.10: Narrowing and Widening of object references............................................................................. 317 Section 54.11: Inheritance and Static Methods........................................................................................................ 318 Chapter 55: Reference Types............................................................................................................................ 320 Section 55.1: Dierent Reference Types................................................................................................................. 320 Chapter 56: Console I/O........................................................................................................................................ 322 Section 56.1: Reading user input from the console................................................................................................ 322 Section 56.2: Aligning strings in console................................................................................................................. 323 Section 56.3: Implementing Basic Command-Line Behavior................................................................................ 324 Chapter 57: Streams............................................................................................................................................... 326 Section 57.1: Using Streams..................................................................................................................................... 326 Section 57.2: Consuming Streams........................................................................................................................... 328 Section 57.3: Creating a Frequency Map................................................................................................................ 330 Section 57.4: Infinite Streams................................................................................................................................... 330 Section 57.5: Collect Elements of a Stream into a Collection............................................................................... 331 Section 57.6: Using Streams to Implement Mathematical Functions.................................................................. 334 Section 57.7: Flatten Streams with flatMap()......................................................................................................... 334 Section 57.8: Parallel Stream................................................................................................................................... 335 Section 57.9: Creating a Stream.............................................................................................................................. 336 Section 57.10: Finding Statistics about Numerical Streams.................................................................................. 337 Section 57.11: Converting an iterator to a stream.................................................................................................. 337 Section 57.12: Using IntStream to iterate over indexes......................................................................................... 337 Section 57.13: Concatenate Streams....................................................................................................................... 338 Section 57.14: Reduction with Streams.................................................................................................................... 338 Section 57.15: Using Streams of Map.Entry to Preserve Initial Values after Mapping....................................... 341 Section 57.16: IntStream to String............................................................................................................................ 341 Section 57.17: Finding the First Element that Matches a Predicate...................................................................... 341 Section 57.18: Using Streams and Method References to Write Self-Documenting Processes........................ 342 Section 57.19: Converting a Stream of Optional to a Stream of Values.............................................................. 343 Section 57.20: Get a Slice of a Stream.................................................................................................................... 343 Section 57.21: Create a Map based on a Stream................................................................................................... 343 Section 57.22: Joining a stream to a single String................................................................................................ 344 Section 57.23: Sort Using Stream............................................................................................................................ 345 Section 57.24: Streams of Primitives....................................................................................................................... 346 Section 57.25: Stream operations categories........................................................................................................ 346 Section 57.26: Collect Results of a Stream into an Array..................................................................................... 347 Section 57.27: Generating random Strings using Streams................................................................................... 347 Chapter 58: InputStreams and OutputStreams....................................................................................... 349 Section 58.1: Closing Streams.................................................................................................................................. 349 Section 58.2: Reading InputStream into a String................................................................................................... 349 Section 58.3: Wrapping Input/Output Streams..................................................................................................... 350 Section 58.4: DataInputStream Example................................................................................................................ 351 Section 58.5: Writing bytes to an OutputStream................................................................................................... 351 Section 58.6: Copying Input Stream to Output Stream......................................................................................... 351 Chapter 59: Readers and Writers.................................................................................................................... 353 Section 59.1: BueredReader................................................................................................................................... 353 Section 59.2: StringWriter Example......................................................................................................................... 354 Chapter 60: Preferences....................................................................................................................................... 355 Section 60.1: Using preferences............................................................................................................................... 355 Section 60.2: Adding event listeners....................................................................................................................... 355 Section 60.3: Getting sub-nodes of Preferences.................................................................................................... 356 Section 60.4: Coordinating preferences access across multiple application instances.................................... 357 Section 60.5: Exporting preferences....................................................................................................................... 357 Section 60.6: Importing preferences....................................................................................................................... 358 Section 60.7: Removing event listeners.................................................................................................................. 359 Section 60.8: Getting preferences values............................................................................................................... 360 Section 60.9: Setting preferences values................................................................................................................ 360 Chapter 61: Collection Factory Methods....................................................................................................... 361 Section 61.1: List Factory Method Examples..................................................................................................... 361 Section 61.2: Set Factory Method Examples..................................................................................................... 361 Section 61.3: Map Factory Method Examples.............................................................................................. 361 Chapter 62: Alternative Collections................................................................................................................ 362 Section 62.1: Multimap in Guava, Apache and Eclipse Collections....................................................................... 362 Section 62.2: Apache HashBag, Guava HashMultiset and Eclipse HashBag...................................................... 364 Section 62.3: Compare operation with collections - Create collections.............................................................. 366 Chapter 63: Concurrent Collections................................................................................................................ 371 Section 63.1: Thread-safe Collections...................................................................................................................... 371 Section 63.2: Insertion into ConcurrentHashMap.................................................................................................. 371 Section 63.3: Concurrent Collections....................................................................................................................... 372 Chapter 64: Choosing Collections.................................................................................................................... 374 Section 64.1: Java Collections Flowchart................................................................................................................ 374 Chapter 65: super keyword................................................................................................................................. 375 Section 65.1: Super keyword use with examples.................................................................................................... 375 Chapter 66: Serialization...................................................................................................................................... 378 Section 66.1: Basic Serialization in Java.................................................................................................................. 378 Section 66.2: Custom Serialization.......................................................................................................................... 379 Section 66.3: Versioning and serialVersionUID...................................................................................................... 382 Section 66.4: Serialization with Gson....................................................................................................................... 383 Section 66.5: Custom JSON Deserialization with Jackson.................................................................................... 384 Chapter 67: Optional............................................................................................................................................... 387 Section 67.1: Map....................................................................................................................................................... 387 Section 67.2: Return default value if Optional is empty........................................................................................ 388 Section 67.3: Throw an exception, if there is no value........................................................................................... 388 Section 67.4: Lazily provide a default value using a Supplier.............................................................................. 388 Section 67.5: Filter..................................................................................................................................................... 389 Section 67.6: Using Optional containers for primitive number types.................................................................. 389 Section 67.7: Run code only if there is a value present......................................................................................... 390 Section 67.8: FlatMap................................................................................................................................................ 390 Chapter 68: Object References......................................................................................................................... 391 Section 68.1: Object References as method parameters...................................................................................... 391 Chapter 69: Exceptions and exception handling...................................................................................... 394 Section 69.1: Catching an exception with try-catch............................................................................................... 394 Section 69.2: The try-with-resources statement.................................................................................................... 395 Section 69.3: Custom Exceptions............................................................................................................................. 398 Section 69.4: Handling InterruptedException......................................................................................................... 400 Section 69.5: Return statements in try catch block............................................................................................... 401 Section 69.6: Introduction......................................................................................................................................... 402 Section 69.7: The Java Exception Hierarchy - Unchecked and Checked Exceptions........................................ 403 Section 69.8: Creating and reading stacktraces.................................................................................................... 406 Section 69.9: Throwing an exception...................................................................................................................... 409 Section 69.10: Advanced features of Exceptions................................................................................................... 411 Section 69.11: The try-finally and try-catch-finally statements............................................................................ 412 Section 69.12: The 'throws' clause in a method declaration................................................................................. 414 Chapter 70: Calendar and its Subclasses.................................................................................................... 416 Section 70.1: Creating Calendar objects................................................................................................................. 416 Section 70.2: Increasing / Decreasing calendar fields.......................................................................................... 416 Section 70.3: Subtracting calendars........................................................................................................................ 416 Section 70.4: Finding AM/PM................................................................................................................................... 416 Chapter 71: Using the static keyword............................................................................................................ 418 Section 71.1: Reference to non-static member from static context..................................................................... 418 Section 71.2: Using static to declare constants...................................................................................................... 418 Chapter 72: Properties Class.............................................................................................................................. 420 Section 72.1: Loading properties.............................................................................................................................. 420 Section 72.2: Saving Properties as XML.................................................................................................................. 420 Section 72.3: Property files caveat: trailing whitespace........................................................................................ 421 Chapter 73: Lambda Expressions..................................................................................................................... 424 Section 73.1: Introduction to Java lambdas........................................................................................................... 424 Section 73.2: Using Lambda Expressions to Sort a Collection............................................................................. 427 Section 73.3: Method References............................................................................................................................ 428 Section 73.4: Implementing multiple interfaces..................................................................................................... 430 Section 73.5: Lambda - Listener Example.............................................................................................................. 430 Section 73.6: Java Closures with lambda expressions.......................................................................................... 431 Section 73.7: Lambdas and memory utilization..................................................................................................... 432 Section 73.8: Using lambda expression with your own functional interface...................................................... 433 Section 73.9: Traditional style to Lambda style..................................................................................................... 433 Section 73.10: `return` only returns from the lambda, not the outer method..................................................... 434 Section 73.11: Lambdas and Execute-around Pattern........................................................................................... 436 Section 73.12: Using lambda expressions & predicates to get a certain value(s) from a list........................... 436 Chapter 74: Basic Control Structures............................................................................................................ 438 Section 74.1: Switch statement................................................................................................................................. 438 Section 74.2: do...while Loop..................................................................................................................................... 439 Section 74.3: For Each............................................................................................................................................... 440 Section 74.4: Continue Statement in Java.............................................................................................................. 441 Section 74.5: If / Else If / Else Control..................................................................................................................... 441 Section 74.6: For Loops............................................................................................................................................. 441 Section 74.7: Ternary Operator............................................................................................................................... 442 Section 74.8: Try... Catch... Finally.......................................................................................................................... 443 Section 74.9: Break.................................................................................................................................................... 443 Section 74.10: While Loops....................................................................................................................................... 444 Section 74.11: If / Else................................................................................................................................................ 444 Section 74.12: Nested break / continue.................................................................................................................. 444 Chapter 75: BueredWriter................................................................................................................................ 446 Section 75.1: Write a line of text to File.................................................................................................................... 446 Chapter 76: New File I/O....................................................................................................................................... 447 Section 76.1: Creating paths..................................................................................................................................... 447 Section 76.2: Manipulating paths............................................................................................................................. 447 Section 76.3: Retrieving information about a path................................................................................................ 447 Section 76.4: Retrieving information using the filesystem.................................................................................... 448 Section 76.5: Reading files........................................................................................................................................ 449 Section 76.6: Writing files.......................................................................................................................................... 449 Chapter 77: File I/O................................................................................................................................................. 450 Section 77.1: Migrating from java.io.File to Java 7 NIO (java.nio.file.Path).......................................................... 450 Section 77.2: Reading an image from a file........................................................................................................... 452 Section 77.3: File Read/Write Using FileInputStream/FileOutputStream........................................................... 452 Section 77.4: Reading all bytes to a byte[]............................................................................................................ 453 Section 77.5: Copying a file using Channel............................................................................................................. 454 Section 77.6: Writing a byte[] to a file..................................................................................................................... 454 Section 77.7: Stream vs Writer/Reader API............................................................................................................ 455 Section 77.8: Reading a file with a Scanner........................................................................................................... 456 Section 77.9: Copying a file using InputStream and OutputStream.................................................................... 457 Section 77.10: Reading from a binary file............................................................................................................... 457 Section 77.11: Reading a file using Channel and Buer......................................................................................... 457 Section 77.12: Adding Directories............................................................................................................................. 458 Section 77.13: Blocking or redirecting standard output / error............................................................................ 459 Section 77.14: Reading a whole file at once............................................................................................................ 460 Section 77.15: Locking............................................................................................................................................... 460 Section 77.16: Reading a file using BueredInputStream..................................................................................... 460 Section 77.17: Iterate over a directory printing subdirectories in it...................................................................... 461 Section 77.18: Writing a file using Channel and Buer.......................................................................................... 461 Section 77.19: Writing a file using PrintStream....................................................................................................... 462 Section 77.20: Iterating over a directory and filter by file extension................................................................... 462 Section 77.21: Accessing the contents of a ZIP file................................................................................................ 463 Chapter 78: Scanner............................................................................................................................................... 464 Section 78.1: General Pattern that does most commonly asked about tasks.................................................... 464 Section 78.2: Using custom delimiters.................................................................................................................... 466 Section 78.3: Reading system input using Scanner............................................................................................... 466 Section 78.4: Reading file input using Scanner...................................................................................................... 466 Section 78.5: Read the entire input as a String using Scanner............................................................................. 467 Section 78.6: Carefully Closing a Scanner.............................................................................................................. 467 Section 78.7: Read an int from the command line................................................................................................ 468 Chapter 79: Interfaces........................................................................................................................................... 469 Section 79.1: Implementing multiple interfaces...................................................................................................... 469 Section 79.2: Declaring and Implementing an Interface....................................................................................... 470 Section 79.3: Extending an interface....................................................................................................................... 470 Section 79.4: Usefulness of interfaces.................................................................................................................... 471 Section 79.5: Default methods................................................................................................................................. 473 Section 79.6: Modifiers in Interfaces........................................................................................................................ 475 Section 79.7: Using Interfaces with Generics.......................................................................................................... 475 Section 79.8: Strengthen bounded type parameters............................................................................................ 478 Section 79.9: Implementing interfaces in an abstract class................................................................................. 478 Chapter 80: Regular Expressions..................................................................................................................... 480 Section 80.1: Using capture groups......................................................................................................................... 480 Section 80.2: Using regex with custom behaviour by compiling the Pattern with flags................................... 481 Section 80.3: Escape Characters............................................................................................................................. 481 Section 80.4: Not matching a given string............................................................................................................. 482 Section 80.5: Matching with a regex literal............................................................................................................. 482 Section 80.6: Matching a backslash........................................................................................................................ 482 Chapter 81: Comparable and Comparator.................................................................................................. 484 Section 81.1: Sorting a List using Comparable or a Comparator............................................................. 484 Section 81.2: The compareTo and compare Methods.......................................................................................... 487 Section 81.3: Natural (comparable) vs explicit (comparator) sorting................................................................. 488 Section 81.4: Creating a Comparator using comparing method......................................................................... 489 Section 81.5: Sorting Map entries............................................................................................................................. 489 Chapter 82: Java Floating Point Operations.............................................................................................. 491 Section 82.1: Comparing floating point values....................................................................................................... 491 Section 82.2: OverFlow and UnderFlow.................................................................................................................. 493 Section 82.3: Formatting the floating point values................................................................................................ 494 Section 82.4: Strict Adherence to the IEEE Specification....................................................................................... 494 Chapter 83: Currency and Money.................................................................................................................... 496 Section 83.1: Add custom currency......................................................................................................................... 496 Chapter 84: Object Cloning................................................................................................................................. 497 Section 84.1: Cloning performing a deep copy...................................................................................................... 497 Section 84.2: Cloning using a copy factory............................................................................................................ 498 Section 84.3: Cloning using a copy constructor..................................................................................................... 498 Section 84.4: Cloning by implementing Clonable interface.................................................................................. 498 Section 84.5: Cloning performing a shallow copy................................................................................................. 499 Chapter 85: Recursion............................................................................................................................................ 501 Section 85.1: The basic idea of recursion................................................................................................................ 501 Section 85.2: Deep recursion is problematic in Java............................................................................................ 501 Section 85.3: Types of Recursion............................................................................................................................. 503 Section 85.4: Computing the Nth Fibonacci Number............................................................................................ 503 Section 85.5: StackOverflowError & recursion to loop.......................................................................................... 504 Section 85.6: Computing the Nth power of a number........................................................................................... 506 Section 85.7: Traversing a Tree data structure with recursion............................................................................ 506 Section 85.8: Reverse a string using Recursion..................................................................................................... 507 Section 85.9: Computing the sum of integers from 1 to N.................................................................................... 507 Chapter 86: Converting to and from Strings............................................................................................. 508 Section 86.1: Converting String to other datatypes............................................................................................... 508 Section 86.2: Conversion to / from bytes............................................................................................................... 509 Section 86.3: Base64 Encoding / Decoding............................................................................................................ 509 Section 86.4: Converting other datatypes to String.............................................................................................. 510 Section 86.5: Getting a `String` from an `InputStream`.......................................................................................... 511 Chapter 87: Random Number Generation.................................................................................................. 512 Section 87.1: Pseudo Random Numbers................................................................................................................. 512 Section 87.2: Pseudo Random Numbers in Specific Range................................................................................. 512 Section 87.3: Generating cryptographically secure pseudorandom numbers................................................... 513 Section 87.4: Generating Random Numbers with a Specified Seed.................................................................... 513 Section 87.5: Select random numbers without duplicates.................................................................................... 514 Section 87.6: Generating Random number using apache-common lang3........................................................ 515 Chapter 88: Singletons.......................................................................................................................................... 516 Section 88.1: Enum Singleton................................................................................................................................... 516 Section 88.2: Singleton without use of Enum (eager initialization)...................................................................... 516 Section 88.3: Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation............ 517 Section 88.4: Thread safe Singleton with double checked locking...................................................................... 517 Section 88.5: Extending singleton (singleton inheritance).................................................................................... 518 Chapter 89: Autoboxing......................................................................................................................................... 521 Section 89.1: Using int and Integer interchangeably............................................................................................. 521 Section 89.2: Auto-unboxing may lead to NullPointerException.......................................................................... 522 Section 89.3: Using Boolean in if statement........................................................................................................... 522 Section 89.4: Dierent Cases When Integer and int can be used interchangeably.......................................... 522 Section 89.5: Memory and Computational Overhead of Autoboxing................................................................. 524 Chapter 90: 2D Graphics in Java...................................................................................................................... 525 Section 90.1: Example 1: Draw and Fill a Rectangle Using Java.......................................................................... 525 Section 90.2: Example 2: Drawing and Filling Oval............................................................................................... 527 Chapter 91: JAXB....................................................................................................................................................... 528 Section 91.1: Reading an XML file (unmarshalling)................................................................................................ 528 Section 91.2: Writing an XML file (marshalling an object)..................................................................................... 528 Section 91.3: Manual field/property XML mapping configuration....................................................................... 529 Section 91.4: Binding an XML namespace to a serializable Java class............................................................... 530 Section 91.5: Using XmlAdapter to generate desired xml format........................................................................ 530 Section 91.6: Using XmlAdapter to trim string........................................................................................................ 532 Section 91.7: Automatic field/property XML mapping configuration (@XmlAccessorType)............................ 532 Section 91.8: Specifying a XmlAdapter instance to (re)use existing data........................................................... 534 Chapter 92: Class - Java Reflection................................................................................................................ 537 Section 92.1: getClass() method of Object class.................................................................................................... 537 Chapter 93: Networking......

Use Quizgecko on...
Browser
Browser