IT

Java Notes for Professionals.pdf

DownLoad Book

Published: 2018-04-09 Author:Bieber 33 Browses


Tags: java

默认图片

Extracting password:85ffbc5e41101838


Java
Notes for Professionals
Java
®
Notes for Professionals
GoalKicker.com
Free Programming Books
Disclaimer
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).
All trademarks and registered trademarks are
the property of their respective owners
900+ pages
of professional hints and tricks
Contents
About 1 ...................................................................................................................................................................................
Chapter 1: Getting started with Java Language 2 ..........................................................................................
Section 1.1: Creating Your First Java Program 2 ...........................................................................................................
Chapter 2: Type Conversion 7 ....................................................................................................................................
Section 2.1: Numeric primitive casting 7 .........................................................................................................................
Section 2.2: Basic Numeric Promotion 7 ........................................................................................................................
Section 2.3: Non-numeric primitive casting 7 ................................................................................................................
Section 2.4: Object casting 8 ...........................................................................................................................................
Section 2.5: Testing if an object can be cast using instanceof 8 .................................................................................
Chapter 3: Getters and Setters 9 .............................................................................................................................
Section 3.1: Using a setter or getter to implement a constraint 9 ...............................................................................
Section 3.2: Why Use Getters and Setters? 9 ................................................................................................................
Section 3.3: Adding Getters and Setters 10 ...................................................................................................................
Chapter 4: Reference Data Types 12 ....................................................................................................................
Section 4.1: Dereferencing 12 ..........................................................................................................................................
Section 4.2: Instantiating a reference type 12 ...............................................................................................................
Chapter 5: Java Compiler - 'javac' 13 ....................................................................................................................
Section 5.1: The 'javac' command - getting started 13 ................................................................................................
Section 5.2: Compiling for a dierent version of Java 15 ............................................................................................
Chapter 6: Documenting Java Code 17 .................................................................................................................
Section 6.1: Building Javadocs From the Command Line 17 .......................................................................................
Section 6.2: Class Documentation 17 .............................................................................................................................
Section 6.3: Method Documentation 18 .........................................................................................................................
Section 6.4: Package Documentation 19 .......................................................................................................................
Section 6.5: Links 19 .........................................................................................................................................................
Section 6.6: Code snippets inside documentation 20 ...................................................................................................
Section 6.7: Field Documentation 21 ..............................................................................................................................
Section 6.8: Inline Code Documentation 21 ...................................................................................................................
Chapter 7: Command line Argument Processing 23 .......................................................................................
Section 7.1: Argument processing using GWT ToolBase 23 .........................................................................................
Section 7.2: Processing arguments by hand 23 ............................................................................................................
Chapter 8: The Java Command - 'java' and 'javaw' 26 .................................................................................
Section 8.1: Entry point classes 26 ..................................................................................................................................
Section 8.2: Troubleshooting the 'java' command 26 ..................................................................................................
Section 8.3: Running a Java application with library dependencies 28 .....................................................................
Section 8.4: Java Options 29 ...........................................................................................................................................
Section 8.5: Spaces and other special characters in arguments 30 ...........................................................................
Section 8.6: Running an executable JAR file 32 ............................................................................................................
Section 8.7: Running a Java applications via a "main" class 32 .................................................................................
Chapter 9: Date Class 34 ...............................................................................................................................................
Section 9.1: Convert java.util.Date to java.sql.Date 34 ..................................................................................................
Section 9.2: A basic date output 34 ................................................................................................................................
Section 9.3: Java 8 LocalDate and LocalDateTime objects 35 ...................................................................................
Section 9.4: Creating a Specific Date 36 ........................................................................................................................
Section 9.5: Converting Date to a certain String format 36 .........................................................................................
Section 9.6: LocalTime 37 ................................................................................................................................................
Section 9.7: Convert formatted string representation of date to Date object 37 .....................................................
Section 9.8: Creating Date objects 38 ............................................................................................................................
Section 9.9: Comparing Date objects 38 ........................................................................................................................
Section 9.10: Converting String into Date 41 .................................................................................................................
Section 9.11: Time Zones and java.util.Date 41 ..............................................................................................................
Chapter 10: Dates and Time (java.time.*) 43 ......................................................................................................
Section 10.1: Calculate Dierence between 2 LocalDates 43 .......................................................................................
Section 10.2: Date and time 43 ........................................................................................................................................
Section 10.3: Operations on dates and times 43 ...........................................................................................................
Section 10.4: Instant 43 .....................................................................................................................................................
Section 10.5: Usage of various classes of Date Time API 44 .......................................................................................
Section 10.6: Date Time Formatting 46 ..........................................................................................................................
Section 10.7: Simple Date Manipulations 46 ...................................................................................................................
Chapter 11: LocalTime 48 ...............................................................................................................................................
Section 11.1: Amount of time between two LocalTime 48 .............................................................................................
Section 11.2: Intro 49 .........................................................................................................................................................
Section 11.3: Time Modification 49 ...................................................................................................................................
Section 11.4: Time Zones and their time dierence 49 .................................................................................................
Chapter 12: Literals 51 ....................................................................................................................................................
Section 12.1: Using underscore to improve readability 51 ............................................................................................
Section 12.2: Hexadecimal, Octal and Binary literals 51 ...............................................................................................
Section 12.3: Boolean literals 52 ......................................................................................................................................
Section 12.4: String literals 52 ..........................................................................................................................................
Section 12.5: The Null literal 53 ........................................................................................................................................
Section 12.6: Escape sequences in literals 53 ................................................................................................................
Section 12.7: Character literals 54 ...................................................................................................................................
Section 12.8: Decimal Integer literals 54 .........................................................................................................................
Section 12.9: Floating-point literals 55 ............................................................................................................................
Chapter 13: Operators 58 ..............................................................................................................................................
Section 13.1: The Increment/Decrement Operators (++/--) 58 ....................................................................................
Section 13.2: The Conditional Operator (? :) 58 .............................................................................................................
Section 13.3: The Bitwise and Logical Operators (~, &, |, ^) 60 .....................................................................................
Section 13.4: The String Concatenation Operator (+) 61 ..............................................................................................
Section 13.5: The Arithmetic Operators (+, -, *, /, %) 63 ................................................................................................
Section 13.6: The Shift Operators (<<, >> and >>>) 65 ...................................................................................................
Section 13.7: The Instanceof Operator 66 ......................................................................................................................
Section 13.8: The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=) 67 .................................
Section 13.9: The conditional-and and conditional-or Operators ( && and || ) 69 .....................................................
Section 13.10: The Relational Operators (<, <=, >, >=) 70 ...............................................................................................
Section 13.11: The Equality Operators (==, !=) 71 .............................................................................................................
Section 13.12: The Lambda operator ( -> ) 73 ................................................................................................................
Chapter 14: Primitive Data Types 74 ......................................................................................................................
Section 14.1: The char primitive 74 ..................................................................................................................................
Section 14.2: Primitive Types Cheatsheet 74 ..................................................................................................................
Section 14.3: The float primitive 75 .................................................................................................................................
Section 14.4: The int primitive 76 .....................................................................................................................................
Section 14.5: Converting Primitives 77 ............................................................................................................................
Section 14.6: Memory consumption of primitives vs. boxed primitives 77 ..................................................................
Section 14.7: The double primitive 78 .............................................................................................................................
Section 14.8: The long primitive 79 ..................................................................................................................................
Section 14.9: The boolean primitive 80 ...........................................................................................................................
Section 14.10: The byte primitive 80 ................................................................................................................................
Section 14.11: Negative value representation 80 ............................................................................................................
Section 14.12: The short primitive 81 ...............................................................................................................................
Chapter 15: Constructors 83 ........................................................................................................................................
Section 15.1: Default Constructor 83 ...............................................................................................................................
Section 15.2: Call parent constructor 84 .........................................................................................................................
Section 15.3: Constructor with Arguments 85 ................................................................................................................
Chapter 16: Object Class Methods and Constructor 87 .................................................................................
Section 16.1: hashCode() method 87 ...............................................................................................................................
Section 16.2: toString() method 89 ..................................................................................................................................
Section 16.3: equals() method 90 ....................................................................................................................................
Section 16.4: wait() and notify() methods 92 .................................................................................................................
Section 16.5: getClass() method 94 .................................................................................................................................
Section 16.6: clone() method 95 ......................................................................................................................................
Section 16.7: Object constructor 96 .................................................................................................................................
Section 16.8: finalize() method 97 ...................................................................................................................................
Chapter 17: Annotations 99 ..........................................................................................................................................
Section 17.1: The idea behind Annotations 99 ................................................................................................................
Section 17.2: Defining annotation types 99 ....................................................................................................................
Section 17.3: Runtime annotation checks via reflection 101 ........................................................................................
Section 17.4: Built-in annotations 101 .............................................................................................................................
Section 17.5: Compile time processing using annotation processor 104 ....................................................................
Section 17.6: Repeating Annotations 108 .......................................................................................................................
Section 17.7: Inherited Annotations 109 ..........................................................................................................................
Section 17.8: Getting Annotation values at run-time 110 .............................................................................................
Section 17.9: Annotations for 'this' and receiver parameters 111 ...............................................................................
Section 17.10: Add multiple annotation values 112 .......................................................................................................
Chapter 18: Immutable Class 113 ..............................................................................................................................
Section 18.1: Example without mutable refs 113 ............................................................................................................
Section 18.2: What is the advantage of immutability? 113 ..........................................................................................
Section 18.3: Rules to define immutable classes 113 ....................................................................................................
Section 18.4: Example with mutable refs 114 .................................................................................................................
Chapter 19: Immutable Objects 115 .........................................................................................................................
Section 19.1: Creating an immutable version of a type using defensive copying 115 ..............................................
Section 19.2: The recipe for an immutable class 115 ....................................................................................................
Section 19.3: Typical design flaws which prevent a class from being immutable 116 ..............................................
Chapter 20: Visibility (controlling access to members of a class) 120 ..................................................
Section 20.1: Private Visibility 120 ...................................................................................................................................
Section 20.2: Public Visibility 120 ....................................................................................................................................
Section 20.3: Package Visibility 121 ...............................................................................................................................
Section 20.4: Protected Visibility 121 ..............................................................................................................................
Section 20.5: Summary of Class Member Access Modifiers 122 .................................................................................
Section 20.6: Interface members 122 ............................................................................................................................
Chapter 21: Generics 123 ................................................................................................................................................
Section 21.1: Creating a Generic Class 123 .....................................................................................................................
Section 21.2: Deciding between `T`, `? super T`, and `? extends T` 125 ........................................................................
Section 21.3: The Diamond 127 .......................................................................................................................................
Section 21.4: Declaring a Generic Method 127 ..............................................................................................................
Section 21.5: Requiring multiple upper bounds ("extends A & B") 128 .......................................................................
Section 21.6: Obtain class that satisfies generic parameter at runtime 128 ..............................................................
Section 21.7: Benefits of Generic class and interface 129 ............................................................................................
Section 21.8: Instantiating a generic type 130 ...............................................................................................................
Section 21.9: Creating a Bounded Generic Class 130 ...................................................................................................
Section 21.10: Referring to the declared generic type within its own declaration 132 ..............................................
Section 21.11: Binding generic parameter to more than 1 type 133 .............................................................................
Section 21.12: Using Generics to auto-cast 134 .............................................................................................................
Section 21.13: Use of instanceof with Generics 134 .......................................................................................................
Section 21.14: Dierent ways for implementing a Generic Interface (or extending a Generic Class) 136 ..............
Chapter 22: Classes and Objects 138 ......................................................................................................................
Section 22.1: Overloading Methods 138 .........................................................................................................................
Section 22.2: Explaining what is method overloading and overriding 139 ................................................................
Section 22.3: Constructors 141 ........................................................................................................................................
Section 22.4: Initializing static final fields using a static initializer 142 ........................................................................
Section 22.5: Basic Object Construction and Use 143 ..................................................................................................
Section 22.6: Simplest Possible Class 145 ......................................................................................................................
Section 22.7: Object Member vs Static Member 145 ....................................................................................................
Chapter 23: Local Inner Class 147 .............................................................................................................................
Section 23.1: Local Inner Class 147 .................................................................................................................................
Chapter 24: Nested and Inner Classes 148 ..........................................................................................................
Section 24.1: A Simple Stack Using a Nested Class 148 ...............................................................................................
Section 24.2: Static vs Non Static Nested Classes 148 .................................................................................................
Section 24.3: Access Modifiers for Inner Classes 150 ...................................................................................................
Section 24.4: Anonymous Inner Classes 151 .................................................................................................................
Section 24.5: Create instance of non-static inner class from outside 152 .................................................................
Section 24.6: Method Local Inner Classes 153 ..............................................................................................................
Section 24.7: Accessing the outer class from a non-static inner class 153 ................................................................
Chapter 25: The java.util.Objects Class 155 .........................................................................................................
Section 25.1: Basic use for object null check 155 ..........................................................................................................
Section 25.2: Objects.nonNull() method reference use in stream api 155 .................................................................
Chapter 26: Default Methods 156 .............................................................................................................................
Section 26.1: Basic usage of default methods 156 ........................................................................................................
Section 26.2: Accessing overridden default methods from implementing class 156 ...............................................
Section 26.3: Why use Default Methods? 157 ...............................................................................................................
Section 26.4: Accessing other interface methods within default method 157 ...........................................................
Section 26.5: Default method multiple inheritance collision 158 .................................................................................
Section 26.6: Class, Abstract class and Interface method precedence 159 ..............................................................
Chapter 27: Packages 161 ............................................................................................................................................
Section 27.1: Using Packages to create classes with the same name 161 .................................................................
Section 27.2: Using Package Protected Scope 161 ......................................................................................................
Chapter 28: Inheritance 163 .........................................................................................................................................
Section 28.1: Inheritance 163 ...........................................................................................................................................
Section 28.2: Abstract Classes 164 .................................................................................................................................
Section 28.3: Using 'final' to restrict inheritance and overriding 166 ..........................................................................
Section 28.4: The Liskov Substitution Principle 167 ......................................................................................................
Section 28.5: Abstract class and Interface usage: "Is-a" relation vs "Has-a" capability 167 ...................................
Section 28.6: Static Inheritance 171 ................................................................................................................................
Section 28.7: Programming to an interface 172 ...........................................................................................................
Section 28.8: Overriding in Inheritance 174 ...................................................................................................................
Section 28.9: Variable shadowing 175 ...........................................................................................................................
Section 28.10: Narrowing and Widening of object references 175 .............................................................................
Section 28.11: Inheritance and Static Methods 176 ........................................................................................................
Chapter 29: Reference Types 178 .............................................................................................................................
Section 29.1: Dierent Reference Types 178 .................................................................................................................
Chapter 30: Strings 180 ..................................................................................................................................................
Section 30.1: Comparing Strings 180 ..............................................................................................................................
Section 30.2: Changing the case of characters within a String 182 ............................................................................
Section 30.3: Finding a String Within Another String 184 .............................................................................................
Section 30.4: String pool and heap storage 184 ...........................................................................................................
Section 30.5: Splitting Strings 186 ...................................................................................................................................
Section 30.6: Joining Strings with a delimiter 188 .........................................................................................................
Section 30.7: String concatenation and StringBuilders 189 .........................................................................................
Section 30.8: Substrings 190 ............................................................................................................................................
Section 30.9: Platform independent new line separator 191 .......................................................................................
Section 30.10: Reversing Strings 191 ..............................................................................................................................
Section 30.11: Adding toString() method for custom objects 192 ................................................................................
Section 30.12: Remove Whitespace from the Beginning and End of a String 193 ....................................................
Section 30.13: Case insensitive switch 193 .....................................................................................................................
Section 30.14: Replacing parts of Strings 193 ................................................................................................................
Section 30.15: Getting the length of a String 195 ..........................................................................................................
Section 30.16: Getting the nth character in a String 195 ..............................................................................................
Section 30.17: Counting occurrences of a substring or character in a string 195 .....................................................
Chapter 31: StringBuer 197 .......................................................................................................................................
Section 31.1: String Buer class 197 ................................................................................................................................
Chapter 32: StringBuilder 198 .....................................................................................................................................
Section 32.1: Comparing StringBuer, StringBuilder, Formatter and StringJoiner 198 ............................................
Section 32.2: Repeat a String n times 199 .....................................................................................................................
Chapter 33: String Tokenizer 200 ..............................................................................................................................
Section 33.1: StringTokenizer Split by space 200 ...........................................................................................................
Section 33.2: StringTokenizer Split by comma ',' 200 ....................................................................................................
Chapter 34: Splitting a string into fixed length parts 201 ...........................................................................
Section 34.1: Break a string up into substrings all of a known length 201 .................................................................
Section 34.2: Break a string up into substrings all of variable length 201 .................................................................
Chapter 35: BigInteger 202 ...........................................................................................................................................
Section 35.1: Initialization 202 ..........................................................................................................................................
Section 35.2: BigInteger Mathematical Operations Examples 203 .............................................................................
Section 35.3: Comparing BigIntegers 205 ......................................................................................................................
Section 35.4: Binary Logic Operations on BigInteger 206 ............................................................................................
Section 35.5: Generating random BigIntegers 207 .......................................................................................................
Chapter 36: Console I/O 209 ........................................................................................................................................
Section 36.1: Reading user input from the console 209 ................................................................................................
Section 36.2: Aligning strings in console 210 .................................................................................................................
Section 36.3: Implementing Basic Command-Line Behavior 211 ................................................................................
Chapter 37: BigDecimal 213 .........................................................................................................................................
Section 37.1: Comparing BigDecimals 213 .....................................................................................................................
Section 37.2: Using BigDecimal instead of float 213 ....................................................................................................
Section 37.3: BigDecimal.valueOf() 214 .........................................................................................................................
Section 37.4: Mathematical operations with BigDecimal 214 ......................................................................................
Section 37.5: Initialization of BigDecimals with value zero, one or ten 217 ................................................................
Section 37.6: BigDecimal objects are immutable 217 ..................................................................................................
Chapter 38: NumberFormat 219 ................................................................................................................................
Section 38.1: NumberFormat 219 ....................................................................................................................................
Chapter 39: Bit Manipulation 220 ..............................................................................................................................
Section 39.1: Checking, setting, clearing, and toggling individual bits. Using long as bit mask 220 ........................
Section 39.2: java.util.BitSet class 220 ............................................................................................................................
Section 39.3: Checking if a number is a power of 2 221 ..............................................................................................
Section 39.4: Signed vs unsigned shift 223 ....................................................................................................................
Section 39.5: Expressing the power of 2 223 .................................................................................................................
Section 39.6: Packing / unpacking values as bit fragments 224 ................................................................................
Chapter 40: Arrays 225 ..................................................................................................................................................
Section 40.1: Creating and Initializing Arrays 225 .........................................................................................................
Section 40.2: Creating a List from an Array 231 ...........................................................................................................
Section 40.3: Creating an Array from a Collection 233 ................................................................................................
Section 40.4: Multidimensional and Jagged Arrays 233 ..............................................................................................
Section 40.5: ArrayIndexOutOfBoundsException 235 ..................................................................................................
Section 40.6: Array Covariance 236 ...............................................................................................................................
Section 40.7: Arrays to Stream 237 ................................................................................................................................
Section 40.8: Iterating over arrays 237 ..........................................................................................................................
Section 40.9: Arrays to a String 239 ...............................................................................................................................
Section 40.10: Sorting arrays 240 ...................................................................................................................................
Section 40.11: Getting the Length of an Array 242 ........................................................................................................
Section 40.12: Finding an element in an array 242 .......................................................................................................
Section 40.13: How do you change the size of an array? 243 .....................................................................................
Section 40.14: Converting arrays between primitives and boxed types 244 .............................................................
Section 40.15: Remove an element from an array 245 ................................................................................................
Section 40.16: Comparing arrays for equality 246 ........................................................................................................
Section 40.17: Copying arrays 246 ..................................................................................................................................
Section 40.18: Casting Arrays 247 ...................................................................................................................................
Chapter 41: Streams 249 ...............................................................................................................................................
Section 41.1: Using Streams 249 ......................................................................................................................................
Section 41.2: Consuming Streams 251 ............................................................................................................................
Section 41.3: Creating a Frequency Map 253 ................................................................................................................
Section 41.4: Infinite Streams 253 ...................................................................................................................................
Section 41.5: Collect Elements of a Stream into a Collection 254 ................................................................................
Section 41.6: Using Streams to Implement Mathematical Functions 256 ...................................................................
Section 41.7: Flatten Streams with flatMap() 257 ..........................................................................................................
Section 41.8: Parallel Stream 258 ....................................................................................................................................
Section 41.9: Creating a Stream 258 ...............................................................................................................................
Section 41.10: Finding Statistics about Numerical Streams 260 ...................................................................................
Section 41.11: Converting an iterator to a stream 260 ...................................................................................................
Section 41.12: Using IntStream to iterate over indexes 260 ..........................................................................................
Section 41.13: Concatenate Streams 261 ........................................................................................................................
Section 41.14: Reduction with Streams 261 ....................................................................................................................
Section 41.15: Using Streams of Map.Entry to Preserve Initial Values after Mapping 264 ........................................
Section 41.16: IntStream to String 264 .............................................................................................................................
Section 41.17: Finding the First Element that Matches a Predicate 264 ......................................................................
Section 41.18: Using Streams and Method References to Write Self-Documenting Processes 265 ........................
Section 41.19: Converting a Stream of Optional to a Stream of Values 266 ..............................................................
Section 41.20: Get a Slice of a Stream 266 .....................................................................................................................
Section 41.21: Create a Map based on a Stream 266 ....................................................................................................
Section 41.22: Joining a stream to a single String 267 .................................................................................................
Section 41.23: Sort Using Stream 268 .............................................................................................................................
Section 41.24: Streams of Primitives 269 ........................................................................................................................
Section 41.25: Stream operations categories 269 .........................................................................................................
Section 41.26: Collect Results of a Stream into an Array 270 ......................................................................................
Section 41.27: Generating random Strings using Streams 270 ....................................................................................
Chapter 42: InputStreams and OutputStreams 271 .......................................................................................
Section 42.1: Closing Streams 271 ..................................................................................................................................
Section 42.2: Reading InputStream into a String 271 ...................................................................................................
Section 42.3: Wrapping Input/Output Streams 272 .....................................................................................................
Section 42.4: DataInputStream Example 273 ................................................................................................................
Section 42.5: Writing bytes to an OutputStream 273 ...................................................................................................
Section 42.6: Copying Input Stream to Output Stream 273 .........................................................................................
Chapter 43: Readers and Writers 275 ....................................................................................................................
Section 43.1: BueredReader 275 ...................................................................................................................................
Section 43.2: StringWriter Example 276 .........................................................................................................................
Chapter 44: Preferences 277 ......................................................................................................................................
Section 44.1: Using preferences 277 ...............................................................................................................................
Section 44.2: Adding event listeners 277 .......................................................................................................................
Section 44.3: Getting sub-nodes of Preferences 278 ....................................................................................................
Section 44.4: Coordinating preferences access across multiple application instances 279 ....................................
Section 44.5: Exporting preferences 279 .......................................................................................................................
Section 44.6: Importing preferences 280 .......................................................................................................................
Section 44.7: Removing event listeners 281 ..................................................................................................................
Section 44.8: Getting preferences values 282 ...............................................................................................................
Section 44.9: Setting preferences values 282 ................................................................................................................
Chapter 45: Collections 283 .........................................................................................................................................
Section 45.1: Removing items from a List within a loop 283 ........................................................................................
Section 45.2: Constructing collections from existing data 285 ....................................................................................
Section 45.3: Declaring an ArrayList and adding objects 287 .....................................................................................
Section 45.4: Iterating over Collections 287 ...................................................................................................................
Section 45.5: Immutable Empty Collections 289 ...........................................................................................................
Section 45.6: Sub Collections 289 ...................................................................................................................................
Section 45.7: Unmodifiable Collection 290 .....................................................................................................................
Section 45.8: Pitfall: concurrent modification exceptions 291 .....................................................................................
Section 45.9: Removing matching items from Lists using Iterator 291 ......................................................................
Section 45.10: Join lists 292 .............................................................................................................................................
Section 45.11: Creating your own Iterable structure for use with Iterator or for-each loop 292 ..............................
Section 45.12: Collections and Primitive Values 294 .....................................................................................................
Chapter 46: Queues and Deques 295 ......................................................................................................................
Section 46.1: The usage of the PriorityQueue 295 .........................................................................................................
Section 46.2: Deque 295 ..................................................................................................................................................
Section 46.3: Stacks 296 ..................................................................................................................................................
Section 46.4: BlockingQueue 297 ....................................................................................................................................
Section 46.5: LinkedList as a FIFO Queue 298 ...............................................................................................................
Section 46.6: Queue Interface 299 ..................................................................................................................................
Chapter 47: Collection Factory Methods 300 .....................................................................................................
Section 47.1: List<E> Factory Method Examples 300 ....................................................................................................
Section 47.2: Set<E> Factory Method Examples 300 ....................................................................................................
Section 47.3: Map<K, V> Factory Method Examples 300 .............................................................................................
Chapter 48: Alternative Collections 301 ................................................................................................................
Section 48.1: Multimap in Guava, Apache and Eclipse Collections 301 .......................................................................
Section 48.2: Apache HashBag, Guava HashMultiset and Eclipse HashBag 303 ......................................................
Section 48.3: Compare operation with collections - Create collections 305 ..............................................................
Chapter 49: Concurrent Collections 310 ...............................................................................................................
Section 49.1: Thread-safe Collections 310 .....................................................................................................................
Section 49.2: Insertion into ConcurrentHashMap 310 ..................................................................................................
Section 49.3: Concurrent Collections 311 .......................................................................................................................
Chapter 50: Choosing Collections 313 ....................................................................................................................
Section 50.1: Java Collections Flowchart 313 ................................................................................................................
Chapter 51: super keyword 314 ..................................................................................................................................
Section 51.1: Super keyword use with examples 314 .....................................................................................................
Chapter 52: Serialization 317 ......................................................................................................................................
Section 52.1: Basic Serialization in Java 317 ..................................................................................................................
Section 52.2: Custom Serialization 318 ..........................................................................................................................
Section 52.3: Versioning and serialVersionUID 321 ......................................................................................................
Section 52.4: Serialization with Gson 322 .......................................................................................................................
Section 52.5: Custom JSON Deserialization with Jackson 323 ...................................................................................
Chapter 53: Enums 326 ...................................................................................................................................................
Section 53.1: Declaring and using a basic enum 326 ....................................................................................................
Section 53.2: Enums with constructors 329 ...................................................................................................................
Section 53.3: Enums with Abstract Methods 330 ...........................................................................................................
Section 53.4: Implements Interface 331 .........................................................................................................................
Section 53.5: Implement Singleton pattern with a single-element enum 332 ............................................................
Section 53.6: Using methods and static blocks 333 ......................................................................................................
Section 53.7: Zero instance enum 333 ...........................................................................................................................
Section 53.8: Enum as a bounded type parameter 334 ...............................................................................................
Section 53.9: Documenting enums 334 ..........................................................................................................................
Section 53.10: Enum constant specific body 335 ...........................................................................................................
Section 53.11: Getting the values of an enum 336 .........................................................................................................
Section 53.12: Enum Polymorphism Pattern 337 ...........................................................................................................
Section 53.13: Compare and Contains for Enum values 338 ........................................................................................
Section 53.14: Get enum constant by name 338 ...........................................................................................................
Section 53.15: Enum with properties (fields) 339 ...........................................................................................................
Section 53.16: Convert enum to String 340 ....................................................................................................................
Section 53.17: Enums with static fields 340 .....................................................................................................................
Chapter 54: Enum Map 342 ..........................................................................................................................................
Section 54.1: Enum Map Book Example 342 ..................................................................................................................
Chapter 55: EnumSet class 343 ..................................................................................................................................
Section 55.1: Enum Set Example 343 ..............................................................................................................................
Chapter 56: Enum starting with number 344 ......................................................................................................
Section 56.1: Enum with name at begining 344 .............................................................................................................
Chapter 57: Lists 345 .......................................................................................................................................................
Section 57.1: Sorting a generic list 345 ...........................................................................................................................
Section 57.2: Convert a list of integers to a list of strings 346 .....................................................................................
Section 57.3: Classes implementing List - Pros and Cons 346 .....................................................................................
Section 57.4: Finding common elements between 2 lists 348 .....................................................................................
Section 57.5: In-place replacement of a List element 349 ...........................................................................................
Section 57.6: Making a list unmodifiable 350 ................................................................................................................
Section 57.7: Moving objects around in the list 350 ......................................................................................................
Section 57.8: Creating, Adding and Removing element from an ArrayList 350 ........................................................
Section 57.9: Creating a List 351 .....................................................................................................................................
Section 57.10: Positional Access Operations 352 ...........................................................................................................
Section 57.11: Iterating over elements in a list 354 ........................................................................................................
Section 57.12: Removing elements from list B that are present in the list A 354 .......................................................
Chapter 58: Sets 356 ........................................................................................................................................................
Section 58.1: Initialization 356 ..........................................................................................................................................
Section 58.2: Basics of Set 356 ........................................................................................................................................
Section 58.3: Types and Usage of Sets 357 ...................................................................................................................
Section 58.4: Create a list from an existing Set 358 .....................................................................................................
Section 58.5: Eliminating duplicates using Set 358 .......................................................................................................
Section 58.6: Declaring a HashSet with values 359 ......................................................................................................
Chapter 59: List vs Set 360 ...........................................................................................................................................
Section 59.1: List vs Set 360 .............................................................................................................................................
Chapter 60: Maps 361 .....................................................................................................................................................
Section 60.1: Iterating Map Entries Eciently 361 .........................................................................................................
Section 60.2: Usage of HashMap 363 ............................................................................................................................
Section 60.3: Using Default Methods of Map from Java 8 364 ...................................................................................
Section 60.4: Iterating through the contents of a Map 366 .........................................................................................
Section 60.5: Merging, combine and composing Maps 367 ........................................................................................
Section 60.6: Add multiple items 368 ..............................................................................................................................
Section 60.7: Creating and Initializing Maps 369 ...........................................................................................................
Section 60.8: Check if key exists 371 ..............................................................................................................................
Section 60.9: Add an element 371 ..................................................................................................................................
Section 60.10: Clear the map 372 ....................................................................................................................................
Section 60.11: Use custom object as key 372 .................................................................................................................
Chapter 61: LinkedHashMap 373 ................................................................................................................................
Section 61.1: Java LinkedHashMap class 373 ................................................................................................................
Chapter 62: TreeMap and TreeSet 374 ..................................................................................................................
Section 62.1: TreeMap of a simple Java type 374 ........................................................................................................
Section 62.2: TreeSet of a simple Java Type 374 .........................................................................................................
Section 62.3: TreeMap/TreeSet of a custom Java type 375 .......................................................................................
Section 62.4: TreeMap and TreeSet Thread Safety 376 ..............................................................................................
Chapter 63: SortedMap 378 .........................................................................................................................................
Section 63.1: Introduction to sorted Map 378 ................................................................................................................
Chapter 64: WeakHashMap 379 ................................................................................................................................
Section 64.1: Concepts of WeakHashmap 379 ..............................................................................................................
Chapter 65: Hashtable 380 ...........................................................................................................................................
Section 65.1: Hashtable 380 .............................................................................................................................................
Chapter 66: Optional 381 ...............................................................................................................................................
Section 66.1: Map 381 .......................................................................................................................................................
Section 66.2: Return default value if Optional is empty 382 ........................................................................................
Section 66.3: Throw an exception, if there is no value 382 ..........................................................................................
Section 66.4: Lazily provide a default value using a Supplier 382 ..............................................................................
Section 66.5: Filter 383 .....................................................................................................................................................
Section 66.6: Using Optional containers for primitive number types 383 ..................................................................
Section 66.7: Run code only if there is a value present 384 .........................................................................................
Section 66.8: FlatMap 384 ................................................................................................................................................
Chapter 67: Object References 385 .........................................................................................................................
Section 67.1: Object References as method parameters 385 ......................................................................................
Chapter 68: Exceptions and exception handling 388 ......................................................................................
Section 68.1: Catching an exception with try-catch 388 ...............................................................................................
Section 68.2: The try-with-resources statement 389 ....................................................................................................
Section 68.3: Custom Exceptions 392 .............................................................................................................................
Section 68.4: Handling InterruptedException 394 .........................................................................................................
Section 68.5: Return statements in try catch block 395 ...............................................................................................
Section 68.6: Introduction 396 .........................................................................................................................................
Section 68.7: The Java Exception Hierarchy - Unchecked and Checked Exceptions 397 ........................................
Section 68.8: Creating and reading stacktraces 400 ....................................................................................................
Section 68.9: Throwing an exception 403 ......................................................................................................................
Section 68.10: Advanced features of Exceptions 405 ...................................................................................................
Section 68.11: The try-finally and try-catch-finally statements 406 ............................................................................
Section 68.12: The 'throws' clause in a method declaration 408 .................................................................................
Chapter 69: Calendar and its Subclasses 410 .....................................................................................................
Section 69.1: Creating Calendar objects 410 .................................................................................................................
Section 69.2: Increasing / Decreasing calendar fields 410 ..........................................................................................
Section 69.3: Subtracting calendars 410 ........................................................................................................................
Section 69.4: Finding AM/PM 410 ...................................................................................................................................
Chapter 70: Using the static keyword 412 ...........................................................................................................
Section 70.1: Reference to non-static member from static context 412 ....................................................................
Section 70.2: Using static to declare constants 412 .....................................................................................................
Chapter 71: Properties Class 414 ...............................................................................................................................
Section 71.1: Loading properties 414 ...............................................................................................................................
Section 71.2: Saving Properties as XML 414 ...................................................................................................................
Section 71.3: Property files caveat: trailing whitespace 415 .........................................................................................
Chapter 72: Lambda Expressions 418 .....................................................................................................................
Section 72.1: Introduction to Java lambdas 418 ...........................................................................................................
Section 72.2: Using Lambda Expressions to Sort a Collection 421 .............................................................................
Section 72.3: Method References 422 ............................................................................................................................
Section 72.4: Implementing multiple interfaces 424 .....................................................................................................
Section 72.5: Lambda - Listener Example 424 ..............................................................................................................
Section 72.6: Java Closures with lambda expressions 425 ..........................................................................................
Section 72.7: Lambdas and memory utilization 426 .....................................................................................................
Section 72.8: Using lambda expression with your own functional interface 426 ......................................................
Section 72.9: Traditional style to Lambda style 427 .....................................................................................................
Section 72.10: `return` only returns from the lambda, not the outer method 428 .....................................................
Section 72.11: Lambdas and Execute-around Pattern 430 ...........................................................................................
Section 72.12: Using lambda expressions & predicates to get a certain value(s) from a list 430 ...........................
Chapter 73: Basic Control Structures 432 .............................................................................................................
Section 73.1: Switch statement 432 .................................................................................................................................
Section 73.2: do...while Loop 433 .....................................................................................................................................
Section 73.3: For Each 434 ...............................................................................................................................................
Section 73.4: Continue Statement in Java 435 ..............................................................................................................
Section 73.5: If / Else If / Else Control 435 .....................................................................................................................
Section 73.6: For Loops 435 .............................................................................................................................................
Section 73.7: Ternary Operator 436 ...............................................................................................................................
Section 73.8: Try ... Catch ... Finally 437 ...........................................................................................................................
Section 73.9: Break 437 ....................................................................................................................................................
Section 73.10: While Loops 438 .......................................................................................................................................
Section 73.11: If / Else 438 ................................................................................................................................................
Section 73.12: Nested break / continue 438 ..................................................................................................................
Chapter 74: BueredWriter 440 ...............................................................................................................................
Section 74.1: Write a line of text to File 440 ....................................................................................................................
Chapter 75: New File I/O 441 ......................................................................................................................................
Section 75.1: Creating paths 441 .....................................................................................................................................
Section 75.2: Manipulating paths 441 .............................................................................................................................
Section 75.3: Retrieving information about a path 441 ................................................................................................
Section 75.4: Retrieving information using the filesystem 442 ....................................................................................
Section 75.5: Reading files 443 ........................................................................................................................................
Section 75.6: Writing files 443 ..........................................................................................................................................
Chapter 76: File I/O 444 .................................................................................................................................................
Section 76.1: Migrating from java.io.File to Java 7 NIO (java.nio.file.Path) 444 ..........................................................
Section 76.2: Reading an image from a file 446 ...........................................................................................................
Section 76.3: File Read/Write Using FileInputStream/FileOutputStream 446 ...........................................................
Section 76.4: Reading all bytes to a byte[] 447 ............................................................................................................
Section 76.5: Copying a file using Channel 448 .............................................................................................................
Section 76.6: Writing a byte[] to a file 448 ....................................................................................................................
Section 76.7: Stream vs Writer/Reader API 449 ............................................................................................................
Section 76.8: Reading a file with a Scanner 450 ...........................................................................................................
Section 76.9: Copying a file using InputStream and OutputStream 451 ....................................................................
Section 76.10: Reading from a binary file 451 ...............................................................................................................
Section 76.11: Reading a file using Channel and Buer 451 .........................................................................................
Section 76.12: Adding Directories 452 .............................................................................................................................
Section 76.13: Blocking or redirecting standard output / error 453 ............................................................................
Section 76.14: Reading a whole file at once 454 ............................................................................................................
Section 76.15: Locking 454 ...............................................................................................................................................
Section 76.16: Reading a file using BueredInputStream 454 .....................................................................................
Section 76.17: Iterate over a directory printing subdirectories in it 455 ......................................................................
Section 76.18: Writing a file using Channel and Buer 455 ..........................................................................................
Section 76.19: Writing a file using PrintStream 456 .......................................................................................................
Section 76.20: Iterating over a directory and filter by file extension 456 ...................................................................
Section 76.21: Accessing the contents of a ZIP file 457 ................................................................................................
Chapter 77: Scanner 458 ...............................................................................................................................................
Section 77.1: General Pattern that does most commonly asked about tasks 458 ....................................................
Section 77.2: Using custom delimiters 460 ....................................................................................................................
Section 77.3: Reading system input using Scanner 460 ...............................................................................................
Section 77.4: Reading file input using Scanner 460 ......................................................................................................
Section 77.5: Read the entire input as a String using Scanner 461 .............................................................................
Section 77.6: Carefully Closing a Scanner 461 ..............................................................................................................
Section 77.7: Read an int from the command line 462 ................................................................................................
Chapter 78: Interfaces 463 ...........................................................................................................................................
Section 78.1: Implementing multiple interfaces 463 ......................................................................................................
Section 78.2: Declaring and Implementing an Interface 464 ......................................................................................
Section 78.3: Extending an interface 464 .......................................................................................................................
Section 78.4: Usefulness of interfaces 465 ....................................................................................................................
Section 78.5: Default methods 467 .................................................................................................................................
Section 78.6: Modifiers in Interfaces 469 ........................................................................................................................
Section 78.7: Using Interfaces with Generics 469 ..........................................................................................................
Section 78.8: Strengthen bounded type parameters 472 ............................................................................................
Section 78.9: Implementing interfaces in an abstract class 472 .................................................................................
Chapter 79: Regular Expressions 474 .....................................................................................................................
Section 79.1: Using capture groups 474 .........................................................................................................................
Section 79.2: Using regex with custom behaviour by compiling the Pattern with flags 475 ....................................
Section 79.3: Escape Characters 475 .............................................................................................................................
Section 79.4: Not matching a given string 476 ..............................................................................................................
Section 79.5: Matching with a regex literal 476 .............................................................................................................
Section 79.6: Matching a backslash 476 ........................................................................................................................
Chapter 80: Comparable and Comparator 478 ................................................................................................
Section 80.1: Sorting a List using Comparable<T> or a Comparator<T> 478 ............................................................
Section 80.2: The compareTo and compare Methods 481 .........................................................................................
Section 80.3: Natural (comparable) vs explicit (comparator) sorting 482 ................................................................
Section 80.4: Creating a Comparator using comparing method 483 ........................................................................
Section 80.5: Sorting Map entries 483 ............................................................................................................................
Chapter 81: Java Floating Point Operations 485 ..............................................................................................
Section 81.1: Comparing floating point values 485 ........................................................................................................
Section 81.2: OverFlow and UnderFlow 487 ..................................................................................................................
Section 81.3: Formatting the floating point values 488 ................................................................................................
Section 81.4: Strict Adherence to the IEEE Specification 488 .......................................................................................
Chapter 82: Currency and Money 490 ....................................................................................................................
Section 82.1: Add custom currency 490 .........................................................................................................................
Chapter 83: Object Cloning 491 ..................................................................................................................................
Section 83.1: Cloning performing a deep copy 491 ......................................................................................................
Section 83.2: Cloning using a copy factory 492 ............................................................................................................
Section 83.3: Cloning using a copy constructor 492 .....................................................................................................
Section 83.4: Cloning by implementing Clonable interface 492 ..................................................................................
Section 83.5: Cloning performing a shallow copy 493 .................................................................................................
Chapter 84: Recursion 495 ...........................................................................................................................................
Section 84.1: The basic idea of recursion 495 ................................................................................................................
Section 84.2: Deep recursion is problematic in Java 495 ............................................................................................
Section 84.3: Types of Recursion 497 ............................................................................................................................
Section 84.4: Computing the Nth Fibonacci Number 497 ............................................................................................
Section 84.5: StackOverflowError & recursion to loop 498 ..........................................................................................
Section 84.6: Computing the Nth power of a number 500 ...........................................................................................
Section 84.7: Traversing a Tree data structure with recursion 500 ............................................................................
Section 84.8: Reverse a string using Recursion 501 .....................................................................................................
Section 84.9: Computing the sum of integers from 1 to N 501 ....................................................................................
Chapter 85: Converting to and from Strings 502 .............................................................................................
Section 85.1: Converting String to other datatypes 502 ...............................................................................................
Section 85.2: Conversion to / from bytes 503 ...............................................................................................................
Section 85.3: Base64 Encoding / Decoding 503 ...........................................................................................................
Section 85.4: Converting other datatypes to String 504 ..............................................................................................
Section 85.5: Getting a `String` from an `InputStream` 505 ..........................................................................................
Chapter 86: Random Number Generation 506 ...................................................................................................
Section 86.1: Pseudo Random Numbers 506 .................................................................................................................
Section 86.2: Pseudo Random Numbers in Specific Range 506 .................................................................................
Section 86.3: Generating cryptographically secure pseudorandom numbers 507 ...................................................
Section 86.4: Generating Random Numbers with a Specified Seed 507 ....................................................................
Section 86.5: Select random numbers without duplicates 508 ....................................................................................
Section 86.6: Generating Random number using apache-common lang3 509 ........................................................
Chapter 87: Singletons 510 ..........................................................................................................................................
Section 87.1: Enum Singleton 510 ....................................................................................................................................
Section 87.2: Singleton without use of Enum (eager initialization) 510 ......................................................................
Section 87.3: Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation 511 ............
Section 87.4: Thread safe Singleton with double checked locking 511 ......................................................................
Section 87.5: Extending singleton (singleton inheritance) 512 ....................................................................................
Chapter 88: Autoboxing 515 ........................................................................................................................................
Section 88.1: Using int and Integer interchangeably 515 .............................................................................................
Section 88.2: Auto-unboxing may lead to NullPointerException 516 ..........................................................................
Section 88.3: Using Boolean in if statement 516 ...........................................................................................................
Section 88.4: Dierent Cases When Integer and int can be used interchangeably 516 ..........................................
Section 88.5: Memory and Computational Overhead of Autoboxing 518 .................................................................
Chapter 89: 2D Graphics in Java 519 ......................................................................................................................
Section 89.1: Example 1: Draw and Fill a Rectangle Using Java 519 ...........................................................................
Section 89.2: Example 2: Drawing and Filling Oval 521 ................................................................................................
Chapter 90: JAXB 522 ......................................................................................................................................................
Section 90.1: Reading an XML file (unmarshalling) 522 ...............................................................................................
Section 90.2: Writing an XML file (marshalling an object) 522 ....................................................................................
Section 90.3: Manual field/property XML mapping configuration 523 ......................................................................
Section 90.4: Binding an XML namespace to a serializable Java class 524 ..............................................................
Section 90.5: Using XmlAdapter to generate desired xml format 524 .......................................................................
Section 90.6: Using XmlAdapter to trim string 526 .......................................................................................................
Section 90.7: Automatic field/property XML mapping configuration (@XmlAccessorType) 526 ...........................
Section 90.8: Specifying a XmlAdapter instance to (re)use existing data 528 ..........................................................
Chapter 91: Class - Java Reflection 531 .................................................................................................................
Section 91.1: getClass() method of Object class 531 .....................................................................................................
Chapter 92: Networking 532 ........................................................................................................................................
Section 92.1: Basic Client and Server Communication using a Socket 532 ................................................................
Section 92.2: Basic Client/Server Communication using UDP (Datagram) 534 .......................................................
Section 92.3: Loading TrustStore and KeyStore from InputStream 535 ....................................................................
Section 92.4: Socket example - reading a web page using a simple socket 536 ......................................................
Section 92.5: Temporarily disable SSL verification (for testing purposes) 537 .........................................................
Section 92.6: Downloading a file using Channel 537 ....................................................................................................
Section 92.7: Multicasting 538 .........................................................................................................................................
Chapter 93: NIO - Networking 541 ............................................................................................................................
Section 93.1: Using Selector to wait for events (example with OP_CONNECT) 541 ..................................................
Chapter 94: HttpURLConnection 543 ......................................................................................................................
Section 94.1: Get response body from a URL as a String 543 .....................................................................................
Section 94.2: POST data 544 ...........................................................................................................................................
Section 94.3: Delete resource 544 ..................................................................................................................................
Section 94.4: Check if resource exists 545 .....................................................................................................................
Chapter 95: JAX-WS 547 ................................................................................................................................................
Section 95.1: Basic Authentication 547 ...........................................................................................................................
Chapter 96: Nashorn JavaScript engine 548 .......................................................................................................
Section 96.1: Execute JavaScript file 548 .......................................................................................................................
Section 96.2: Intercept script output 548 .......................................................................................................................
Section 96.3: Hello Nashorn 549 .....................................................................................................................................
Section 96.4: Evaluate Arithmetic Strings 549 ...............................................................................................................
Section 96.5: Set global variables 549 ............................................................................................................................
Section 96.6: Set and get global variables 550 .............................................................................................................
Section 96.7: Usage of Java objects in JavaScript in Nashorn 550 ............................................................................
Section 96.8: Implementing an interface from script 551 ............................................................................................
Chapter 97: Java Native Interface 552 ..................................................................................................................
Section 97.1: Calling C++ methods from Java 552 ........................................................................................................
Section 97.2: Calling Java methods from C++ (callback) 553 .....................................................................................
Section 97.3: Loading native libraries 555 .....................................................................................................................
Chapter 98: Functional Interfaces 557 ...................................................................................................................
Section 98.1: List of standard Java Runtime Library functional interfaces by signature 557 ..................................
Chapter 99: Fluent Interface 558 ..............................................................................................................................
Section 99.1: Fluent programming style 558 .................................................................................................................
Section 99.2: Truth - Fluent Testing Framework 559 ....................................................................................................
Chapter 100: Dequeue Interface 560 .......................................................................................................................
Section 100.1: Adding Elements to Deque 560 ...............................................................................................................
Section 100.2: Removing Elements from Deque 560 ....................................................................................................
Section 100.3: Retrieving Element without Removing 560 ...........................................................................................
Section 100.4: Iterating through Deque 560 ..................................................................................................................
Chapter 101: Remote Method Invocation (RMI) 562 .........................................................................................
Section 101.1: Callback: invoking methods on a "client" 562 .........................................................................................
Section 101.2: Simple RMI example with Client and Server implementation 566 .......................................................
Section 101.3: Client-Server: invoking methods in one JVM from another 568 ..........................................................
Chapter 102: Iterator and Iterable 571 ..................................................................................................................
Section 102.1: Removing elements using an iterator 571 .............................................................................................
Section 102.2: Creating your own Iterable 571 ..............................................................................................................
Section 102.3: Using Iterable in for loop 572 ..................................................................................................................
Section 102.4: Using the raw iterator 573 ......................................................................................................................
Chapter 103: Reflection API 574 .................................................................................................................................
Section 103.1: Dynamic Proxies 574 ................................................................................................................................
Section 103.2: Introduction 575 .......................................................................................................................................
Section 103.3: Evil Java hacks with Reflection 576 .......................................................................................................
Section 103.4: Misuse of Reflection API to change private and final variables 578 ...................................................
Section 103.5: Getting and Setting fields 579 .................................................................................................................
Section 103.6: Call constructor 580 .................................................................................................................................
Section 103.7: Call constructor of nested class 581 ......................................................................................................
Section 103.8: Invoking a method 581 ............................................................................................................................
Section 103.9: Get Class given its (fully qualified) name 582 .......................................................................................
Section 103.10: Getting the Constants of an Enumeration 582 ....................................................................................
Section 103.11: Call overloaded constructors using reflection 583 ...............................................................................
Chapter 104: ByteBuer 585 .......................................................................................................................................
Section 104.1: Basic Usage - Using DirectByteBuer 585 ............................................................................................
Section 104.2: Basic Usage - Creating a ByteBuer 585 .............................................................................................
Section 104.3: Basic Usage - Write Data to the Buer 586 ..........................................................................................
Chapter 105: Applets 587 ...............................................................................................................................................
Section 105.1: Minimal Applet 587 ...................................................................................................................................
Section 105.2: Creating a GUI 588 ...................................................................................................................................
Section 105.3: Open links from within the applet 588 ...................................................................................................
Section 105.4: Loading images, audio and other resources 589 .................................................................................
Chapter 106: Expressions 591 ......................................................................................................................................
Section 106.1: Operator Precedence 591 ........................................................................................................................
Section 106.2: Expression Basics 592 ..............................................................................................................................
Section 106.3: Expression evaluation order 593 ............................................................................................................
Section 106.4: Constant Expressions 594 .......................................................................................................................
Chapter 107: JSON in Java 596 ..................................................................................................................................
Section 107.1: Using Jackson Object Mapper 596 .........................................................................................................
Section 107.2: JSON To Object (Gson Library) 597 .......................................................................................................
Section 107.3: JSONObject.NULL 597 .............................................................................................................................
Section 107.4: JSON Builder - chaining methods 598 ...................................................................................................
Section 107.5: Object To JSON (Gson Library) 598 .......................................................................................................
Section 107.6: JSON Iteration 598 ...................................................................................................................................
Section 107.7: optXXX vs getXXX methods 599 .............................................................................................................
Section 107.8: Extract single element from JSON 599 ..................................................................................................
Section 107.9: JsonArray to Java List (Gson Library) 599 ...........................................................................................
Section 107.10: Encoding data as JSON 600 ..................................................................................................................
Section 107.11: Decoding JSON data 600 .......................................................................................................................
Chapter 108: XML Parsing using the JAXP APIs 602 .........................................................................................
Section 108.1: Parsing a document using the StAX API 602 ..........................................................................................
Section 108.2: Parsing and navigating a document using the DOM API 603 .............................................................
Chapter 109: XML XPath Evaluation 605 ................................................................................................................
Section 109.1: Parsing multiple XPath Expressions in a single XML 605 ......................................................................
Section 109.2: Parsing single XPath Expression multiple times in an XML 605 ..........................................................
Section 109.3: Evaluating a NodeList in an XML document 606 ..................................................................................
Chapter 110: XOM - XML Object Model 607 ...........................................................................................................
Section 110.1: Reading a XML file 607 ..............................................................................................................................
Section 110.2: Writing to a XML File 609 .........................................................................................................................
Chapter 111: Polymorphism 612 ..................................................................................................................................
Section 111.1: Method Overriding 612 ...............................................................................................................................
Section 111.2: Method Overloading 613 ...........................................................................................................................
Section 111.3: Polymorphism and dierent types of overriding 614 ............................................................................
Section 111.4: Virtual functions 617 ..................................................................................................................................
Section 111.5: Adding behaviour by adding classes without touching existing code 618 ..........................................
Chapter 112: Encapsulation 620 ..................................................................................................................................
Section 112.1: Encapsulation to maintain invariants 620 ...............................................................................................
Section 112.2: Encapsulation to reduce coupling 621 ....................................................................................................
Chapter 113: Java Agents 622 ......................................................................................................................................
Section 113.1: Modifying classes with agents 622 ...........................................................................................................
Section 113.2: Adding an agent at runtime 622 .............................................................................................................
Section 113.3: Setting up a basic agent 623 ....................................................................................................................
Chapter 114: Varargs (Variable Argument) 624 ................................................................................................
Section 114.1: Working with Varargs parameters 624 ...................................................................................................
Section 114.2: Specifying a varargs parameter 624 ......................................................................................................
Chapter 115: Logging (java.util.logging) 625 .......................................................................................................
Section 115.1: Logging complex messages (eciently) 625 .........................................................................................
Section 115.2: Using the default logger 626 ...................................................................................................................
Section 115.3: Logging levels 627 ....................................................................................................................................
Chapter 116: log4j / log4j2 629 ..................................................................................................................................
Section 116.1: Properties-File to log to DB 629 ...............................................................................................................
Section 116.2: How to get Log4j 629 ................................................................................................................................
Section 116.3: Setting up property file 630 ......................................................................................................................
Section 116.4: Basic log4j2.xml configuration file 631 ...................................................................................................
Section 116.5: How to use Log4j in Java code 631 ........................................................................................................
Section 116.6: Migrating from log4j 1.x to 2.x 632 ...........................................................................................................
Section 116.7: Filter Logoutput by level (log4j 1.x) 633 ...................................................................................................
Chapter 117: Oracle Ocial Code Standard 634 ...............................................................................................
Section 117.1: Naming Conventions 634 ..........................................................................................................................
Section 117.2: Class Structure 635 ...................................................................................................................................
Section 117.3: Annotations 636 .........................................................................................................................................
Section 117.4: Import statements 636 .............................................................................................................................
Section 117.5: Braces 637 .................................................................................................................................................
Section 117.6: Redundant Parentheses 638 ....................................................................................................................
Section 117.7: Modifiers 638 ..............................................................................................................................................
Section 117.8: Indentation 639 ..........................................................................................................................................
Section 117.9: Literals 639 .................................................................................................................................................
Section 117.10: Package declaration 639 ........................................................................................................................
Section 117.11: Lambda Expressions 639 .........................................................................................................................
Section 117.12: Java Source Files 640 ..............................................................................................................................
Section 117.13: Wrapping statements 640 .......................................................................................................................
Section 117.14: Wrapping Method Declarations 641 ......................................................................................................
Section 117.15: Wrapping Expressions 641 ......................................................................................................................
Section 117.16: Whitespace 642 ........................................................................................................................................
Section 117.17: Special Characters 642 ............................................................................................................................
Section 117.18: Variable Declarations 643 .......................................................................................................................
Chapter 118: Character encoding 644 .....................................................................................................................
Section 118.1: Reading text from a file encoded in UTF-8 644 .....................................................................................
Section 118.2: Writing text to a file in UTF-8 644 ............................................................................................................
Section 118.3: Getting byte representation of a string in UTF-8 645 ...........................................................................
Chapter 119: Apache Commons Lang 646 .............................................................................................................
Section 119.1: Implement equals() method 646 ..............................................................................................................
Section 119.2: Implement hashCode() method 646 .......................................................................................................
Section 119.3: Implement toString() method 647 ...........................................................................................................
Chapter 120: Localization and Internationalization 649 ................................................................................
Section 120.1: Locale 649 ..................................................................................................................................................
Section 120.2: Automatically formatted Dates using "locale" 650 ..............................................................................
Section 120.3: String Comparison 650 ............................................................................................................................
Chapter 121: Parallel programming with Fork/Join framework 651 ......................................................
Section 121.1: Fork/Join Tasks in Java 651 ....................................................................................................................
Chapter 122: Non-Access Modifiers 653 .................................................................................................................
Section 122.1: final 653 ......................................................................................................................................................
Section 122.2: static 654 ...................................................................................................................................................
Section 122.3: abstract 655 ..............................................................................................................................................
Section 122.4: strictfp 656 ................................................................................................................................................
Section 122.5: volatile 656 ................................................................................................................................................
Section 122.6: synchronized 657 .....................................................................................................................................
Section 122.7: transient 658 .............................................................................................................................................
Chapter 123: Process 659 ...............................................................................................................................................
Section 123.1: Pitfall: Runtime.exec, Process and ProcessBuilder don't understand shell syntax 659 ......................
Section 123.2: Simple example (Java version < 1.5) 661 ...............................................................................................
Chapter 124: Java Native Access 662 .....................................................................................................................
Section 124.1: Introduction to JNA 662 ...........................................................................................................................
Chapter 125: Modules 663 ..............................................................................................................................................
Section 125.1: Defining a basic module 663 ...................................................................................................................
Chapter 126: Concurrent Programming (Threads) 664 ..................................................................................
Section 126.1: Callable and Future 664 ...........................................................................................................................
Section 126.2: CountDownLatch 665 ...............................................................................................................................
Section 126.3: Basic Multithreading 667 .........................................................................................................................
Section 126.4: Locks as Synchronisation aids 668 .........................................................................................................
Section 126.5: Semaphore 669 ........................................................................................................................................
Section 126.6: Synchronization 670 .................................................................................................................................
Section 126.7: Runnable Object 671 ................................................................................................................................
Section 126.8: Creating basic deadlocked system 672 .................................................................................................
Section 126.9: Creating a java.lang.Thread instance 674 .............................................................................................
Section 126.10: Atomic operations 675 ...........................................................................................................................
Section 126.11: Exclusive write / Concurrent read access 676 ......................................................................................
Section 126.12: Producer-Consumer 677 ........................................................................................................................
Section 126.13: Visualizing read/write barriers while using synchronized / volatile 679 ...........................................
Section 126.14: Get status of all threads started by your program excluding system threads 680 ........................
Section 126.15: Using ThreadLocal 681 ...........................................................................................................................
Section 126.16: Multiple producer/consumer example with shared global queue 682 .............................................
Section 126.17: Add two `int` arrays using a Threadpool 683 .......................................................................................
Section 126.18: Pausing Execution 684 ............................................................................................................................
Section 126.19: Thread Interruption / Stopping Threads 685 .......................................................................................
Chapter 127: Executor, ExecutorService and Thread pools 688 ................................................................
Section 127.1: ThreadPoolExecutor 688 ..........................................................................................................................
Section 127.2: Retrieving value from computation - Callable 689 ...............................................................................
Section 127.3: submit() vs execute() exception handling dierences 690 ..................................................................
Section 127.4: Handle Rejected Execution 692 ..............................................................................................................
Section 127.5: Fire and Forget - Runnable Tasks 692 ...................................................................................................
Section 127.6: Use cases for dierent types of concurrency constructs 693 .............................................................
Section 127.7: Wait for completion of all tasks in ExecutorService 694 ......................................................................
Section 127.8: Use cases for dierent types of ExecutorService 696 ..........................................................................
Section 127.9: Scheduling tasks to run at a fixed time, after a delay or repeatedly 698 ..........................................
Section 127.10: Using Thread Pools 699 .........................................................................................................................
Chapter 128: ThreadLocal 700 ....................................................................................................................................
Section 128.1: Basic ThreadLocal usage 700 ..................................................................................................................
Section 128.2: ThreadLocal Java 8 functional initialization 701 ..................................................................................
Section 128.3: Multiple threads with one shared object 702 ........................................................................................
Chapter 129: Using ThreadPoolExecutor in MultiThreaded applications. 704 ....................................
Section 129.1: Performing Asynchronous Tasks Where No Return Value Is Needed Using a Runnable Class
Instance 704 ..............................................................................................................................................................
Section 129.2: Performing Asynchronous Tasks Where a Return Value Is Needed Using a Callable Class
Instance 705 ..............................................................................................................................................................
Section 129.3: Defining Asynchronous Tasks Inline using Lambdas 708 ....................................................................
Chapter 130: Common Java Pitfalls 710 ................................................................................................................
Section 130.1: Pitfall: using == to compare primitive wrappers objects such as Integer 710 .....................................
Section 130.2: Pitfall: using == to compare strings 710 .................................................................................................
Section 130.3: Pitfall: forgetting to free resources 712 .................................................................................................
Section 130.4: Pitfall: testing a file before attempting to open it 713 ..........................................................................
Section 130.5: Pitfall: thinking of variables as objects 714 ...........................................................................................
Section 130.6: Pitfall: memory leaks 717 ........................................................................................................................
Section 130.7: Pitfall: Not understanding that String is an immutable class 718 .......................................................
Section 130.8: Pitfall: combining assignment and side-eects 719 .............................................................................
Chapter 131: Java Pitfalls - Exception usage 720 ..............................................................................................
Section 131.1: Pitfall - Catching Throwable, Exception, Error or RuntimeException 720 ............................................
Section 131.2: Pitfall - Ignoring or squashing exceptions 721 .......................................................................................
Section 131.3: Pitfall - Throwing Throwable, Exception, Error or RuntimeException 722 ...........................................
Section 131.4: Pitfall - Using exceptions for normal flowcontrol 723 ...........................................................................
Section 131.5: Pitfall - Directly subclassing `Throwable` 724 .........................................................................................
Section 131.6: Pitfall - Catching InterruptedException 724 ............................................................................................
Section 131.7: Pitfall - Excessive or inappropriate stacktraces 726 ..............................................................................
Chapter 132: Java Pitfalls - Language syntax 727 ...........................................................................................
Section 132.1: Pitfall - Missing a ‘break’ in a 'switch' case 727 ......................................................................................
Section 132.2: Pitfall - Declaring classes with the same names as standard classes 727 ........................................
Section 132.3: Pitfall - Leaving out braces: the "dangling if" and "dangling else" problems 728 .............................
Section 132.4: Pitfall - Octal literals 730 ..........................................................................................................................
Section 132.5: Pitfall - Using '==' to test a boolean 730 .................................................................................................
Section 132.6: Pitfall - Ignoring method visibility 731 ....................................................................................................
Section 132.7: Pitfall: Using 'assert' for argument or user input validation 731 .........................................................
Section 132.8: Pitfall - Wildcard imports can make your code fragile 732 .................................................................
Section 132.9: Pitfall - Misplaced semicolons and missing braces 733 .......................................................................
Section 132.10: Pitfall - Overloading instead of overriding 734 ....................................................................................
Section 132.11: Pitfall of Auto-Unboxing Null Objects into Primitives 735 ....................................................................
Chapter 133: Java Pitfalls - Threads and Concurrency 736 .........................................................................
Section 133.1: Pitfall - Extending 'java.lang.Thread' 736 ................................................................................................
Section 133.2: Pitfall - Too many threads makes an application slower 737 .............................................................
Section 133.3: Pitfall: incorrect use of wait() / notify() 738 ...........................................................................................
Section 133.4: Pitfall: Shared variables require proper synchronization 738 ..............................................................
Section 133.5: Pitfall - Thread creation is relatively expensive 741 .............................................................................
Chapter 134: Java Pitfalls - Nulls and NullPointerException 744 .............................................................
Section 134.1: Pitfall - "Making good" unexpected nulls 744 .........................................................................................
Section 134.2: Pitfall - Using null to represent an empty array or collection 745 ......................................................
Section 134.3: Pitfall - Not checking if an I/O stream isn't even initialized when closing it 746 ...............................
Section 134.4: Pitfall - Returning null instead of throwing an exception 746 ..............................................................
Section 134.5: Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions 747 ................
Section 134.6: Pitfall - Using "Yoda notation" to avoid NullPointerException 748 ......................................................
Chapter 135: Java Pitfalls - Performance Issues 749 ......................................................................................
Section 135.1: Pitfall - String concatenation in a loop does not scale 749 ..................................................................
Section 135.2: Pitfall - Using size() to test if a collection is empty is inecient 750 ..................................................
Section 135.3: Pitfall - Interning strings so that you can use == is a bad idea 750 .....................................................
Section 135.4: Pitfall - Using 'new' to create primitive wrapper instances is inecient 752 .....................................
Section 135.5: Pitfall - Eciency concerns with regular expressions 752 ...................................................................
Section 135.6: Pitfall - Small reads / writes on unbuered streams are inecient 755 ...........................................
Section 135.7: Pitfall - Over-use of primitive wrapper types is inecient 757 ............................................................
Section 135.8: Pitfall - The overheads of creating log messages 758 .........................................................................
Section 135.9: Pitfall - Iterating a Map's keys can be inecient 759 ...........................................................................
Section 135.10: Pitfall - Calling System.gc() is inecient 759 .......................................................................................
Section 135.11: Pitfall - Calling 'new String(String)' is inecient 760 ............................................................................
Chapter 136: ServiceLoader 761 ................................................................................................................................
Section 136.1: Simple ServiceLoader Example 761 ........................................................................................................
Section 136.2: Logger Service 762 ...................................................................................................................................
Chapter 137: Classloaders 764 ....................................................................................................................................
Section 137.1: Implementing a custom classLoader 764 ...............................................................................................
Section 137.2: Loading an external .class file 764 ..........................................................................................................
Section 137.3: Instantiating and using a classloader 765 .............................................................................................
Chapter 138: Creating Images Programmatically 767 ...................................................................................
Section 138.1: Creating a simple image programmatically and displaying it 767 .....................................................
Section 138.2: Save an Image to disk 768 ......................................................................................................................
Section 138.3: Setting individual pixel's color in BueredImage 768 ...........................................................................
Section 138.4: Specifying image rendering quality 769 ................................................................................................
Section 138.5: Creating an image with BueredImage class 771 ...............................................................................
Section 138.6: Editing and re-using image with BueredImage 772 ...........................................................................
Section 138.7: How to scale a BueredImage 773 ........................................................................................................
Chapter 139: Atomic Types 774 ..................................................................................................................................
Section 139.1: Creating Atomic Types 774 ......................................................................................................................
Section 139.2: Motivation for Atomic Types 774 ............................................................................................................
Chapter 140: RSA Encryption 778 .............................................................................................................................
Section 140.1: An example using a hybrid cryptosystem consisting of OAEP and GCM 778 ....................................
Chapter 141: Secure objects 783 ................................................................................................................................
Section 141.1: SealedObject (javax.crypto.SealedObject) 783 ......................................................................................
Section 141.2: SignedObject (java.security.SignedObject) 783 .....................................................................................
Chapter 142: Security & Cryptography 785 .........................................................................................................
Section 142.1: Compute Cryptographic Hashes 785 ......................................................................................................
Section 142.2: Encrypt and Decrypt Data with Public / Private Keys 785 ..................................................................
Section 142.3: Generate Cryptographically Random Data 786 ...................................................................................
Section 142.4: Generate Public / Private Key Pairs 786 ................................................................................................
Section 142.5: Compute and Verify Digital Signatures 787 ..........................................................................................
Chapter 143: Security & Cryptography 788 .........................................................................................................
Section 143.1: The JCE 788 ...............................................................................................................................................
Section 143.2: Keys and Key Management 788 ............................................................................................................
Section 143.3: Common Java vulnerabilities 788 ..........................................................................................................
Section 143.4: Networking Concerns 788 .......................................................................................................................
Section 143.5: Randomness and You 788 .......................................................................................................................
Section 143.6: Hashing and Validation 788 ....................................................................................................................
Chapter 144: SecurityManager 790 .........................................................................................................................
Section 144.1: Sandboxing classes loaded by a ClassLoader 790 ...............................................................................
Section 144.2: Enabling the SecurityManager 791 ........................................................................................................
Section 144.3: Implementing policy deny rules 791 ......................................................................................................
Chapter 145: JNDI 799 ....................................................................................................................................................
Section 145.1: RMI through JNDI 799 ..............................................................................................................................
Chapter 146: sun.misc.Unsafe 803 ............................................................................................................................
Section 146.1: Instantiating sun.misc.Unsafe via reflection 803 ....................................................................................
Section 146.2: Instantiating sun.misc.Unsafe via bootclasspath 803 ...........................................................................
Section 146.3: Getting Instance of Unsafe 803 ..............................................................................................................
Section 146.4: Uses of Unsafe 804 ..................................................................................................................................
Chapter 147: Java Memory Model 805 ...................................................................................................................
Section 147.1: Motivation for the Memory Model 805 ....................................................................................................
Section 147.2: Happens-before relationships 807 .........................................................................................................
Section 147.3: How to avoid needing to understand the Memory Model 808 ............................................................
Section 147.4: Happens-before reasoning applied to some examples 809 ...............................................................
Chapter 148: Java deployment 812 .........................................................................................................................
Section 148.1: Making an executable JAR from the command line 812 .....................................................................
Section 148.2: Creating an UberJAR for an application and its dependencies 813 ..................................................
Section 148.3: Creating JAR, WAR and EAR files 814 ...................................................................................................
Section 148.4: Introduction to Java Web Start 815 .......................................................................................................
Chapter 149: Java plugin system implementations 818 ...............................................................................
Section 149.1: Using URLClassLoader 818 ......................................................................................................................
Chapter 150: JavaBean 822 .........................................................................................................................................
Section 150.1: Basic Java Bean 822 ................................................................................................................................
Chapter 151: Java SE 7 Features 823 .......................................................................................................................
Section 151.1: New Java SE 7 programming language features 823 ..........................................................................
Section 151.2: Binary Literals 823 ....................................................................................................................................
Section 151.3: The try-with-resources statement 823 ...................................................................................................
Section 151.4: Underscores in Numeric Literals 824 ......................................................................................................
Section 151.5: Type Inference for Generic Instance Creation 824 ................................................................................
Section 151.6: Strings in switch Statements 824 .............................................................................................................
Chapter 152: Java SE 8 Features 826 ......................................................................................................................
Section 152.1: New Java SE 8 programming language features 826 .........................................................................
Chapter 153: Dynamic Method Dispatch 827 .......................................................................................................
Section 153.1: Dynamic Method Dispatch - Example Code 827 ...................................................................................
Chapter 154: Generating Java Code 830 ..............................................................................................................
Section 154.1: Generate POJO From JSON 830 .............................................................................................................
Chapter 155: JShell 831 ..................................................................................................................................................
Section 155.1: Editting Snippets 831 ................................................................................................................................
Section 155.2: Entering and Exiting JShell 832 ...............................................................................................................
Section 155.3: Expressions 832 ........................................................................................................................................
Section 155.4: Methods and Classes 833 ........................................................................................................................
Section 155.5: Variables 833 ............................................................................................................................................
Chapter 156: Stack-Walking API 834 ........................................................................................................................
Section 156.1: Print all stack frames of the current thread 834 ....................................................................................
Section 156.2: Print current caller class 835 ...................................................................................................................
Section 156.3: Showing reflection and other hidden frames 835 .................................................................................
Chapter 157: Sockets 837 ..............................................................................................................................................
Section 157.1: Read from socket 837 ..............................................................................................................................
Chapter 158: Java Sockets 838 ..................................................................................................................................
Section 158.1: A simple TCP echo back server 838 ........................................................................................................
Chapter 159: FTP (File Transfer Protocol) 841 ....................................................................................................
Section 159.1: Connecting and Logging Into a FTP Server 841 ....................................................................................
Chapter 160: Using Other Scripting Languages in Java 846 .......................................................................
Section 160.1: Evaluating A JavaScript file in -scripting mode of nashorn 846 ..........................................................
Chapter 161: C++ Comparison 849 .............................................................................................................................
Section 161.1: Static Class Members 849 .........................................................................................................................
Section 161.2: Classes Defined within Other Constructs 849 ........................................................................................
Section 161.3: Pass-by-value & Pass-by-reference 850 ................................................................................................
Section 161.4: Inheritance vs Composition 851 ..............................................................................................................
Section 161.5: Outcast Downcasting 852 ........................................................................................................................
Section 161.6: Abstract Methods & Classes 852 .............................................................................................................
Chapter 162: Audio 854 ....................................................................................................................................................
Section 162.1: Play a MIDI file 854 ....................................................................................................................................
Section 162.2: Play an Audio file Looped 855 ................................................................................................................
Section 162.3: Basic audio output 855 ............................................................................................................................
Section 162.4: Bare metal sound 856 ..............................................................................................................................
Chapter 163: Java Print Service 858 ........................................................................................................................
Section 163.1: Building the Doc that will be printed 858 ................................................................................................
Section 163.2: Discovering the available print services 858 .........................................................................................
Section 163.3: Defining print request attributes 859 ......................................................................................................
Section 163.4: Listening print job request status change 859 ......................................................................................
Section 163.5: Discovering the default print service 861 ..............................................................................................
Section 163.6: Creating a print job from a print service 861 ........................................................................................
Chapter 164: CompletableFuture 863 .....................................................................................................................
Section 164.1: Simple Example of CompletableFuture 863 ...........................................................................................
Chapter 165: Runtime Commands 864 ....................................................................................................................
Section 165.1: Adding shutdown hooks 864 ....................................................................................................................
Chapter 166: Unit Testing 865 ......................................................................................................................................
Section 166.1: What is Unit Testing? 865 .........................................................................................................................
Chapter 167: Asserting 868 ...........................................................................................................................................
Section 167.1: Checking arithmetic with assert 868 .......................................................................................................
Chapter 168: Multi-Release JAR Files 869 .............................................................................................................
Section 168.1: Example of a multi-release Jar file's contents 869 ...............................................................................
Section 168.2: Creating a multi-release Jar using the jar tool 869 ..............................................................................
Section 168.3: URL of a loaded class inside a multi-release Jar 870 ..........................................................................
Chapter 169: Just in Time (JIT) compiler 872 ......................................................................................................
Section 169.1: Overview 872 .............................................................................................................................................
Chapter 170: Bytecode Modification 874 ...............................................................................................................
Section 170.1: What is Bytecode? 874 .............................................................................................................................
Section 170.2: How to edit jar files with ASM 875 ..........................................................................................................
Section 170.3: How to load a ClassNode as a Class 877 ..............................................................................................
Section 170.4: How to rename classes in a jar file 878 .................................................................................................
Section 170.5: Javassist Basic 878 ..................................................................................................................................
Chapter 171: Disassembling and Decompiling 880 ............................................................................................
Section 171.1: Viewing bytecode with javap 880 .............................................................................................................
Chapter 172: JMX 887 ......................................................................................................................................................
Section 172.1: Simple example with Platform MBean Server 887 ................................................................................
Chapter 173: Java Virtual Machine (JVM) 891 ....................................................................................................
Section 173.1: These are the basics 891 ..........................................................................................................................
Chapter 174: XJC 892 .......................................................................................................................................................
Section 174.1: Generating Java code from simple XSD file 892 ...................................................................................
Chapter 175: JVM Flags 895 .........................................................................................................................................
Section 175.1: -XXaggressive 895 ....................................................................................................................................
Section 175.2: -XXallocClearChunks 895 .........................................................................................................................
Section 175.3: -XXallocClearChunkSize 895 ....................................................................................................................
Section 175.4: -XXcallProfiling 895 ..................................................................................................................................
Section 175.5: -XXdisableFatSpin 896 .............................................................................................................................
Section 175.6: -XXdisableGCHeuristics 896 ....................................................................................................................
Section 175.7: -XXdumpSize 896 ......................................................................................................................................
Section 175.8: -XXexitOnOutOfMemory 897 ...................................................................................................................
Chapter 176: JVM Tool Interface 898 ......................................................................................................................
Section 176.1: Iterate over objects reachable from object (Heap 1.0) 898 ..................................................................
Section 176.2: Get JVMTI environment 900 ....................................................................................................................
Section 176.3: Example of initialization inside of Agent_OnLoad method 900 ..........................................................
Chapter 177: Java Memory Management 902 ....................................................................................................
Section 177.1: Setting the Heap, PermGen and Stack sizes 902 ...................................................................................
Section 177.2: Garbage collection 903 ............................................................................................................................
Section 177.3: Memory leaks in Java 905 .......................................................................................................................
Section 177.4: Finalization 906 .........................................................................................................................................
Section 177.5: Manually triggering GC 907 .....................................................................................................................
Chapter 178: Java Performance Tuning 908 .......................................................................................................
Section 178.1: An evidence-based approach to Java performance tuning 908 ........................................................
Section 178.2: Reducing amount of Strings 909 ............................................................................................................
Section 178.3: General approach 909 .............................................................................................................................
Chapter 179: Benchmarks 911 .....................................................................................................................................
Section 179.1: Simple JMH example 911 .........................................................................................................................
Chapter 180: FileUpload to AWS 914 .......................................................................................................................
Section 180.1: Upload file to s3 bucket 914 ....................................................................................................................
Chapter 181: AppDynamics and TIBCO BusinessWorks Instrumentation for Easy
Integration 916 ...................................................................................................................................................................
Section 181.1: Example of Instrumentation of all BW Applications in a Single Step for Appdynamics 916 .............
Appendix A: Installing Java (Standard Edition) 917 ........................................................................................
Section A.1: Setting %PATH% and %JAVA_HOME% after installing on Windows 917 ..............................................
Section A.2: Installing a Java JDK on Linux 918 ...........................................................................................................
Section A.3: Installing a Java JDK on macOS 920 ........................................................................................................
Section A.4: Installing a Java JDK or JRE on Windows 921 ........................................................................................
Section A.5: Configuring and switching Java versions on Linux using alternatives 922 ..........................................
Section A.6: What do I need for Java Development 923 .............................................................................................
Section A.7: Selecting an appropriate Java SE release 923 ........................................................................................
Section A.8: Java release and version naming 924 ......................................................................................................
Section A.9: Installing Oracle Java on Linux with latest tar file 924 ............................................................................
Section A.10: Post-installation checking and configuration on Linux 925 ...................................................................
Appendix B: Java Editions, Versions, Releases and Distributions 927 ...................................................
Section B.1: Dierences between Java SE JRE or Java SE JDK distributions 927 ....................................................
Section B.2: Java SE Versions 928 ..................................................................................................................................
Section B.3: Dierences between Java EE, Java SE, Java ME and JavaFX 929 .......................................................
Appendix C: The Classpath 931 ..................................................................................................................................
Section C.1: Dierent ways to specify the classpath 931 .............................................................................................
Section C.2: Adding all JARs in a directory to the classpath 931 ................................................................................
Section C.3: Load a resource from the classpath 932 ..................................................................................................
Section C.4: Classpath path syntax 932 .........................................................................................................................
Section C.5: Dynamic Classpath 933 ..............................................................................................................................
Section C.6: Mapping classnames to pathnames 933 ..................................................................................................
Section C.7: The bootstrap classpath 933 .....................................................................................................................
Section C.8: What the classpath means: how searches work 934 ..............................................................................
Appendix D: Resources (on classpath) 935 ..........................................................................................................
Section D.1: Loading default configuration 935 ............................................................................................................
Section D.2: Loading an image from a resource 935 ...................................................................................................
Section D.3: Finding and reading resources using a classloader 935 ........................................................................
Section D.4: Loading same-name resource from multiple JARs 937 .........................................................................
Credits 938 ............................................................................................................................................................................
You may also like 952 ......................................................................................................................................................
Java® Notes for Professionals 1
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
http://GoalKicker.com/JavaBook
This Java® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Java® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to web@petercv.com
Java® Notes for Professionals 2
Chapter 1: Getting started with Java
Language
Java SE Version Code Name End-of-life (free1) Release Date
Java SE 9 (Early Access)
None
future 2017-07-27
Java SE 8 Spider future 2014-03-18
Java SE 7 Dolphin 2015-04-14 2011-07-28
Java SE 6 Mustang 2013-04-16 2006-12-23
Java SE 5 Tiger 2009-11-04 2004-10-04
Java SE 1.4 Merlin prior to 2009-11-04 2002-02-06
Java SE 1.3 Kestrel prior to 2009-11-04 2000-05-08
Java SE 1.2 Playground prior to 2009-11-04 1998-12-08
Java SE 1.1
None
prior to 2009-11-04 1997-02-19
Java SE 1.0 Oak prior to 2009-11-04 1996-01-21
Section 1.1: Creating Your First Java Program
Create a new file in your text editor or IDE named HelloWorld.java. Then paste this code block into the file and
save:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Run live on Ideone
Note: For Java to recognize this as a public class (and not throw a compile time error), the filename must be the
same as the class name (HelloWorld in this example) with a .java extension. There should also be a public access
modifier before it.
Naming conventions recommend that Java classes begin with an uppercase character, and be in camel case format
(in which the first letter of each word is capitalized). The conventions recommend against underscores (_) and dollar
signs ($).
To compile, open a terminal window and navigate to the directory of HelloWorld.java:
cd /path/to/containing/folder/
Note: cd is the terminal command to change directory.
Enter javac followed by the file name and extension as follows:
$ javac HelloWorld.java
It's fairly common to get the error 'javac' is not recognized as an internal or external command, operable
program or batch file. even when you have installed the JDK and are able to run the program from IDE ex.
eclipse etc. Since the path is not added to the environment by default.
In case you get this on windows, to resolve, first try browsing to your javac.exe path, it's most probably in your
C:\Program Files\Java\jdk(version number)\bin. Then try running it with below.
Java® Notes for Professionals 3
$ C:\Program Files\Java\jdk(version number)\bin\javac HelloWorld.java
Previously when we were calling javac it was same as above command. Only in that case your OS knew where
javac resided. So let's tell it now, this way you don't have to type the whole path every-time. We would need to add
this to our PATH
To edit the PATH environment variable in Windows XP/Vista/7/8/10:
Control Panel System Advanced system settings
Switch to "Advanced" tab Environment Variables
In "System Variables", scroll down to select "PATH" Edit
You cannot undo this so be careful. First copy your existing path to notepad. Then to get the exact PATH to your
javac browse manually to the folder where javac resides and click on the address bar and then copy it. It should
look something like c:\Program Files\Java\jdk1.8.0_xx\bin
In "Variable value" field, paste this IN FRONT of all the existing directories, followed by a semi-colon (;). DO NOT
DELETE any existing entries.
Variable name : PATH
Variable value : c:\Program Files\Java\jdk1.8.0_xx\bin;[Existing Entries...]
Now this should resolve.
For Linux Based systems try here.
Note: The javac command invokes the Java compiler.
The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual
Machine (JVM). The Java programming language compiler, javac, reads source files written in the Java programming
language and compiles them into bytecode class files. Optionally, the compiler can also process annotations found
in source and class files using the Pluggable Annotation Processing API. The compiler is a command line tool but
can also be invoked using the Java Compiler API.
To run your program, enter java followed by the name of the class which contains the main method (HelloWorld in
our example). Note how the .class is omitted:
$ java HelloWorld
Note: The java command runs a Java application.
This will output to your console:
Hello, World!
You have successfully coded and built your very first Java program!
Note: In order for Java commands (java, javac, etc) to be recognized, you will need to make sure:
A JDK is installed (e.g. Oracle, OpenJDK and other sources)
Your environment variables are properly set up
You will need to use a compiler (javac) and an executor (java) provided by your JVM. To find out which versions you
Java® Notes for Professionals 4
have installed, enter java -version and javac -version on the command line. The version number of your
program will be printed in the terminal (e.g. 1.8.0_73).
A closer look at the Hello World program
The "Hello World" program contains a single file, which consists of a HelloWorld class definition, a main method,
and a statement inside the main method.
public class HelloWorld {
The class keyword begins the class definition for a class named HelloWorld. Every Java application contains at least
one class definition (Further information about classes).
public static void main(String[] args) {
This is an entry point method (defined by its name and signature of public static void main(String[])) from
which the JVM can run your program. Every Java program should have one. It is:
public: meaning that the method can be called from anywhere mean from outside the program as well. See
Visibility for more information on this.
static: meaning it exists and can be run by itself (at the class level without creating an object).
void: meaning it returns no value. Note: This is unlike C and C++ where a return code such as int is expected
(Java's way is System.exit()).
This main method accepts:
An array (typically called args) of Strings passed as arguments to main function (e.g. from command line
arguments).
Almost all of this is required for a Java entry point method.
Non-required parts:
The name args is a variable name, so it can be called anything you want, although it is typically called args.
Whether its parameter type is an array (String[] args) or Varargs (String... args) does not matter
because arrays can be passed into varargs.
Note: A single application may have multiple classes containing an entry point (main) method. The entry point of the
application is determined by the class name passed as an argument to the java command.
Inside the main method, we see the following statement:
System.out.println("Hello, World!");
Let's break down this statement element-by-element:
Element Purpose
System
this denotes that the subsequent expression will call upon the System class, from the java.lang
package.
.
this is a "dot operator". Dot operators provide you access to a classes members1; i.e. its fields
(variables) and its methods. In this case, this dot operator allows you to reference the out static field
within the System class.
out
this is the name of the static field of PrintStream type within the System class containing the standard
output functionality.
Java® Notes for Professionals 5
.
this is another dot operator. This dot operator provides access to the println method within the out
variable.
println
this is the name of a method within the PrintStream class. This method in particular prints the
contents of the parameters into the console and inserts a newline after.
(
this parenthesis indicates that a method is being accessed (and not a field) and begins the
parameters being passed into the println method.
"Hello,
World!"
this is the String literal that is passed as a parameter, into the println method. The double quotation
marks on each end delimit the text as a String.
)
this parenthesis signifies the closure of the parameters being passed into the println method.
;
this semicolon marks the end of the statement.
Note: Each statement in Java must end with a semicolon (;).
The method body and class body are then closed.
} // end of main function scope
} // end of class HelloWorld scope
Here's another example demonstrating the OO paradigm. Let's model a football team with one (yes, one!) member.
There can be more, but we'll discuss that when we get to arrays.
First, let's define our Team class:
public class Team {
Member member;
public Team(Member member) { // who is in this Team?
this.member = member; // one 'member' is in this Team!
}
}
Now, let's define our Member class:
class Member {
private String name;
private String type;
private int level; // note the data type here
private int rank; // note the data type here as well
public Member(String name, String type, int level, int rank) {
this.name = name;
this.type = type;
this.level = level;
this.rank = rank;
}
}
Why do we use private here? Well, if someone wanted to know your name, they should ask you directly, instead of
reaching into your pocket and pulling out your Social Security card. This private does something like that: it
prevents outside entities from accessing your variables. You can only return private members through getter
functions (shown below).
After putting it all together, and adding the getters and main method as discussed before, we have:
public class Team {
Member member;
public Team(Member member) {
this.member = member;
}
Java® Notes for Professionals 6
// here's our main method
public static void main(String[] args) {
Member myMember = new Member("Aurieel", "light", 10, 1);
Team myTeam = new Team(myMember);
System.out.println(myTeam.member.getName());
System.out.println(myTeam.member.getType());
System.out.println(myTeam.member.getLevel());
System.out.println(myTeam.member.getRank());
}
}
class Member {
private String name;
private String type;
private int level;
private int rank;
public Member(String name, String type, int level, int rank) {
this.name = name;
this.type = type;
this.level = level;
this.rank = rank;
}
/* let's define our getter functions here */
public String getName() { // what is your name?
return this.name; // my name is ...
}
public String getType() { // what is your type?
return this.type; // my type is ...
}
public int getLevel() { // what is your level?
return this.level; // my level is ...
}
public int getRank() { // what is your rank?
return this.rank; // my rank is
}
}
Output:
Aurieel
light
10
1
Run on ideone
Once again, the main method inside the Test class is the entry point to our program. Without the main method, we
cannot tell the Java Virtual Machine (JVM) from where to begin execution of the program.
1 - Because the HelloWorld class has little relation to the System class, it can only access public data.
收藏
分享
暂无回复
Author