فهرست مطالب :
of professional hints and tricks
GoalKicker.com
Free Programming Books
Contents
About
Chapter 11: Strings
Chapter 12: StringBuIer
Chapter 13: StringBuilder
Chapter 16: Date Class
Chapter 18: LocalTime
Chapter 19: BigDecimal
Chapter 20: BigInteger
Chapter 23: Arrays
Chapter 24: Collections
Chapter 25: Lists
Chapter 26: Sets
Chapter 27: List vs Set
Chapter 29: LinkedHashMap
Chapter 37: EnumSet class
Chapter 39: Hashtable
Chapter 41: Constructors
Chapter 43: Annotations
Chapter 47: Generics
Chapter 50: Nested and Inner Classes
Chapter 52: Default Methods
Chapter 53: Packages
Chapter 54: Inheritance
Chapter 57: Streams
Chapter 60: Preferences
Chapter 66: Serialization
Chapter 67: Optional
Chapter 75: Bu\'IeredWriter
Chapter 77: File I/O
Chapter 78: Scanner
Chapter 84: Object Cloning
Chapter 88: Singletons
Chapter 89: Autoboxing
Chapter 91: JAXB
Chapter 93: Networking
Chapter 96: JAX-WS
Chapter 98: Java Native Interface
Chapter 103: Reflection API
Chapter 104: ByteBuIer
Chapter 105: Applets
Chapter 106: Expressions
Chapter 107: JSON in Java
Chapter 111: Polymorphism
Chapter 116: log4j / log4j2
Chapter 123: Process
Chapter 128: ThreadLocal
Chapter 137: Classloaders
Chapter 139: Atomic Types
Chapter 140: RSA Encryption
Chapter 141: Secure objects
Chapter 145: JNDI
Chapter 150: JavaBean
Chapter 155: JShell
Chapter 156: Stack-Walking API
Chapter 157: Sockets
Chapter 158: Java Sockets
Chapter 161: C++ Comparison
Chapter 162: Audio
Chapter 166: Unit Testing
Chapter 167: Asserting
Chapter 172: JMX
Chapter 174: XJC
Chapter 175: JVM Flags
Chapter 179: Benchmarks
Integration
About
Chapter 1: Getting started with Java Language
Java SE Version Code Name End-of-life (free1) Release Date
Section 1.1: Creating Your First Java Program
A closer look at the Hello World program
Chapter 2: Type Conversion
Section 2.1 : Numeric primitive casting
Section 2.2 : Basic Numeric Promotion
Section 2.3 : Non-numeric primitive casting
Section 2.4 : Object casting
Section 2.5 : Testing if an object can be cast using instanceof
Chapter 3: Getters and Setters
Section 3.1 : Using a setter or getter to implement a constraint
Section 3.2 : Why Use Getters and Setters?
Section 3.3 : Adding Getters and Setters
Chapter 4: Reference Data Types
Section 4.1 : Dereferencing
Section 4.2 : Instantiating a reference type
Chapter 5: Java Compiler - \'javac\'
Section 5.1 : The \'javac\' command - getting started
Simple example
Example with packages
Compiling multiple files at once with \'javac\'.
Commonly used \'javac\' options
Section 5.2 : Compiling for a drierent version of Java
Compiling old Java with a newer compiler
Chapter 6: Documenting Java Code
Section 6.1 : Building Javadocs From the Command Line
Section 6.2 : Class Documentation
Section 6.3 : Method Documentation
Section 6.4 : Package Documentation
Section 6.5 : Links
Section 6.6 : Code snippets inside documentation
Section 6.7 : Field Documentation
Section 6.8 : Inline Code Documentation
Chapter 7: Command line Argument Processing
Parameter Details
Section 7.1 : Argument processing using GWT ToolBase
Section 7.2 : Processing arguments by hand
A command with no arguments
A command with two arguments
Chapter 8: The Java Command - \'java\' and \'javaw\'
Section 8.1 : Entry point classes
JavaFX entry-points
Section 8.2 : Troubleshooting the \'java\' command
Other Resources
Section 8.3 : Running a Java application with library dependencies
Section 8.4 : Java Options
Selecting the VM type
Section 8.5 : Spaces and other special characters in arguments
Solutions using a POSIX shell
Section 8.6 : Running an executable JAR file
Section 8.7 : Running a Java applications via a \"main\" class
Specifying a classpath
Chapter 9: Literals
Section 9.1 : Using underscore to improve readability
Section 9.2 : Hexadecimal, Octal and Binary literals
Section 9.3 : Boolean literals
Section 9.4 : String literals
Interning of string literals
Section 9.5 : The Null literal
Section 9.6 : Escape sequences in literals
Section 9.7 : Character literals
Section 9.8 : Decimal Integer literals
Ordinary integer literals
Long integer literals
Section 9.9 : Floating-point literals
Simple decimal forms
Chapter 10: Primitive Data Types
Section 10. 1: The char primitive
Section 10. 2: Primitive Types Cheatsheet
Section 10. 3: The float primitive
Section 10. 4: The int primitive
Section 10. 5: Converting Primitives
Widening Conversion:
Section 10. 6: Memory consumption of primitives vs. boxed primitives
Primitive Boxed Type Memory Size of primitive / boxed
Boxed value caches
Section 10. 7: The double primitive
Section 10. 8: The long primitive
Section 10. 9: The boolean primitive
Section 10.1 0: The byte primitive
Section 10.1 1: Negative value representation
Original Process Result
Section 10.1 2: The short primitive
Chapter 11: Strings
Section 11.1: Comparing Strings
default:
break;
Comparing with interned Strings
Section 11. 2: Changing the case of characters within a String
Section 11. 3: Finding a String Within Another String
Section 11.4: String pool and heap storage
Section 11.5: Splitting Strings
Splitting with a StringTokenizer
Section 11. 6: Joining Strings with a delimiter
Section 11. 7: String concatenation and StringBuilders
Using concat() method:
Section 11. 8: Substrings
Section 11. 9: Platform independent new line separator
Section 11.1 0: Reversing Strings
Section 11.1 1: Adding toString() method for custom objects
Section 11.1 2: Remove Whitespace from the Beginning and End of a String
Section 11.1 3: Case insensitive switch
break;
Section 11.1 4: Replacing parts of Strings
WoWcorn Replace sequence of characters with another sequence of characters:
Section 11.1 5: Getting the length of a String
Section 11.1 6: Getting the nth character in a String
Section 11.1 7: Counting occurrences of a substring or character in a string
Chapter 12: StringBuIer
Section 12.1: String BuIer class
Key Points:
Chapter 13: StringBuilder
Section 13. 1: Comparing StrmgBu\'Ier, StringBuilder, Formatter and StringJoiner
Section 13. 2: Repeat a String n times
Chapter 14: String Tokenizer
Section 14. 1: StringTokenizer Split by space
Section 14. 2: StringTokenizer Split by comma \',\'
Chapter 15: Splitting a string into fixed length parts
Section 15. 1: Break a string up into substrings all of a known length
Section 15. 2: Break a string up into substrings all of variable length
Chapter 16: Date Class
Parameter Explanation
Section 16. 1: Convert java.util.Date to java.sql.Date
Example
Section 16. 2: A basic date output
Section 16. 3: Java 8 LocalDate and LocalDateTime objects
Section 16. 4: Creating a Specific Date
Section 16. 5: Converting Date to a certain String format
Section 16. 6: LocalTime
Section 16. 7: Convert formatted string representation of date
to Date object
Section 16. 8: Creating Date objects
Section 16. 9: Comparing Date objects
Calendar, Date, and LocalDate
Date comparison before Java 8
Section 16.1 0: Converting String into Date
Section 16.1 1: Time Zones and java.util.Date
Chapter 17: Dates and Time (java.time.*)
Section 17. 1: Calculate Di\'Ierence between 2 LocalDates
Section 17. 2: Date and time
Section 17. 3: Operations on dates and times
Section 17. 4: Instant
Section 17. 5: Usage of various classes of Date Time API
Section 17.6: Date Time Formatting
Section 17.7: Simple Date Manipulations
Chapter 18: LocalTime
Method
Output
Section 18. 1: Amount of time between two LocalTime
Section 18. 2: Intro
Fields
Section 18. 3: Time Modification
Section 18. 4: Time Zones and their time di\'Ierence
Chapter 19: BigDecimal
Section 19. 1: Comparing BigDecimals
Section 19. 2: Using BigDecimal instead of float
Section 19. 3: BigDecimal.valueOf()
Section 19. 4: Mathematical operations with BigDecimal
1.Addition
2.Subtraction
3.Multiplication
4.Division
5.Remainder or Modulus
6.Power
7.Max
8.Min
9.Move Point To Left
10.Move Point To Right
Section 19.5: Initialization of BigDecimals with value zero, one or ten
Section 19.6: BigDecimal objects are immutable
Chapter 20: BigInteger
Section 20. 1: Initialization
Section 20. 2: BigInteger Mathematical Operations Examples
Section 20. 3: Comparing BigIntegers
Section 20.4: Binary Logic Operations on BigInteger
Section 20.5: Generating random BigIntegers
Chapter 21: NumberFormat
Section 21.1: NumberFormat
Chapter 22: Bit Manipulation
Section 22. 1: Checking, setting, clearing, and toggling
individual bits. Using long as bit mask
Section 22. 2: java.util.BitSet class
Section 22. 3: Checking if a number is a power of 2
Usage for Left and Right Shift
Section 22. 4: Signed vs unsigned shift
Section 22. 5: Expressing the power of 2
Section 22. 6: Packing / unpacking values as bit fragments
Chapter 23: Arrays
Parameter Details
Section 23. 1: Creating and Initializing Arrays
Basic cases
Arrays may not be re-initialized with array initializer shortcut syntax
Section 23. 2: Creating a List from an Array
Section 23. 3: Creating an Array from a Collection
Section 23. 4: Multidimensional and Jagged Arrays
Section 23. 5: ArrayIndexOutOfBoundsException
Section 23. 6: Array Covariance
Section 23. 7: Arrays to Stream
Section 23. 8: Iterating over arrays
Section 23. 9: Arrays to a String
return \"CAT!\";
public class Dog {
Section 23.1 0: Sorting arrays
Sorting String arrays:
Increasing Order
Section 23.1 1: Getting the Length of an Array
Section 23.1 2: Finding an element in an array
Section 23.1 3: How do you change the size of an array?
Section 23.1 4: Converting arrays between primitives and boxed types
Section 23.1 5: Remove an element from an array
Using ArrayList
Section 23.1 6: Comparing arrays for equality
Section 23.1 7: Copying arrays
Arrays.copyOfRange()
Section 23.1 8: Casting Arrays
Chapter 24: Collections
Section 24. 1: Removing items from a List within a loop
Using a \"should-be-removed\" list
Section 24. 2: Constructing collections from existing data
Standard Collections
Java Collections framework
Google Guava Collections framework
Mapping Collections
Java Collections framework
Section 24. 3: Declaring an ArrayList and adding objects
Section 24. 4: Iterating over Collections
Iterating over List
Iterating over Set
Section 24. 5: Immutable Empty Collections
Section 24. 6: Sub Collections
List subList(int fromIndex, int toIndex)
Set subSet(fromIndex,toIndex)
Section 24. 7: Unmodifiable Collection
Section 24. 8: Pitfall: concurrent modification exceptions
Section 24. 9: Removing matching items from Lists using Iterator
Section 24.1 0: Join lists
Section 24.1 1: Creating your own Iterable structure for use with Iterator or for-each loop
Section 24.1 2: Collections and Primitive Values
Chapter 25: Lists
Section 25. 1: Sorting a generic list
Section 25. 2: Convert a list of integers to a list of strings
Section 25. 3: Classes implementing List - Pros and Cons
1. Abstract Classes:
2. Concrete Classes:
- PROS:
- CONS:
- PROS:
RoleList
Section 25. 4: Finding common elements between 2 lists
Section 25. 5: In-place replacement of a List element
Section 25. 6: Making a list unmodifiable
Section 25. 7: Moving objects around in the list
Section 25. 8: Creating, Adding and Removing element from an ArrayList
Section 25. 9: Creating a List
Giving your list a type
Section 25.1 0: Positional Access Operations
Section 25.1 1: Iterating over elements in a list
Section 25.1 2: Removing elements from list B that are present in the list A
Chapter 26: Sets
Section 26. 1: Initialization
Section 26. 2: Basics of Set
What is a Set?
Creating a set
Section 26. 3: Types and Usage of Sets
HashSet - Random Sorting
LinkedHashSet - Insertion Order
Section 26. 4: Create a list from an existing Set
Using a new List
Section 26. 5: Eliminating duplicates using Set
Section 26. 6: Declaring a HashSet with values
Chapter 27: List vs Set
Section 27.1: List vs Set
Chapter 28: Maps
Section 28. 1: Iterating Map Entries E\'lciently
Section 28. 2: Usage of HashMap
1. Declaring HashMap
2. Putting values in HashMap.
3. Getting values from HashMap.
4. Check whether the Key is in the Map or not.
5. Check whether the Value is in the Map or not.
Section 28. 3: Using Default Methods of Map from Java 8
Section 28. 4: Iterating through the contents of a Map
Iterating through map keys:
Iterating through map values:
Section 28. 5: Merging, combine and composing Maps
Section 28. 6: Add multiple items
Section 28. 7: Creating and Initializing Maps
Introduction
Section 28. 8: Check if key exists
Section 28. 9: Add an element
Section 28.1 0: Clear the map
Section 28.1 1: Use custom object as key
Chapter 29: LinkedHashMap
Section 29.1: Java LinkedHashMap class
Key Points:
Methods:
Example:
Chapter 30: WeakHashMap
Section 30.1: Concepts of WeakHashmap
Key Points:
Chapter 31: SortedMap
Section 31.1: Introduction to sorted Map
Keypoint:
Methods of sorted Map :
Example
Chapter 32: TreeMap and TreeSet
Section 32. 1: TreeMap of a simple Java type
Section 32. 2: TreeSet of a simple Java Type
Section 32. 3: TreeMap/TreeSet of a custom Java type
Section 32. 4: TreeMap and TreeSet Thread Safety
Chapter 33: Queues and Deques
Section 33. 1: The usage of the PriorityQueue
Section 33. 2: Deque
Brief description
Removing Elements
Section 33. 3: Stacks
What is a Stack?
Example
Section 33. 4: BlockingQueue
Operation Throws Exception Special Value Blocks Times out
Section 33. 5: LinkedList as a FIFO Queue
Section 33. 6: Queue Interface
Basics
Type of operation Throws exception Returns special value
Chapter 34: Dequeue Interface
Section 34. 1: Adding Elements to Deque
Section 34. 2: Removing Elements from Deque
Section 34. 3: Retrieving Element without Removing
Section 34. 4: Iterating through Deque
Chapter 35: Enums
Section 35.1: Declaring and using a basic enum
Section 35. 2: Enums with constructors
Section 35. 3: Enums with Abstract Methods
Section 35. 4: Implements Interface
NULL {
Section 35. 5: Implement Singleton pattern with a singleelement enum
Section 35. 6: Using methods and static blocks
static {
Section 35. 7: Zero instance enum
Section 35. 8: Enum as a bounded type parameter
Section 35. 9: Documenting enums
Section 35.1 0: Enum constant specific body
Section 35.1 1: Getting the values of an enum
Section 35.1 2: Enum Polymorphism Pattern
Section 35.1 3: Compare and Contains for Enum values
Section 35.1 4: Get enum constant by name
Section 35.1 5: Enum with properties (fields)
Section 35.1 6: Convert enum to String
By default:
Section 35.1 7: Enums with static fields
Chapter 36: Enum Map
Section 36.1: Enum Map Book Example
public enum Key{
Chapter 37: EnumSet class
Section 37.1: Enum Set Example
Chapter 38: Enum starting with number
Section 38.1: Enum with name at beginning
Chapter 39: Hashtable
Section 39.1: Hashtable
Chapter 40: Operators
Section 40. 1: The Increment/Decrement Operators (++/--)
Section 40. 2: The Conditional Operator (? :)
Common Usage
Section 40. 3: The Bitwise and Logical Operators (~, &, |, A)
A B ~A A & B A | B A A B
Section 40. 4: The String Concatenation Operator (+)
Optimization and efficiency
Section 40. 5: The Arithmetic Operators (+, -, *, /, %)
The meaning of division
Section 40. 6: The Shift Operators (<<, >> and >>>)
Operand1 Operand2 << >> >>>
Section 40. 7: The Instanceof Operator
Section 40. 8: The Assignment Operators (=, +=, -=, *=, /=, %=,
<<=, >>= , >>>=, &=, |= and A=)
1. =
2. +=
3. -=
4. *=
5. /=
7. <<=
8. >>=
9. >>>=
10. &=
11. |=
12. A=
Section 40.9: The conditional-and and conditional-or Operators ( && and || )
Example - using && to avoid a costly calculation
Section 40.10: The Relational Operators (<, <=, >, >=)
Section 40.11: The Equality Operators (==, !=)
The Reference == and != operators
About the NaN edge-cases
Section 40.12: The Lambda operator ( -> )
Chapter 41: Constructors
Section 41. 1: Default Constructor
Section 41. 2: Call parent constructor
Withoutsuper(...)method:
Withsuper()method:
Section 41. 3: Constructor with Arguments
Chapter 42: Object Class Methods and Constructor
Section 42. 1: hashCode() method
public class Foo {
return true;
return false;
Internal caching of hash codes
public final class ImmutableArray { private int[] array;
private volatile int hash = 0;
Section 42. 2: toString() method
Section 42. 3: equals() method
TL;DR
public class Foo {
public class Foo {
return true;
return false;
return true;
return false;
return false;
Section 42. 4: wait() and notify() methods
Section 42. 5: getClass() method
Section 42. 6: clone() method
Section 42. 7: Object constructor
Section 42. 8: finalize() method
Chapter 43: Annotations
Section 43. 1: The idea behind Annotations
Section 43. 2: Defining annotation types
Available values
RetentionPolicy
Effect
@Documented
@Inherited
Section 43. 3: Runtime annotation checks via reflection
Section 43. 4: Built-in annotations
@SuppressWarnings
Section 43. 5: Compile time processing using annotation processor
The annotation processor
Section 43. 6: Repeating Annotations
Section 43. 7: Inherited Annotations
null
Section 43. 8: Getting Annotation values at run-time
Section 43. 9: Annotations for \'this\' and receiver parameters
Section 43.1 0: Add multiple annotation values
Chapter 44: Immutable Class
Section 44. 1: Example without mutable refs
Section 44. 2: What is the advantage of immutability?
Section 44. 3: Rules to define immutable classes
Section 44. 4: Example with mutable refs
public int getY() { return y;
public void setY(int y) {
public final class ImmutableCircle {
private final Point center;
private final double radius;
Chapter 45: Immutable Objects
Section 45. 1: Creating an immutable version of a type using defensive copying
private final int[] array;
Section 45. 2: The recipe for an immutable class
Section 45. 3: Typical design flaws which prevent a class from being immutable
Using some setters, without setting all needed properties in the constructor(s)
Not marking instance variables as private and final
public final class Names {
Injecting constructor with object(s) that can be modified outside the immutable class
Letting the methods of the class being overridden
Chapter 46: Visibility (controlling access to members of a class)
Section 46. 1: Private Visibility
Section 46. 2: Public Visibility
Section 46. 3: Package Visibility
Section 46. 4: Protected Visibility
Section 46. 5: Summary of Class Member Access Modifiers
Access Modifier Visibility Inheritance
Section 46. 6: Interface members
Chapter 47: Generics
Section 47. 1: Creating a Generic Class
Extending a generic class
public abstract class AbstractParam
{ private T value;
Section 47. 2: Deciding between \'T\',\'? super T\', and \'? extends T\'
Section 47. 3: The Diamond
Section 47. 4: Declaring a Generic Method
Section 47. 5: Requiring multiple upper bounds (\"extends A & B\")
Section 47. 6: Obtain class that satisfies generic parameter at runtime
Background
Implementations
Example usage
Section 47. 7: Benefits of Generic class and interface
Enabling programmers to implement generic algorithms
Section 47. 8: Instantiating a generic type
Section 47. 9: Creating a Bounded Generic Class
public abstract class Animal {
Section 47.1 0: Referring to the declared generic type within its own declaration
Section 47.1 1: Binding generic parameter to more than 1 type
Section 47.1 2: Using Generics to auto-cast
Section 47.1 3: Use of instanceof with Generics
Using generics to define the type in instanceof
Section 47.1 4: DiIerent ways for implementing a Generic Interface (or extending a Generic Class)
Generic class implementation
Raw type class implementation
Chapter 48: Classes and Objects
Section 48. 1: Overloading Methods
public class Displayer {
Methods can be overloaded:
Section 48. 2: Explaining what is method overloading and overriding
different.
Method Overriding
Method Overriding
Section 48. 3: Constructors
Section 48. 4: Initializing static final fields using a static
initializer
static {
Section 48. 5: Basic Object Construction and Use
Section 48. 6: Simplest Possible Class
Section 48. 7: Object Member vs Static Member
Chapter 49: Local Inner Class
Section 49.1: Local Inner Class
Chapter 50: Nested and Inner Classes
Section 50. 1: A Simple Stack Using a Nested Class
Section 50. 2: Static vs Non Static Nested Classes
Section 50. 3: Access Modifiers for Inner Classes
Section 50. 4: Anonymous Inner Classes
Constructors
Section 50. 5: Create instance of non-static inner class from outside
Section 50. 6: Method Local Inner Classes
Section 50. 7: Accessing the outer class from a non-static inner class
Chapter 51: The java.util.Objects Class
Section 51. 1: Basic use for object null check
For null check in method
Section 51. 2: Objects.nonNull() method reference use in stream
api
continue ;
Chapter 52: Default Methods
Section 52. 1: Basic usage of default methods
Section 52. 2: Accessing overridden default methods from implementing class
Section 52. 3: Why use Default Methods?
public interface Swim {
public interface Swim {
Section 52. 4: Accessing other interface methods within default method
Section 52. 5: Default method multiple inheritance collision
public interface A {
public interface B {
Section 52. 6: Class, Abstract class and Interface method precedence
Chapter 53: Packages
Section 53. 1: Using Packages to create classes with the same name
Section 53. 2: Using Package Protected Scope
Chapter 54: Inheritance
Section 54. 1: Inheritance
public class A{}
public class B{}
Section 54. 2: Abstract Classes
Section 54. 3: Using \'final\' to restrict inheritance and overriding
Final classes
Section 54. 4: The Liskov Substitution Principle
Section 54. 5: Abstract class and Interface usage: \"Is-a\" relation vs \"Has-a\" capability
Consider using interfaces if...
Section 54. 6: Static Inheritance
Section 54. 7: Programming to an interface
Section 54. 8: Overriding in Inheritance
Section 54. 9: Variable shadowing
Section 54.1 0: Narrowing and Widening of object references
Section 54.1 1: Inheritance and Static Methods
Chapter 55: Reference Types
Section 55.1: DiIerent Reference Types
1. Strong Reference
2. Weak Reference
3. Soft Reference
4. Phantom Reference
Chapter 56: Console I/O
Section 56. 1: Reading user input from the console
Using BufferedReader:
Using Scanner:
Section 56. 2: Aligning strings in console
Format strings examples
Section 56. 3: Implementing Basic Command-Line Behavior
Chapter 57: Streams
Section 57. 1: Using Streams
Output:
Example:
Section 57. 2: Consuming Streams
Section 57. 3: Creating a Frequency Map
Section 57. 4: Infinite Streams
Section 57. 5: Collect Elements of a Stream into a Collection
Collect with toList() and toSet()
Cheat-Sheet Goal
Section 57. 6: Using Streams to Implement Mathematical Functions
Section 57. 7: Flatten Streams with flatMap()
Section 57. 8: Parallel Stream
Section 57. 9: Creating a Stream
Section 57.1 0: Finding Statistics about Numerical Streams
Section 57.1 1: Converting an iterator to a stream
Section 57.1 2: Using IntStream to iterate over indexes
Section 57.1 3: Concatenate Streams
Example 1 - Concatenate two Streams
Section 57.1 4: Reduction with Streams
Section 57.1 5: Using Streams of Map.Entry to Preserve Initial
Values after Mapping
Section 57.1 6: IntStream to String
Section 57.1 7: Finding the First Element that Matches a Predicate
Section 57.1 8: Using Streams and Method References to Write Self-Documenting Processes
Section 57.1 9: Converting a Stream of Optional to a Stream of Values
Section 57.2 0: Get a Slice of a Stream
Notes:
Section 57.2 1: Create a Map based on a Stream
Simple case without duplicate keys
Grouping by value
Section 57.2 2: Joining a stream to a single String
Section 57.2 3: Sort Using Stream
Section 57.2 4: Streams of Primitives
Section 57.2 5: Stream operations categories
Stateless Operations
Stateful operations
Section 57.2 6: Collect Results of a Stream into an Array
Section 57.2 7: Generating random Strings using Streams
Chapter 58: InputStreams and OutputStreams
Section 58. 1: Closing Streams
Section 58. 2: Reading InputStream into a String
Section 58. 3: Wrapping Input/Output Streams
List of Input/Output Stream wrappers Wrapper
Description
Section 58. 4: DataInputStream Example
Section 58. 5: Writing bytes to an OutputStream
Section 58. 6: Copying Input Stream to Output Stream
Chapter 59: Readers and Writers
Section 59. 1: Bu\'IeredReader
Introduction
int ch;
The BufferedReader buffer size
The BufferedReader.readLine() method Example: reading all lines of a File into a List
Section 59. 2: StringWriter Example
Chapter 60: Preferences
Section 60. 1: Using preferences
Section 60. 2: Adding event listeners
Section 60. 3: Getting sub-nodes of Preferences
Section 60. 4: Coordinating preferences access across multiple application instances
Section 60. 5: Exporting preferences
Section 60. 6: Importing preferences
Section 60. 7: Removing event listeners
Section 60. 8: Getting preferences values
Section 60. 9: Setting preferences values
Chapter 61: Collection Factory Methods
Description
Section 61. 1: List Factory Method Examples
Section 61. 2: Set Factory Method Examples
Section 61. 3: Map Factory Method Examples
Chapter 62: Alternative Collections
Section 62.1: Multimap in Guava, Apache and Eclipse Collections
1. MultiValueMap from Apache
2. HashBiMap from GS / Eclipse Collection
Section 62.2: Apache HashBag, Guava HashMultiset and
Eclipse HashBag
Section 62.3: Compare operation with collections - Create collections
Compare operation with collections - Create collections 1. Create List
Description JDK
JDK
new
JDK new
Chapter 63: Concurrent Collections
Section 63. 1: Thread-safe Collections
Section 63. 2: Insertion into ConcurrentHashMap
Section 63. 3: Concurrent Collections
Chapter 64: Choosing Collections
Section 64.1: Java Collections Flowchart
Chapter 65: super keyword
Section 65.1: Super keyword use with examples
Constructor Level
Chapter 66: Serialization
Section 66. 1: Basic Serialization in Java
What is Serialization
How to write an object into a file
How to recreate an object from its serialized state
try {
Section 66. 2: Custom Serialization
Section 66. 3: Versioning and serialVersionUID
Incompatible Changes
Section 66. 4: Serialization with Gson
Section 66. 5: Custom JSON Deserialization with Jackson
Chapter 67: Optional
Section 67. 1: Map
Section 67. 2: Return default value if Optional is empty
Section 67. 3: Throw an exception, if there is no value
Section 67. 4: Lazily provide a default value using a Supplier
Section 67. 5: Filter
Section 67. 6: Using Optional containers for primitive number types
Section 67. 7: Run code only if there is a value present
Section 67. 8: FlatMap
Chapter 68: Object References
Section 68.1: Object References as method parameters
Chapter 69: Exceptions and exception handling
Section 69. 1: Catching an exception with try-catch
try {
Try-catch with multiple catches
try {
try {
try {
Section 69. 2: The try-with-resources statement
What is a resource?
The enhanced try-with-resource statements
Managing multiple resources
Section 69. 3: Custom Exceptions
Section 69. 4: Handling InterruptedException
Section 69. 5: Return statements in try catch block
Section 69. 6: Introduction
try {
Section 69. 7: The Java Exception Hierarchy - Unchecked and Checked Exceptions
Checked versus Unchecked Exceptions
Section 69. 8: Creating and reading stacktraces
Printing a stacktrace
try {
Understanding a stacktrace
1 public class Main {
2 public void foo() {
6 public int bar() {
Capturing a stacktrace as a String
Section 69. 9: Throwing an exception
Section 69.1 0: Advanced features of Exceptions
Optimizing exception construction
Section 69.1 1: The try-finally and try-catch-finally statements
Try-finally
try {
try-catch-finally
Section 69.1 2: The \'throws\' clause in a method declaration
What is the point of declaring unchecked exceptions as thrown?
Chapter 70: Calendar and its Subclasses
Section 70. 1: Creating Calendar objects
Section 70. 2: Increasing / Decreasing calendar fields
Section 70. 3: Subtracting calendars
Section 70. 4: Finding AM/PM
Chapter 71: Using the static keyword
Section 71. 1: Reference to non-static member from static context
Section 71. 2: Using static to declare constants
Chapter 72: Properties Class
Section 72. 1: Loading properties
Section 72. 2: Saving Properties as XML
Storing Properties in a XML File
Section 72. 3: Property files caveat: trailing whitespace
Chapter 73: Lambda Expressions
Section 73. 1: Introduction to Java lambdas
Functional Interfaces
Lambda Expressions
Accepting Lambdas
The Type of a Lambda Expression
Section 73. 2: Using Lambda Expressions to Sort a Collection
Sorting lists
Section 73. 3: Method References
Cheat-Sheet
Method Reference Format
Section 73. 4: Implementing multiple interfaces
Section 73. 5: Lambda - Listener Example
Anonymous class listener
Lambda listener
Section 73. 6: Java Closures with lambda expressions
Section 73. 7: Lambdas and memory utilization
Section 73. 8: Using lambda expression with your own functional interface
Section 73. 9: Traditional style to Lambda style
Traditional way
Section 73.1 0: \'return\' only returns from the lambda, not the outer method
return;
Section 73.1 1: Lambdas and Execute-around Pattern
Section 73.1 2: Using lambda expressions & predicates to get a certain value(s) from a list
Chapter 74: Basic Control Structures
Section 74.1: Switch statement
break;
default:
Section 74. 2: do...while Loop
Section 74. 3: For Each
Examples:
Section 74. 4: Continue Statement in Java
Section 74. 5: If / Else If / Else Control
Section 74. 6: For Loops
Section 74. 7: Ternary Operator
Section 74. 8: Try ... Catch ... Finally
Section 74. 9: Break
Section 74.1 0: While Loops
Section 74.1 1: If / Else
Section 74.1 2: Nested break / continue
Chapter 75: BuIeredWriter
Section 75.1: Write a line of text to File
Chapter 76: New File I/O
Section 76. 1: Creating paths
Section 76. 2: Manipulating paths
Joining Two Paths
Section 76. 3: Retrieving information about a path
Section 76. 4: Retrieving information using the filesystem
Checking whether a path points to a file or a directory
Section 76. 5: Reading files
Section 76. 6: Writing files
Chapter 77: File I/O
Section 77. 1: Migrating from java.io.File to Java 7 NIO (java.nio.file.Path)
Section 77. 2: Reading an image from a file
Section 77. 3: File Read/Write Using FileInputStream/FileOutputStream
Section 77. 4: Reading all bytes to a byte[]
Section 77. 5: Copying a file using Channel
Section 77. 6: Writing a byte[] to a file
Section 77. 7: Stream vs Writer/Reader API
Section 77. 8: Reading a file with a Scanner
Section 77. 9: Copying a file using InputStream and OutputStream
Section 77.1 0: Reading from a binary file
Section 77.1 1: Reading a file using Channel and Bu\'Ier
try {
Section 77.1 2: Adding Directories
Section 77.1 3: Blocking or redirecting standard output / error
Section 77.1 4: Reading a whole file at once
Section 77.1 5: Locking
Section 77.1 6: Reading a file using Bu\'IeredlnputStream
Section 77.1 7: Iterate over a directory printing subdirectories in it
Section 77.1 8: Writing a file using Channel and Bu\'Ier
Section 77.1 9: Writing a file using PrintStream
Section 77.2 0: Iterating over a directory and filter by file extension
Section 77.2 1: Accessing the contents of a ZIP file
Creating a new file
Chapter 78: Scanner
Parameter Details
Section 78. 1: General Pattern that does most commonly asked about tasks
static {
Section 78. 2: Using custom delimiters
Section 78. 3: Reading system input using Scanner
Section 78. 4: Reading file input using Scanner
try {
Section 78. 5: Read the entire input as a String using Scanner
Section 78. 6: Carefully Closing a Scanner
Section 78. 7: Read an int from the command line
Chapter 79: Interfaces
Section 79. 1: Implementing multiple interfaces
Section 79. 2: Declaring and Implementing an Interface
Section 79. 3: Extending an interface
Section 79. 4: Usefulness of interfaces
return null;
} else {
Section 79. 5: Default methods
Observer pattern implementation
Section 79. 6: Modifiers in Interfaces
Section 79. 7: Using Interfaces with Generics
Section 79. 8: Strengthen bounded type parameters
Section 79. 9: Implementing interfaces in an abstract class
Chapter 80: Regular Expressions
Section 80. 1: Using capture groups
Section 80. 2: Using regex with custom behaviour by compiling the Pattern with flags
Section 80. 3: Escape Characters
Generally
Splitting a Pipe Delimited String
Section 80. 4: Not matching a given string
Output:
Section 80. 5: Matching with a regex literal
Section 80. 6: Matching a backslash
Chapter 81: Comparable and Comparator
Section 81. 1: Sorting a List using Comparable or a
Comparator
comparator
Section 81. 2: The compareTo and compare Methods
Section 81. 3: Natural (comparable) vs explicit (comparator) sorting
Section 81. 4: Creating a Comparator using comparing method
Section 81. 5: Sorting Map entries
Chapter 82: Java Floating Point Operations
Section 82. 1: Comparing floating point values
Section 82. 2: OverFlow and UnderFlow
Section 82. 3: Formatting the floating point values
Section 82. 4: Strict Adherence to the IEEE Specification
Chapter 83: Currency and Money
Section 83.1: Add custom currency
Chapter 84: Object Cloning
Section 84. 1: Cloning performing a deep copy
Section 84. 2: Cloning using a copy factory
Section 84. 3: Cloning using a copy constructor
Section 84. 4: Cloning by implementing Clonable interface
Section 84. 5: Cloning performing a shallow copy
Chapter 85: Recursion
Section 85. 1: The basic idea of recursion
What is recursion:
public int factorial(int n) {
} else {
Section 85. 2: Deep recursion is problematic in Java
public static int add(int a, int b) {
} else {
return b;
Section 85. 3: Types of Recursion
Section 85. 4: Computing the Nth Fibonacci Number
Section 85. 5: StackOverflowError & recursion to loop
Example
public static void recursion(int depth) {
Workaround
Example
Section 85. 6: Computing the Nth power of a number
Section 85. 7: Traversing a Tree data structure with recursion
Section 85. 8: Reverse a string using Recursion
Section 85. 9: Computing the sum of integers from 1 to N
Chapter 86: Converting to and from Strings
Section 86. 1: Converting String to other datatypes
Section 86. 2: Conversion to / from bytes
Section 86. 3: Base64 Encoding / Decoding
Section 86. 4: Converting other datatypes to String
Section 86. 5: Getting a \'String\' from an \'InputStream\'
Chapter 87: Random Number Generation
Section 87. 1: Pseudo Random Numbers
Section 87. 2: Pseudo Random Numbers in Specific Range
Section 87. 3: Generating cryptographically secure pseudorandom numbers
public class Foo {
Section 87. 4: Generating Random Numbers with a Specified Seed
Section 87. 5: Select random numbers without duplicates
break;
Section 87.6: Generating Random number using apachecommon lang3
Chapter 88: Singletons
Section 88. 1: Enum Singleton
Section 88. 2: Singleton without use of Enum (eager initialization)
Section 88. 3: Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation
Section 88. 4: Thread safe Singleton with double checked locking
Section 88. 5: Extending singleton (singleton inheritance)
Chapter 89: Autoboxing
Section 89. 1: Using int and Integer interchangeably
Section 89. 2: Auto-unboxing may lead to NullPointerException
Section 89. 3: Using Boolean in if statement
Section 89. 4: DiIerent Cases When Integer and int can be used interchangeably
public class Test{
Section 89. 5: Memory and Computational Overhead of Autoboxing
Chapter 90: 2D Graphics in Java
Section 90. 1: Example 1: Draw and Fill a Rectangle Using Java
Section 90. 2: Example 2: Drawing and Filling Oval
Chapter 91: JAXB
Parameter Details
Section 91. 1: Reading an XML file (unmarshalling)
Section 91. 2: Writing an XML file (marshalling an object)
public class User {
private long userID; private String name;
public class XMLCreator {
try {
Jon Skeet
8884321
Section 91. 3: Manual field/property XML mapping configuration
Section 91. 4: Binding an XML namespace to a serializable Java class
Section 91. 5: Using XmlAdapter to generate desired xml format
Section 91. 6: Using XmlAdapter to trim string
Section 91. 7: Automatic field/property XML mapping configuration (@XmlAccessorType)
Section 91. 8: Specifying a XmlAdapter instance to (re)use existing data
Adapter
try {
try {
Chapter 92: Class - Java Reflection
Section 92.1: getClass() method of Object class
class Test {
Chapter 93: Networking
Section 93. 1: Basic Client and Server Communication using a Socket
Server: Start, and wait for incoming connections
while (true) {
Server: Handling clients
Closing Sockets and Handling Exceptions
Basic Server and Client - complete examples
Section 93. 2: Basic Client/Server Communication using UDP
(Datagram)
Section 93. 3: Loading TrustStore and KeyStore from
InputStream
Section 93. 4: Socket example - reading a web page using a simple socket
Section 93. 5: Temporarily disable SSL verification (for testing purposes)
Section 93. 6: Downloading a file using Channel
If the file already exists, it will be overwritten!
Notes
Section 93. 7: Multicasting
Chapter 94: NIO - Networking
Section 94.1: Using Selector to wait for events (example with OP_CONNECT)
} ELSE
Chapter 95: HttpURLConnection
Section 95. 1: Get response body from a URL as a String
Section 95. 2: POST data
try {
} finally {
How it works
Section 95. 3: Delete resource
try {
Section 95. 4: Check if resource exists
Chapter 96: JAX-WS
Section 96.1: Basic Authentication
Chapter 97: Nashorn JavaScript engine
Section 97. 1: Execute JavaScript file
Section 97. 2: Intercept script output
Section 97. 3: Hello Nashorn
Section 97. 4: Evaluate Arithmetic Strings
Section 97. 5: Set global variables
Section 97. 6: Set and get global variables
Section 97. 7: Usage of Java objects in JavaScript in Nashorn
Type If for each .length
Recommendatons:
Section 97. 8: Implementing an interface from script
public static interface Pet {
public void eat();
try {
Chapter 98: Java Native Interface
Parameter JNIEnv
Details
Section 98. 1: Calling C++ methods from Java
Output
Section 98. 2: Calling Java methods from C++ (callback)
C++ code
Section 98. 3: Loading native libraries
Chapter 99: Functional Interfaces
Section 99.1: List of standard Java Runtime Library functional interfaces by signature
Parameter Types Return Type () void
Interface
Chapter 100: Fluent Interface
Section 100 .1: Fluent programming style
Section 100 .2: Truth - Fluent Testing Framework
Chapter 101: Remote Method Invocation (RMI) Section 101.1: Callback: invoking methods on a \"client\"
Overview
The shared remote interfaces
try {
Section 101.2: Simple RMI example with Client and Server implementation
Client package
PersonListLocal.java
Section 101.3: Client-Server: invoking methods in one JVM from another
try {
Chapter 102: Iterator and Iterable
Section 102 .1: Removing elements using an iterator
Section 102 .2: Creating your own Iterable
Section 102 .3: Using Iterable in for loop
Section 102 .4: Using the raw iterator
Chapter 103: Reflection API
Section 103 .1: Dynamic Proxies
public interface MyInterface1{
public interface MyInterface2{
return null;
Section 103 .2: Introduction
Basics
Section 103 .3: Evil Java hacks with Reflection
Crazy Strings
1 = 42
Section 103 .4: Misuse of Reflection API to change private and final variables
class A {
public int age;
public final String rep; public static int count=0;
public A(){
Section 103 .5: Getting and Setting fields
Section 103 .6: Call constructor
Getting the Constructor Object
Section 103 .7: Call constructor of nested class
Section 103 .8: Invoking a method
Section 103 .9: Get Class given its (fully qualified) name
Section 103. 10: Getting the Constants of an Enumeration
Section 103. 11: Call overloaded constructors using reflection
Chapter 104: ByteBu\'Ier
Section 104 .1: Basic Usage - Using DirectByteBu\'Ier
Section 104 .2: Basic Usage - Creating a ByteBu\'Ier
Section 104 .3: Basic Usage - Write Data to the Buier
Chapter 105: Applets
Section 105 .1: Minimal Applet
Section 105 .2: Creating a GUI
Section 105 .3: Open links from within the applet
Section 105 .4: Loading images, audio and other resources
Load and play an audio file
Chapter 106: Expressions
Section 106.1: Operator Precedence
new
Section 106 .2: Expression Basics
The Type of an Expression
Section 106 .3: Expression evaluation order
Simple Example
Section 106 .4: Constant Expressions
Chapter 107: JSON in Java
Section 107 .1: Using Jackson Object Mapper
Section 107 .2: JSON To Object (Gson Library)
Section 107 .3: JSONObject.NULL
Note
Section 107 .4: JSON Builder - chaining methods
Section 107 .5: Object To JSON (Gson Library)
Section 107 .6: JSON Iteration
Iterate over JSONObject properties
Section 107 .7: optXXX vs getXXX methods
Section 107 .8: Extract single element from JSON
Section 107 .9: JsonArray to Java List (Gson Library)
Section 107. 10: Encoding data as JSON
Section 107. 11: Decoding JSON data
Chapter 108: XML Parsing using the JAXP APIs
Section 108 .1: Parsing a document using the StAX API
Section 108 .2: Parsing and navigating a document using the DOM API
Chapter 109: XML XPath Evaluation
Section 109 .1: Parsing multiple XPath Expressions in a single XML
Section 109 .2: Parsing single XPath Expression multiple times in an XML
Section 109 .3: Evaluating a NodeList in an XML document
Chapter 110: XOM - XML Object Model
Section 110 .1: Reading a XML file
try {
Section 110 .2: Writing to a XML File
Example
Chapter 111: Polymorphism
Section 111.1: Method Overriding
Section 111.2: Method Overloading
Section 111.3: Polymorphism and drierent types of overriding
Section 111.4: Virtual functions
public class A{
public void hello(){
Section 111.5: Adding behaviour by adding classes without touching existing code
Chapter 112: Encapsulation
Section 112 .1: Encapsulation to maintain invariants
return a;
public double getDegrees(){
public double getRadians(){
Section 112 .2: Encapsulation to reduce coupling
Chapter 113: Java Agents
Section 113 .1: Modifying classes with agents
Section 113 .2: Adding an agent at runtime
Section 113 .3: Setting up a basic agent
Chapter 114: Varargs (Variable Argument)
Section 114 .1: Working with Varargs parameters
Section 114 .2: Specifying a varargs parameter
Chapter 115: Logging (java.util.logging)
Section 115.1: Logging complex messages (e\'lciently)
Section 115.2: Using the default logger
Section 115.3: Logging levels
Chapter 116: log4j / log4j2
Section 116 .1: Properties-File to log to DB
Section 116 .2: How to get Log4j
Current version (log4j2)
Using Maven:
Using Ivy:
Using Gradle:
Section 116 .3: Setting up property file
Section 116 .4: Basic log4j2.xml configuration file
Section 116 .5: How to use Log4j in Java code
Section 116 .6: Migrating from log4j 1.x to 2.x
Section 116 .7: Filter Logoutput by level (log4j 1.x)
Chapter 117: Oracle O\'lcial Code Standard
Section 117 .1: Naming Conventions
Package names
Class, Interface and Enum Names
Method Names
Variables
Section 117 .2: Class Structure
Order of class members
Section 117 .3: Annotations
Section 117 .4: Import statements
Section 117 .5: Braces
Section 117 .6: Redundant Parentheses
Section 117 .7: Modifiers
strictfp
Section 117 .8: Indentation
Section 117 .9: Literals
Section 117. 10: Package declaration
Section 117. 11: Lambda Expressions
Section 117. 12: Java Source Files
Section 117. 13: Wrapping statements
Section 117. 14: Wrapping Method Declarations
Section 117. 15: Wrapping Expressions
Section 117. 16: Whitespace
Vertical Whitespace
Section 117. 17: Special Characters
Section 117. 18: Variable Declarations
Chapter 118: Character encoding
Section 118 .1: Reading text from a file encoded in UTF-8
Section 118 .2: Writing text to a file in UTF-8
Section 118 .3: Getting byte representation of a string in UTF-8
Chapter 119: Apache Commons Lang
Section 119 .1: Implement equals() method
Section 119 .2: Implement hashCode() method
Section 119 .3: Implement toString() method
Chapter 120: Localization and Internationalization Section 120.1: Locale
Language
Java ResourceBundle
Section 120.2: Automatically formatted Dates using \"locale\"
Section 120.3: String Comparison
Chapter 121: Parallel programming with Fork/Join framework Section 121.1: Fork/Join Tasks in Java
Chapter 122: Non-Access Modifiers
Section 122 .1: final
Usages
Good Programming Practice
private static final List foo; static {
Section 122 .2: static
public class TestStatic {
static {
Section 122 .3: abstract
abstract class Car
Section 122 .4: strictfp
class A{
strictfp void m(){}
Section 122 .5: volatile
Section 122 .6: synchronized
Section 122 .7: transient
Chapter 123: Process
Section 123 .1: Pitfall: Runtime.exec, Process and ProcessBuilder don\'t understand shell syntax
Section 123 .2: Simple example (Java version < 1.5)
Chapter 124: Java Native Access
Section 124.1: Introduction to JNA
What is JNA?
Chapter 125: Modules
Section 125.1: Defining a basic module
Chapter 126: Concurrent Programming (Threads)
Section 126.1: Callable and Future
The result from a Callable task submission is available to be tapped via a Future
Callable Interface
public interface Callable {
Output
Other operations permitted on Future
Section 126 .2: CountDownLatch
Section 126 .3: Basic Multithreading
Section 126 .4: Locks as Synchronisation aids
Section 126 .5: Semaphore
Section 126 .6: Synchronization
public static void bar() {
Section 126 .7: Runnable Object
Example in Java8:
Runnable vs Thread subclass
Section 126 .8: Creating basic deadlocked system
Section 126 .9: Creating a java.lang.Thread instance
Section 126. 10: Atomic operations
Section 126. 11: Exclusive write / Concurrent read access
Section 126. 12: Producer-Consumer
Section 126. 13: Visualizing read/write barriers while using synchronized / volatile
Section 126. 14: Get status of all threads started by your program excluding system threads
Section 126. 15: Using ThreadLocal
Section 126. 16: Multiple producer/consumer example with shared global queue
Section 126. 17: Add two \'int\' arrays using a Threadpool
Section 126. 18: Pausing Execution
Section 126. 19: Thread Interruption / Stopping Threads
Examples :
Example of code that stops handling tasks upon interruption
Example of code that delays setting the interrupt flag until completely done :
Example of code that has a fixed list of tasks but may quit early when interrupted
Chapter 127: Executor, ExecutorService and Thread pools
Section 127.1: ThreadPoolExecutor
Section 127.2: Retrieving value from computation - Callable
Section 127.3: submit() vs execute() exception handling di\'Ierences
Section 127 .4: Handle Rejected Execution
Section 127 .5: Fire and Forget - Runnable Tasks
Section 127 .6: Use cases for drierent types of concurrency
constructs
Section 127 .7: Wait for completion of all tasks in ExecutorService
Section 127 .8: Use cases for drierent types of ExecutorService
Section 127.9: Scheduling tasks to run at a fixed time, after a delay or repeatedly
Starting a task after a fixed delay
Starting tasks at a fixed rate
Section 127.10: Using Thread Pools
Method Description
Chapter 128: ThreadLocal
Section 128 .1: Basic ThreadLocal usage
Section 128 .2: ThreadLocal Java 8 functional initialization
Section 128 .3: Multiple threads with one shared object
try {
Chapter 129: Using ThreadPoolExecutor in MultiThreaded applications.
Section 129.1: Performing Asynchronous Tasks Where No Return Value Is Needed Using a Runnable Class Instance
AsyncExample1
Section 129 .2: Performing Asynchronous Tasks Where a Return Value Is Needed Using a Callable Class Instance
AsyncValueTypeTaskCompleter.java
AsyncExample2.java
Observations of Note:
Section 129 .3: Defining Asynchronous Tasks Inline using Lambdas
Observations of Note:
Chapter 130: Common Java Pitfalls
Section 130 .1: Pitfall: using == to compare primitive wrappers objects such as Integer
Section 130 .2: Pitfall: using == to compare strings
Section 130 .3: Pitfall: forgetting to free resources
Section 130 .4: Pitfall: testing a file before attempting to open it
return;
Section 130 .5: Pitfall: thinking of variables as objects
public final class MutableLocation { public int x;
public int y;
Method calls do NOT pass objects at all
void g() {
void g() {
Section 130 .6: Pitfall: memory leaks
Classloader leak
try {
Section 130 .7: Pitfall: Not understanding that String is an immutable class
Section 130 .8: Pitfall: combining assignment and side-ejects
Chapter 131: Java Pitfalls - Exception usage
Section 131 .1: Pitfall - Catching Throwable, Exception, Error or RuntimeException
try {
Section 131 .2: Pitfall - Ignoring or squashing exceptions
try {
Section 131 .3: Pitfall - Throwing Throwable, Exception, Error or RuntimeException
try {
Section 131 .4: Pitfall - Using exceptions for normal flowcontrol
Section 131 .5: Pitfall - Directly subclassing \'Throwable\'
Section 131 .6: Pitfall - Catching InterruptedException
Section 131 .7: Pitfall - Excessive or inappropriate stacktraces
Chapter 132: Java Pitfalls - Language syntax
Section 132 .1: Pitfall - Missing a ‘break’ in a \'switch\' case
Section 132 .2: Pitfall - Declaring classes with the same names as standard classes
Section 132 .3: Pitfall - Leaving out braces: the \"dangling if\" and \"dangling else\" problems
The \"dangling else\" problem
Section 132 .4: Pitfall - Octal literals
Section 132 .5: Pitfall - Using \'==\' to test a boolean
Section 132 .6: Pitfall - Ignoring method visibility
Section 132 .7: Pitfall: Using \'assert\' for argument or user input validation
Section 132 .8: Pitfall - Wildcard imports can make your code fragile
Section 132 .9: Pitfall - Misplaced semicolons and missing braces
Section 132. 10: Pitfall - Overloading instead of overriding
public final class Person {
Section 132. 11: Pitfall of Auto-Unboxing Null Objects into Primitives
Chapter 133: Java Pitfalls - Threads and Concurrency
Section 133 .1: Pitfall - Extending \'java.lang.Thread\'
Section 133 .2: Pitfall - Too many threads makes an application slower
Section 133 .3: Pitfall: incorrect use of wait() / notify()
The \"Lost Notification\" problem
The \"Illegal Monitor State\" bug
Wait / notify is too low-level
Section 133 .4: Pitfall: Shared variables require proper synchronization
Why can\'t I reproduce this?
Section 133.5: Pitfall - Thread creation is relatively expensive
Chapter 134: Java Pitfalls - Nulls and NullPointerException
Section 134 .1: Pitfall - \"Making good\" unexpected nulls
In summary
Section 134 .2: Pitfall - Using null to represent an empty array or collection
Section 134 .3: Pitfall - Not checking if an I/O stream isn\'t even initialized when closing it
try {
Section 134 .4: Pitfall - Returning null instead of throwing an exception
Section 134 .5: Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions
Section 134 .6: Pitfall - Using \"Yoda notation\" to avoid NullPointerException
Chapter 135: Java Pitfalls - Performance Issues
Section 135 .1: Pitfall - String concatenation in a loop does not scale
Section 135 .2: Pitfall - Using size() to test if a collection is empty is ine\'Ident
Section 135 .3: Pitfall - Interning strings so that you can use == is a bad idea
Costs of using \'intern()\'
Interning as a potential denial of service vector
Section 135 .4: Pitfall - Using \'new\' to create primitive wrapper instances is ine\'Ident
Section 135 .5: Pitfall - E\'lciency concerns with regular expressions
return false;
return true;
Section 135.6: Pitfall - Small reads / writes on unbu\'Iered streams are inelcient
What about character-based streams?
Are buffered streams always a win?
Is this the fastest way to copy a file in Java?
Section 135 .7: Pitfall - Over-use of primitive wrapper types is ine\'Ident
Section 135 .8: Pitfall - The overheads of creating log messages
Solution
Section 135 .9: Pitfall - Iterating a Map\'s keys can be inelcient
Section 135. 10: Pitfall - Calling System.gc() is ineIcient
Section 135.11: Pitfall - Calling \'new String(String)\' is
ine\'Ident
Chapter 136: ServiceLoader
Section 136 .1: Simple ServiceLoader Example
Section 136 .2: Logger Service
Chapter 137: Classloaders
Section 137 .1: Implementing a custom classLoader
Section 137 .2: Loading an external .class file
Section 137 .3: Instantiating and using a classloader
Chapter 138: Creating Images Programmatically
Section 138 .1: Creating a simple image programmatically and displaying it
Section 138 .2: Save an Image to disk
Section 138 .3: Setting individual pixel\'s color in Bu\'Ieredlmage
Section 138 .4: Specifying image rendering quality
Section 138 .5: Creating an image with Bu\'Ieredlmage class
Section 138 .6: Editing and re-using image with Bu\'Ieredlmage
Section 138 .7: How to scale a BuIeredlmage
Chapter 139: Atomic Types
Parameter Description
Section 139 .1: Creating Atomic Types
Section 139 .2: Motivation for Atomic Types
How does one implement Atomic Types?
public void count(int number) {
How do Atomic Types work?
return new;
Chapter 140: RSA Encryption
Section 140.1: An example using a hybrid cryptosystem consisting of OAEP and GCM
try {
Chapter 141: Secure objects
Section 141 .1: SealedObject (javax.crypto.SealedObject)
Section 141 .2: SignedObject (java.security.SignedObject)
Chapter 142: Security & Cryptography
Section 142 .1: Compute Cryptographic Hashes
Section 142 .2: Encrypt and Decrypt Data with Public / Private
Keys
Section 142 .3: Generate Cryptographically Random Data
Section 142 .4: Generate Public / Private Key Pairs
Section 142 .5: Compute and Verify Digital Signatures
Chapter 143: Security & Cryptography
Section 143 .1: The JCE
Section 143 .2: Keys and Key Management
Section 143 .3: Common Java vulnerabilities Section 143.4: Networking Concerns Section 143.5: Randomness and You
Section 143.6: Hashing and Validation
Chapter 144: SecurityManager
Section 144 .1: Sandboxing classes loaded by a ClassLoader
Section 144 .2: Enabling the SecurityManager
Section 144 .3: Implementing policy deny rules
try {
} The DenyingPolicy class
Chapter 145: JNDI
Section 145.1: RMI through JNDI
Chapter 146: sun.misc.Unsafe
Section 146 .1: Instantiating sun.misc.Unsafe via reflection
Section 146 .2: Instantiating sun.misc.Unsafe via bootclasspath
Section 146 .3: Getting Instance of Unsafe
public static final Unsafe UNSAFE;
static {
try {
Section 146 .4: Uses of Unsafe
Use
Chapter 147: Java Memory Model
Section 147 .1: Motivation for the Memory Model
Effects of memory caches
Proper synchronization
The Memory Model
Section 147 .2: Happens-before relationships
Section 147 .3: How to avoid needing to understand the Memory Model
Section 147 .4: Happens-before reasoning applied to some examples
Behavior of \'volatile\' in an example with 2 threads
Chapter 148: Java deployment
Section 148 .1: Making an executable JAR from the command line
Section 148 .2: Creating an UberJAR for an application and its dependencies
Section 148 .3: Creating JAR, WAR and EAR files
Creating JAR, WAR and EAR files using the jar command.
Section 148 .4: Introduction to Java Web Start
An example JNLP file
Demo
Setting up the web server
Launching Web Start applications from the command line
Chapter 149: Java plugin system implementations
Section 149.1: Using URLClassLoader
Chapter 150: JavaBean
Section 150.1: Basic Java Bean
Chapter 151: Java SE 7 Features
Section 151 .1: New Java SE 7 programming language features
Section 151 .2: Binary Literals
Section 151 .3: The try-with-resources statement
Section 151 .4: Underscores in Numeric Literals
Section 151 .5: Type Inference for Generic Instance Creation
Section 151 .6: Strings in switch Statements
Chapter 152: Java SE 8 Features
Section 152.1: New Java SE 8 programming language features
Chapter 153: Dynamic Method Dispatch
What is Dynamic Method Dispatch?
Section 153.1: Dynamic Method Dispatch - Example Code
Chapter 154: Generating Java Code
Section 154.1: Generate POJO From JSON
Chapter 155: JShell
Section 155 .1: Editting Snippets
Section 155 .2: Entering and Exiting JShell
Starting JShell
Section 155 .3: Expressions
Section 155 .4: Methods and Classes
Section 155 .5: Variables
Chapter 156: Stack-Walking API
Section 156.1: Print all stack frames of the current thread
Output:
Section 156.2: Print current caller class
Section 156.3: Showing reflection and other hidden frames
Chapter 157: Sockets
Section 157.1: Read from socket
try (
Chapter 158: Java Sockets
Section 158.1: A simple TCP echo back server
try {
Chapter 159: FTP (File Transfer Protocol)
Parameters Details
Section 159.1: Connecting and Logging Into a FTP Server
try {
Chapter 160: Using Other Scripting Languages in Java
Section 160.1: Evaluating A JavaScript file in -scripting mode of nashorn
Chapter 161: C++ Comparison
Section 161 .1: Static Class Members
private :
Section 161 .2: Classes Defined within Other Constructs
Defined within a Method
Section 161 .3: Pass-by-value & Pass-by-reference
Section 161 .4: Inheritance vs Composition
Section 161 .5: Outcast Downcasting
Section 161 .6: Abstract Methods & Classes
Abstract Method
Chapter 162: Audio
Section 162 .1: Play a MIDI file
Section 162 .2: Play an Audio file Looped
Section 162 .3: Basic audio output
Section 162 .4: Bare metal sound
Chapter 163: Java Print Service
Section 163 .1: Building the Doc that will be printed
Section 163 .2: Discovering the available print services
Section 163 .3: Defining print request attributes
Section 163 .4: Listening print job request status change
Section 163 .5: Discovering the default print service
Section 163 .6: Creating a print job from a print service
Chapter 164: CompletableFuture
Section 164.1: Simple Example of CompletableFuture
Chapter 165: Runtime Commands
Section 165.1: Adding shutdown hooks
Chapter 166: Unit Testing
Section 166.1: What is Unit Testing?
Tests need to be fine-grained
Enter unit-testing
Chapter 167: Asserting
Parameter Details
Section 167.1: Checking arithmetic with assert
Chapter 168: Multi-Release JAR Files
Section 168.1: Example of a multi-release Jar file\'s contents
Section 168 .2: Creating a multi-release Jar using the jar tool
Section 168 .3: URL of a loaded class inside a multi-release Jar
Chapter 169: Just in Time (JIT) compiler
Section 169.1: Overview
Chapter 170: Bytecode Modification
Section 170 .1: What is Bytecode?
What\'s the logic behind this?
I\'d like to learn more about bytecode!
Section 170 .2: How to edit jar files with ASM
try {
Section 170 .3: How to load a ClassNode as a Class
return new
Section 170.4: How to rename classes in a jar file
Section 170.5: Javassist Basic
Chapter 171: Disassembling and Decompiling
Name
Description
Section 171.1: Viewing bytecode with javap
Chapter 172: JMX
Section 172.1: Simple example with Platform MBean Server
try {
Chapter 173: Java Virtual Machine (JVM)
Section 173.1: These are the basics
Chapter 174: XJC
Section 174.1: Generating Java code from simple XSD file
XSD schema (schema.xsd)
Using xjc
} package-info.java
Chapter 175: JVM Flags
Section 175 .1: -XXaggressive
Section 175 .2: -XXallocClearChunks
Section 175 .3: -XXallocClearChunkSize
Section 175 .4: -XXcallProfiling
Section 175 .5: -XXdisableFatSpin
Section 175 .6: -XXdisableGCHeuristics
Section 175 .7: -XXdumpSize
Section 175 .8: -XXexitOnOutOfMemory
Chapter 176: JVM Tool Interface
Section 176.1: Iterate over objects reachable from object (Heap 1.0)
Section 176.2: Get JVMTI environment
Section 176.3: Example of initialization inside of
Agent_OnLoad method
Chapter 177: Java Memory Management
Section 177 .1: Setting the Heap, PermGen and Stack sizes
Setting the Heap, PermGen and default Stack sizes:
Finding the default sizes:
Section 177 .2: Garbage collection
The C++ approach - new and delete
Section 177 .3: Memory leaks in Java
Section 177 .4: Finalization
Section 177 .5: Manually triggering GC
Chapter 178: Java Performance Tuning
Section 178 .1: An evidence-based approach to Java performance tuning
Section 178 .2: Reducing amount of Strings
Section 178 .3: General approach
Chapter 179: Benchmarks
Section 179.1: Simple JMH example
Chapter 180: FileUpload to AWS
Section 180.1: Upload file to s3 bucket
return url;
Front end Function
Chapter 181: AppDynamics and TIBCO BusinessWorks Instrumentation for Easy
Integration
Section 181.1: Example of Instrumentation of all BW Applications in a Single Step for Appdynamics
Appendix A: Installing Java (Standard Edition)
Section A.1: Setting %PATH% and %JAVA_HOME% after installing on Windows
Assumptions:
Section A.2: Installing a Java JDK on Linux
Using the Package Manager
Section A.3: Installing a Java JDK on macOS
Oracle Java 7 and Java 8
Apple Java 6 on macOS
Section A.4: Installing a Java JDK or JRE on Windows
Section A.5: Configuring and switching Java versions on Linux using alternatives
Using Alternatives
Section A.6: What do I need for Java Development
Section A.7: Selecting an appropriate Java SE release
Section A.8: Java release and version naming
JDK version Marketing name
Section A.9: Installing Oracle Java on Linux with latest tar file
Section A.10: Post-installation checking and configuration on Linux
Configuring PATH directly
Appendix B: Java Editions, Versions, Releases and
Distributions
Section B.1: Di\'Ierences between Java SE JRE or Java SE JDK
distributions
Section B.2: Java SE Versions
Java SE Version History
Section B.3: Di\'Ierences between Java EE, Java SE, Java ME and JavaFX
The Java Programming Language Platforms
Java SE
Java ME
Java FX
Appendix C: The Classpath
Section C.1: Di\'Ierent ways to specify the classpath
Section C.2: Adding all JARs in a directory to the classpath
Section C.3: Load a resource from the classpath
Section C.4: Classpath path syntax
Section C.5: Dynamic Classpath
Section C.6: Mapping classnames to pathnames
Source pathname SomeClass.java
Classfile pathname SomeClass.class
Section C.7: The bootstrap classpath
Section C.8: What the classpath means: how searches work
Appendix D: Resources (on classpath)
Section D.1: Loading default configuration
Section D.2: Loading an image from a resource
Section D.3: Finding and reading resources using a classloader
Absolute and relative resource paths
Obtaining a Class or Classloader
Methods
Description
Section D.4: Loading same-name resource from multiple JARs
Credits
You may also like
Git
Hibernate
Python
Spring Framework
Copyright
Title Page
Dedication
Contents
Chapter 1: ‘I’m thinking’ – Oh, but are you?
Chapter 2: Renegade perception
Chapter 3: The Pushbacker sting
Chapter 4: ‘Covid’: The calculated catastrophe
Chapter 5: There is no ‘virus’
Chapter 6: Sequence of deceit
Chapter 7: War on your mind
Chapter 8: ‘Reframing’ insanity
Chapter 9: We must have it? So what is it?
Chapter 10: Human 2.0
Chapter 11: Who controls the Cult?
Chapter 12: Escaping Wetiko
Postscript
Appendix: Cowan-Kaufman-Morell Statement on Virus Isolation
Bibliography
Index