JavaNotesForProfessionals PDF
JavaNotesForProfessionals PDF
Java
Notes for Professionals
®
900+ pages
of professional hints and tricks
Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial Java® group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with Java Language .......................................................................................... 2
Section 1.1: Creating Your First Java Program ........................................................................................................... 2
Chapter 2: Type Conversion .................................................................................................................................... 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 dierent 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 Dierence 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 dierence ................................................................................................. 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 (? :) ............................................................................................................. 59
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 >>>) ................................................................................................... 66
Section 13.7: The Instanceof Operator ...................................................................................................................... 67
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 (<, <=, >, >=) ............................................................................................... 71
Section 13.11: The Equality Operators (==, !=) ............................................................................................................. 71
Section 13.12: The Lambda operator ( -> ) ................................................................................................................ 74
Chapter 14: Primitive Data Types ...................................................................................................................... 75
Section 14.1: The char primitive .................................................................................................................................. 75
Section 14.2: Primitive Types Cheatsheet .................................................................................................................. 75
Section 14.3: The float primitive ................................................................................................................................. 76
Section 14.4: The int primitive ..................................................................................................................................... 77
Section 14.5: Converting Primitives ............................................................................................................................ 78
Section 14.6: Memory consumption of primitives vs. boxed primitives .................................................................. 78
Section 14.7: The double primitive ............................................................................................................................. 79
Section 14.8: The long primitive .................................................................................................................................. 80
Section 14.9: The boolean primitive ........................................................................................................................... 81
Section 14.10: The byte primitive ................................................................................................................................ 81
Section 14.11: Negative value representation ............................................................................................................ 82
Section 14.12: The short primitive ............................................................................................................................... 83
Chapter 15: Constructors ........................................................................................................................................ 84
Section 15.1: Default Constructor ............................................................................................................................... 84
Section 15.2: Call parent constructor ......................................................................................................................... 85
Section 15.3: Constructor with Arguments ................................................................................................................ 86
Chapter 16: Object Class Methods and Constructor ................................................................................. 88
Section 16.1: hashCode() method ............................................................................................................................... 88
Section 16.2: toString() method .................................................................................................................................. 90
Section 16.3: equals() method .................................................................................................................................... 91
Section 16.4: wait() and notify() methods ................................................................................................................. 94
Section 16.5: getClass() method ................................................................................................................................. 95
Section 16.6: clone() method ...................................................................................................................................... 96
Section 16.7: Object constructor ................................................................................................................................. 97
Section 16.8: finalize() method ................................................................................................................................... 99
Chapter 17: Annotations ........................................................................................................................................ 100
Section 17.1: The idea behind Annotations .............................................................................................................. 100
Section 17.2: Defining annotation types .................................................................................................................. 100
Section 17.3: Runtime annotation checks via reflection ........................................................................................ 102
Section 17.4: Built-in annotations ............................................................................................................................. 102
Section 17.5: Compile time processing using annotation processor .................................................................... 105
Section 17.6: Repeating Annotations ....................................................................................................................... 109
Section 17.7: Inherited Annotations .......................................................................................................................... 110
Section 17.8: Getting Annotation values at run-time ............................................................................................. 111
Section 17.9: Annotations for 'this' and receiver parameters ............................................................................... 112
Section 17.10: Add multiple annotation values ....................................................................................................... 113
Chapter 18: Immutable Class .............................................................................................................................. 114
Section 18.1: Example without mutable refs ............................................................................................................ 114
Section 18.2: What is the advantage of immutability? .......................................................................................... 114
Section 18.3: Rules to define immutable classes .................................................................................................... 114
Section 18.4: Example with mutable refs ................................................................................................................. 115
Chapter 19: Immutable Objects ......................................................................................................................... 116
Section 19.1: Creating an immutable version of a type using defensive copying .............................................. 116
Section 19.2: The recipe for an immutable class .................................................................................................... 116
Section 19.3: Typical design flaws which prevent a class from being immutable .............................................. 117
Chapter 20: Visibility (controlling access to members of a class) .................................................. 121
Section 20.1: Private Visibility ................................................................................................................................... 121
Section 20.2: Public Visibility .................................................................................................................................... 121
Section 20.3: Package Visibility ............................................................................................................................... 122
Section 20.4: Protected Visibility .............................................................................................................................. 122
Section 20.5: Summary of Class Member Access Modifiers ................................................................................. 123
Section 20.6: Interface members ............................................................................................................................ 123
Chapter 21: Generics ................................................................................................................................................ 124
Section 21.1: Creating a Generic Class ..................................................................................................................... 124
Section 21.2: Deciding between `T`, `? super T`, and `? extends T` ........................................................................ 126
Section 21.3: The Diamond ....................................................................................................................................... 128
Section 21.4: Declaring a Generic Method .............................................................................................................. 128
Section 21.5: Requiring multiple upper bounds ("extends A & B") ....................................................................... 129
Section 21.6: Obtain class that satisfies generic parameter at runtime .............................................................. 129
Section 21.7: Benefits of Generic class and interface ............................................................................................ 130
Section 21.8: Instantiating a generic type ............................................................................................................... 131
Section 21.9: Creating a Bounded Generic Class ................................................................................................... 131
Section 21.10: Referring to the declared generic type within its own declaration .............................................. 133
Section 21.11: Binding generic parameter to more than 1 type ............................................................................. 134
Section 21.12: Using Generics to auto-cast ............................................................................................................. 135
Section 21.13: Use of instanceof with Generics ....................................................................................................... 135
Section 21.14: Dierent ways for implementing a Generic Interface (or extending a Generic Class) .............. 137
Chapter 22: Classes and Objects ...................................................................................................................... 139
Section 22.1: Overloading Methods ......................................................................................................................... 139
Section 22.2: Explaining what is method overloading and overriding ................................................................ 140
Section 22.3: Constructors ........................................................................................................................................ 142
Section 22.4: Initializing static final fields using a static initializer ........................................................................ 143
Section 22.5: Basic Object Construction and Use .................................................................................................. 144
Section 22.6: Simplest Possible Class ...................................................................................................................... 146
Section 22.7: Object Member vs Static Member .................................................................................................... 146
Chapter 23: Local Inner Class ............................................................................................................................. 148
Section 23.1: Local Inner Class ................................................................................................................................. 148
Chapter 24: Nested and Inner Classes .......................................................................................................... 149
Section 24.1: A Simple Stack Using a Nested Class ............................................................................................... 149
Section 24.2: Static vs Non Static Nested Classes ................................................................................................. 149
Section 24.3: Access Modifiers for Inner Classes ................................................................................................... 151
Section 24.4: Anonymous Inner Classes ................................................................................................................. 152
Section 24.5: Create instance of non-static inner class from outside ................................................................. 153
Section 24.6: Method Local Inner Classes .............................................................................................................. 154
Section 24.7: Accessing the outer class from a non-static inner class ................................................................ 154
Chapter 25: The java.util.Objects Class ......................................................................................................... 156
Section 25.1: Basic use for object null check .......................................................................................................... 156
Section 25.2: Objects.nonNull() method reference use in stream api ................................................................. 156
Chapter 26: Default Methods ............................................................................................................................. 157
Section 26.1: Basic usage of default methods ........................................................................................................ 157
Section 26.2: Accessing overridden default methods from implementing class ............................................... 157
Section 26.3: Why use Default Methods? ............................................................................................................... 158
Section 26.4: Accessing other interface methods within default method ........................................................... 158
Section 26.5: Default method multiple inheritance collision ................................................................................. 159
Section 26.6: Class, Abstract class and Interface method precedence .............................................................. 160
Chapter 27: Packages ............................................................................................................................................ 162
Section 27.1: Using Packages to create classes with the same name ................................................................. 162
Section 27.2: Using Package Protected Scope ...................................................................................................... 162
Chapter 28: Inheritance ......................................................................................................................................... 164
Section 28.1: Inheritance ........................................................................................................................................... 164
Section 28.2: Abstract Classes ................................................................................................................................. 165
Section 28.3: Using 'final' to restrict inheritance and overriding .......................................................................... 167
Section 28.4: The Liskov Substitution Principle ...................................................................................................... 168
Section 28.5: Abstract class and Interface usage: "Is-a" relation vs "Has-a" capability ................................... 168
Section 28.6: Static Inheritance ................................................................................................................................ 172
Section 28.7: Programming to an interface ........................................................................................................... 173
Section 28.8: Overriding in Inheritance ................................................................................................................... 175
Section 28.9: Variable shadowing ........................................................................................................................... 176
Section 28.10: Narrowing and Widening of object references ............................................................................. 176
Section 28.11: Inheritance and Static Methods ........................................................................................................ 177
Chapter 29: Reference Types ............................................................................................................................. 179
Section 29.1: Dierent Reference Types ................................................................................................................. 179
Chapter 30: Strings .................................................................................................................................................. 181
Section 30.1: Comparing Strings .............................................................................................................................. 181
Section 30.2: Changing the case of characters within a String ............................................................................ 183
Section 30.3: Finding a String Within Another String ............................................................................................. 185
Section 30.4: String pool and heap storage ........................................................................................................... 186
Section 30.5: Splitting Strings ................................................................................................................................... 187
Section 30.6: Joining Strings with a delimiter ......................................................................................................... 189
Section 30.7: String concatenation and StringBuilders ......................................................................................... 190
Section 30.8: Substrings ............................................................................................................................................ 191
Section 30.9: Platform independent new line separator ....................................................................................... 192
Section 30.10: Reversing Strings .............................................................................................................................. 192
Section 30.11: Adding toString() method for custom objects ................................................................................ 193
Section 30.12: Remove Whitespace from the Beginning and End of a String .................................................... 194
Section 30.13: Case insensitive switch ..................................................................................................................... 194
Section 30.14: Replacing parts of Strings ................................................................................................................ 195
Section 30.15: Getting the length of a String .......................................................................................................... 196
Section 30.16: Getting the nth character in a String .............................................................................................. 196
Section 30.17: Counting occurrences of a substring or character in a string ..................................................... 196
Chapter 31: StringBuer ....................................................................................................................................... 198
Section 31.1: String Buer class ................................................................................................................................ 198
Chapter 32: StringBuilder ..................................................................................................................................... 199
Section 32.1: Comparing StringBuer, StringBuilder, Formatter and StringJoiner ............................................ 199
Section 32.2: Repeat a String n times ..................................................................................................................... 200
Chapter 33: String Tokenizer .............................................................................................................................. 201
Section 33.1: StringTokenizer Split by space ........................................................................................................... 201
Section 33.2: StringTokenizer Split by comma ',' .................................................................................................... 201
Chapter 34: Splitting a string into fixed length parts ........................................................................... 202
Section 34.1: Break a string up into substrings all of a known length ................................................................. 202
Section 34.2: Break a string up into substrings all of variable length ................................................................. 202
Chapter 35: BigInteger ........................................................................................................................................... 203
Section 35.1: Initialization .......................................................................................................................................... 203
Section 35.2: BigInteger Mathematical Operations Examples ............................................................................. 204
Section 35.3: Comparing BigIntegers ...................................................................................................................... 206
Section 35.4: Binary Logic Operations on BigInteger ............................................................................................ 207
Section 35.5: Generating random BigIntegers ....................................................................................................... 208
Chapter 36: Console I/O ........................................................................................................................................ 210
Section 36.1: Reading user input from the console ................................................................................................ 210
Section 36.2: Aligning strings in console ................................................................................................................. 211
Section 36.3: Implementing Basic Command-Line Behavior ................................................................................ 212
Chapter 37: BigDecimal ......................................................................................................................................... 214
Section 37.1: Comparing BigDecimals ..................................................................................................................... 214
Section 37.2: Using BigDecimal instead of float .................................................................................................... 214
Section 37.3: BigDecimal.valueOf() ......................................................................................................................... 215
Section 37.4: Mathematical operations with BigDecimal ...................................................................................... 215
Section 37.5: Initialization of BigDecimals with value zero, one or ten ................................................................ 218
Section 37.6: BigDecimal objects are immutable .................................................................................................. 218
Chapter 38: NumberFormat ................................................................................................................................ 220
Section 38.1: NumberFormat .................................................................................................................................... 220
Chapter 39: Bit Manipulation .............................................................................................................................. 221
Section 39.1: Checking, setting, clearing, and toggling individual bits. Using long as bit mask ........................ 221
Section 39.2: java.util.BitSet class ............................................................................................................................ 221
Section 39.3: Checking if a number is a power of 2 .............................................................................................. 222
Section 39.4: Signed vs unsigned shift .................................................................................................................... 224
Section 39.5: Expressing the power of 2 ................................................................................................................. 224
Section 39.6: Packing / unpacking values as bit fragments ................................................................................ 225
Chapter 40: Arrays .................................................................................................................................................. 226
Section 40.1: Creating and Initializing Arrays ......................................................................................................... 226
Section 40.2: Creating a List from an Array ........................................................................................................... 232
Section 40.3: Creating an Array from a Collection ................................................................................................ 234
Section 40.4: Multidimensional and Jagged Arrays .............................................................................................. 234
Section 40.5: ArrayIndexOutOfBoundsException .................................................................................................. 236
Section 40.6: Array Covariance ............................................................................................................................... 237
Section 40.7: Arrays to Stream ................................................................................................................................ 238
Section 40.8: Iterating over arrays .......................................................................................................................... 238
Section 40.9: Arrays to a String ............................................................................................................................... 240
Section 40.10: Sorting arrays ................................................................................................................................... 241
Section 40.11: Getting the Length of an Array ........................................................................................................ 243
Section 40.12: Finding an element in an array ....................................................................................................... 243
Section 40.13: How do you change the size of an array? ..................................................................................... 244
Section 40.14: Converting arrays between primitives and boxed types ............................................................. 245
Section 40.15: Remove an element from an array ................................................................................................ 246
Section 40.16: Comparing arrays for equality ........................................................................................................ 247
Section 40.17: Copying arrays .................................................................................................................................. 247
Section 40.18: Casting Arrays ................................................................................................................................... 248
Chapter 41: Streams ............................................................................................................................................... 250
Section 41.1: Using Streams ...................................................................................................................................... 250
Section 41.2: Consuming Streams ............................................................................................................................ 252
Section 41.3: Creating a Frequency Map ................................................................................................................ 254
Section 41.4: Infinite Streams ................................................................................................................................... 254
Section 41.5: Collect Elements of a Stream into a Collection ................................................................................ 255
Section 41.6: Using Streams to Implement Mathematical Functions ................................................................... 257
Section 41.7: Flatten Streams with flatMap() .......................................................................................................... 258
Section 41.8: Parallel Stream .................................................................................................................................... 259
Section 41.9: Creating a Stream ............................................................................................................................... 259
Section 41.10: Finding Statistics about Numerical Streams ................................................................................... 261
Section 41.11: Converting an iterator to a stream ................................................................................................... 261
Section 41.12: Using IntStream to iterate over indexes .......................................................................................... 261
Section 41.13: Concatenate Streams ........................................................................................................................ 262
Section 41.14: Reduction with Streams .................................................................................................................... 262
Section 41.15: Using Streams of Map.Entry to Preserve Initial Values after Mapping ........................................ 265
Section 41.16: IntStream to String ............................................................................................................................. 265
Section 41.17: Finding the First Element that Matches a Predicate ...................................................................... 265
Section 41.18: Using Streams and Method References to Write Self-Documenting Processes ........................ 266
Section 41.19: Converting a Stream of Optional to a Stream of Values .............................................................. 267
Section 41.20: Get a Slice of a Stream ..................................................................................................................... 267
Section 41.21: Create a Map based on a Stream .................................................................................................... 267
Section 41.22: Joining a stream to a single String ................................................................................................. 268
Section 41.23: Sort Using Stream ............................................................................................................................. 269
Section 41.24: Streams of Primitives ........................................................................................................................ 270
Section 41.25: Stream operations categories ......................................................................................................... 270
Section 41.26: Collect Results of a Stream into an Array ...................................................................................... 271
Section 41.27: Generating random Strings using Streams .................................................................................... 271
Chapter 42: InputStreams and OutputStreams ....................................................................................... 272
Section 42.1: Closing Streams .................................................................................................................................. 272
Section 42.2: Reading InputStream into a String ................................................................................................... 272
Section 42.3: Wrapping Input/Output Streams ..................................................................................................... 273
Section 42.4: DataInputStream Example ................................................................................................................ 274
Section 42.5: Writing bytes to an OutputStream ................................................................................................... 274
Section 42.6: Copying Input Stream to Output Stream ......................................................................................... 274
Chapter 43: Readers and Writers .................................................................................................................... 276
Section 43.1: BueredReader ................................................................................................................................... 276
Section 43.2: StringWriter Example ......................................................................................................................... 277
Chapter 44: Preferences ...................................................................................................................................... 278
Section 44.1: Using preferences ............................................................................................................................... 278
Section 44.2: Adding event listeners ....................................................................................................................... 278
Section 44.3: Getting sub-nodes of Preferences .................................................................................................... 279
Section 44.4: Coordinating preferences access across multiple application instances .................................... 280
Section 44.5: Exporting preferences ....................................................................................................................... 280
Section 44.6: Importing preferences ....................................................................................................................... 281
Section 44.7: Removing event listeners .................................................................................................................. 282
Section 44.8: Getting preferences values ............................................................................................................... 283
Section 44.9: Setting preferences values ................................................................................................................ 283
Chapter 45: Collections ......................................................................................................................................... 284
Section 45.1: Removing items from a List within a loop ........................................................................................ 284
Section 45.2: Constructing collections from existing data .................................................................................... 286
Section 45.3: Declaring an ArrayList and adding objects ..................................................................................... 288
Section 45.4: Iterating over Collections ................................................................................................................... 288
Section 45.5: Immutable Empty Collections ........................................................................................................... 290
Section 45.6: Sub Collections ................................................................................................................................... 290
Section 45.7: Unmodifiable Collection ..................................................................................................................... 291
Section 45.8: Pitfall: concurrent modification exceptions ..................................................................................... 292
Section 45.9: Removing matching items from Lists using Iterator ...................................................................... 292
Section 45.10: Join lists ............................................................................................................................................. 293
Section 45.11: Creating your own Iterable structure for use with Iterator or for-each loop .............................. 293
Section 45.12: Collections and Primitive Values ..................................................................................................... 295
Chapter 46: Queues and Deques ...................................................................................................................... 296
Section 46.1: The usage of the PriorityQueue ......................................................................................................... 296
Section 46.2: Deque .................................................................................................................................................. 296
Section 46.3: Stacks .................................................................................................................................................. 297
Section 46.4: BlockingQueue .................................................................................................................................... 298
Section 46.5: LinkedList as a FIFO Queue ............................................................................................................... 299
Section 46.6: Queue Interface .................................................................................................................................. 300
Chapter 47: Collection Factory Methods ..................................................................................................... 301
Section 47.1: List<E> Factory Method Examples .................................................................................................... 301
Section 47.2: Set<E> Factory Method Examples .................................................................................................... 301
Section 47.3: Map<K, V> Factory Method Examples ............................................................................................. 301
Chapter 48: Alternative Collections ................................................................................................................ 302
Section 48.1: Multimap in Guava, Apache and Eclipse Collections ....................................................................... 302
Section 48.2: Apache HashBag, Guava HashMultiset and Eclipse HashBag ...................................................... 304
Section 48.3: Compare operation with collections - Create collections .............................................................. 306
Chapter 49: Concurrent Collections ............................................................................................................... 311
Section 49.1: Thread-safe Collections ..................................................................................................................... 311
Section 49.2: Insertion into ConcurrentHashMap .................................................................................................. 311
Section 49.3: Concurrent Collections ....................................................................................................................... 312
Chapter 50: Choosing Collections .................................................................................................................... 314
Section 50.1: Java Collections Flowchart ................................................................................................................ 314
Chapter 51: super keyword .................................................................................................................................. 315
Section 51.1: Super keyword use with examples ..................................................................................................... 315
Chapter 52: Serialization ...................................................................................................................................... 318
Section 52.1: Basic Serialization in Java .................................................................................................................. 318
Section 52.2: Custom Serialization .......................................................................................................................... 319
Section 52.3: Versioning and serialVersionUID ...................................................................................................... 322
Section 52.4: Serialization with Gson ....................................................................................................................... 323
Section 52.5: Custom JSON Deserialization with Jackson ................................................................................... 324
Chapter 53: Enums ................................................................................................................................................... 327
Section 53.1: Declaring and using a basic enum .................................................................................................... 327
Section 53.2: Enums with constructors ................................................................................................................... 330
Section 53.3: Enums with Abstract Methods ........................................................................................................... 331
Section 53.4: Implements Interface ......................................................................................................................... 332
Section 53.5: Implement Singleton pattern with a single-element enum ............................................................ 333
Section 53.6: Using methods and static blocks ...................................................................................................... 334
Section 53.7: Zero instance enum ........................................................................................................................... 335
Section 53.8: Enum as a bounded type parameter ............................................................................................... 335
Section 53.9: Documenting enums .......................................................................................................................... 335
Section 53.10: Enum constant specific body ........................................................................................................... 336
Section 53.11: Getting the values of an enum ......................................................................................................... 338
Section 53.12: Enum Polymorphism Pattern ........................................................................................................... 338
Section 53.13: Compare and Contains for Enum values ........................................................................................ 339
Section 53.14: Get enum constant by name ........................................................................................................... 340
Section 53.15: Enum with properties (fields) ........................................................................................................... 340
Section 53.16: Convert enum to String .................................................................................................................... 341
Section 53.17: Enums with static fields ..................................................................................................................... 341
Chapter 54: Enum Map .......................................................................................................................................... 343
Section 54.1: Enum Map Book Example .................................................................................................................. 343
Chapter 55: EnumSet class .................................................................................................................................. 344
Section 55.1: Enum Set Example .............................................................................................................................. 344
Chapter 56: Enum starting with number ...................................................................................................... 345
Section 56.1: Enum with name at begining ............................................................................................................. 345
Chapter 57: Lists ....................................................................................................................................................... 346
Section 57.1: Sorting a generic list ........................................................................................................................... 346
Section 57.2: Convert a list of integers to a list of strings ..................................................................................... 347
Section 57.3: Classes implementing List - Pros and Cons ..................................................................................... 347
Section 57.4: Finding common elements between 2 lists ..................................................................................... 349
Section 57.5: In-place replacement of a List element ........................................................................................... 350
Section 57.6: Making a list unmodifiable ................................................................................................................ 351
Section 57.7: Moving objects around in the list ...................................................................................................... 351
Section 57.8: Creating, Adding and Removing element from an ArrayList ........................................................ 351
Section 57.9: Creating a List ..................................................................................................................................... 352
Section 57.10: Positional Access Operations ........................................................................................................... 353
Section 57.11: Iterating over elements in a list ........................................................................................................ 355
Section 57.12: Removing elements from list B that are present in the list A ....................................................... 355
Chapter 58: Sets ........................................................................................................................................................ 357
Section 58.1: Initialization .......................................................................................................................................... 357
Section 58.2: Basics of Set ........................................................................................................................................ 357
Section 58.3: Types and Usage of Sets ................................................................................................................... 358
Section 58.4: Create a list from an existing Set ..................................................................................................... 359
Section 58.5: Eliminating duplicates using Set ....................................................................................................... 359
Section 58.6: Declaring a HashSet with values ...................................................................................................... 360
Chapter 59: List vs Set ........................................................................................................................................... 361
Section 59.1: List vs Set ............................................................................................................................................. 361
Chapter 60: Maps ..................................................................................................................................................... 362
Section 60.1: Iterating Map Entries Eciently ......................................................................................................... 362
Section 60.2: Usage of HashMap ............................................................................................................................ 364
Section 60.3: Using Default Methods of Map from Java 8 ................................................................................... 365
Section 60.4: Iterating through the contents of a Map ......................................................................................... 367
Section 60.5: Merging, combine and composing Maps ........................................................................................ 368
Section 60.6: Add multiple items .............................................................................................................................. 369
Section 60.7: Creating and Initializing Maps ........................................................................................................... 370
Section 60.8: Check if key exists .............................................................................................................................. 372
Section 60.9: Add an element .................................................................................................................................. 372
Section 60.10: Clear the map .................................................................................................................................... 373
Section 60.11: Use custom object as key ................................................................................................................. 373
Chapter 61: LinkedHashMap ................................................................................................................................ 374
Section 61.1: Java LinkedHashMap class ................................................................................................................ 374
Chapter 62: TreeMap and TreeSet .................................................................................................................. 375
Section 62.1: TreeMap of a simple Java type ........................................................................................................ 375
Section 62.2: TreeSet of a simple Java Type ......................................................................................................... 375
Section 62.3: TreeMap/TreeSet of a custom Java type ....................................................................................... 376
Section 62.4: TreeMap and TreeSet Thread Safety .............................................................................................. 377
Chapter 63: SortedMap ......................................................................................................................................... 379
Section 63.1: Introduction to sorted Map ................................................................................................................ 379
Chapter 64: WeakHashMap ................................................................................................................................ 380
Section 64.1: Concepts of WeakHashmap .............................................................................................................. 380
Chapter 65: Hashtable ........................................................................................................................................... 381
Section 65.1: Hashtable ............................................................................................................................................. 381
Chapter 66: Optional ............................................................................................................................................... 382
Section 66.1: Map ....................................................................................................................................................... 382
Section 66.2: Return default value if Optional is empty ........................................................................................ 383
Section 66.3: Throw an exception, if there is no value .......................................................................................... 383
Section 66.4: Lazily provide a default value using a Supplier .............................................................................. 383
Section 66.5: Filter ..................................................................................................................................................... 384
Section 66.6: Using Optional containers for primitive number types .................................................................. 384
Section 66.7: Run code only if there is a value present ......................................................................................... 385
Section 66.8: FlatMap ................................................................................................................................................ 385
Chapter 67: Object References ......................................................................................................................... 386
Section 67.1: Object References as method parameters ...................................................................................... 386
Chapter 68: Exceptions and exception handling ...................................................................................... 389
Section 68.1: Catching an exception with try-catch ............................................................................................... 389
Section 68.2: The try-with-resources statement .................................................................................................... 390
Section 68.3: Custom Exceptions ............................................................................................................................. 393
Section 68.4: Handling InterruptedException ......................................................................................................... 395
Section 68.5: Return statements in try catch block ............................................................................................... 396
Section 68.6: Introduction ......................................................................................................................................... 397
Section 68.7: The Java Exception Hierarchy - Unchecked and Checked Exceptions ........................................ 398
Section 68.8: Creating and reading stacktraces .................................................................................................... 401
Section 68.9: Throwing an exception ...................................................................................................................... 404
Section 68.10: Advanced features of Exceptions ................................................................................................... 406
Section 68.11: The try-finally and try-catch-finally statements ............................................................................ 407
Section 68.12: The 'throws' clause in a method declaration ................................................................................. 409
Chapter 69: Calendar and its Subclasses ..................................................................................................... 411
Section 69.1: Creating Calendar objects ................................................................................................................. 411
Section 69.2: Increasing / Decreasing calendar fields .......................................................................................... 411
Section 69.3: Subtracting calendars ........................................................................................................................ 411
Section 69.4: Finding AM/PM ................................................................................................................................... 411
Chapter 70: Using the static keyword ........................................................................................................... 413
Section 70.1: Reference to non-static member from static context .................................................................... 413
Section 70.2: Using static to declare constants ..................................................................................................... 413
Chapter 71: Properties Class ............................................................................................................................... 415
Section 71.1: Loading properties ............................................................................................................................... 415
Section 71.2: Saving Properties as XML ................................................................................................................... 415
Section 71.3: Property files caveat: trailing whitespace ......................................................................................... 416
Chapter 72: Lambda Expressions ..................................................................................................................... 419
Section 72.1: Introduction to Java lambdas ........................................................................................................... 419
Section 72.2: Using Lambda Expressions to Sort a Collection ............................................................................. 422
Section 72.3: Method References ............................................................................................................................ 423
Section 72.4: Implementing multiple interfaces ..................................................................................................... 425
Section 72.5: Lambda - Listener Example .............................................................................................................. 425
Section 72.6: Java Closures with lambda expressions .......................................................................................... 426
Section 72.7: Lambdas and memory utilization ..................................................................................................... 427
Section 72.8: Using lambda expression with your own functional interface ...................................................... 427
Section 72.9: Traditional style to Lambda style ..................................................................................................... 428
Section 72.10: `return` only returns from the lambda, not the outer method ..................................................... 429
Section 72.11: Lambdas and Execute-around Pattern ........................................................................................... 431
Section 72.12: Using lambda expressions & predicates to get a certain value(s) from a list ........................... 431
Chapter 73: Basic Control Structures ............................................................................................................. 433
Section 73.1: Switch statement ................................................................................................................................. 433
Section 73.2: do...while Loop ..................................................................................................................................... 434
Section 73.3: For Each ............................................................................................................................................... 435
Section 73.4: Continue Statement in Java .............................................................................................................. 436
Section 73.5: If / Else If / Else Control ..................................................................................................................... 436
Section 73.6: For Loops ............................................................................................................................................. 436
Section 73.7: Ternary Operator ............................................................................................................................... 437
Section 73.8: Try ... Catch ... Finally ........................................................................................................................... 438
Section 73.9: Break .................................................................................................................................................... 438
Section 73.10: While Loops ....................................................................................................................................... 439
Section 73.11: If / Else ................................................................................................................................................ 439
Section 73.12: Nested break / continue .................................................................................................................. 439
Chapter 74: BueredWriter ............................................................................................................................... 441
Section 74.1: Write a line of text to File .................................................................................................................... 441
Chapter 75: New File I/O ...................................................................................................................................... 442
Section 75.1: Creating paths ..................................................................................................................................... 442
Section 75.2: Manipulating paths ............................................................................................................................. 442
Section 75.3: Retrieving information about a path ................................................................................................ 442
Section 75.4: Retrieving information using the filesystem .................................................................................... 443
Section 75.5: Reading files ........................................................................................................................................ 444
Section 75.6: Writing files .......................................................................................................................................... 444
Chapter 76: File I/O ................................................................................................................................................. 445
Section 76.1: Migrating from java.io.File to Java 7 NIO (java.nio.file.Path) .......................................................... 445
Section 76.2: Reading an image from a file ........................................................................................................... 447
Section 76.3: File Read/Write Using FileInputStream/FileOutputStream ........................................................... 447
Section 76.4: Reading all bytes to a byte[] ............................................................................................................ 448
Section 76.5: Copying a file using Channel ............................................................................................................. 449
Section 76.6: Writing a byte[] to a file .................................................................................................................... 449
Section 76.7: Stream vs Writer/Reader API ............................................................................................................ 450
Section 76.8: Reading a file with a Scanner ........................................................................................................... 451
Section 76.9: Copying a file using InputStream and OutputStream .................................................................... 452
Section 76.10: Reading from a binary file ............................................................................................................... 452
Section 76.11: Reading a file using Channel and Buer ......................................................................................... 452
Section 76.12: Adding Directories ............................................................................................................................. 453
Section 76.13: Blocking or redirecting standard output / error ............................................................................ 454
Section 76.14: Reading a whole file at once ............................................................................................................ 455
Section 76.15: Locking ............................................................................................................................................... 455
Section 76.16: Reading a file using BueredInputStream ..................................................................................... 455
Section 76.17: Iterate over a directory printing subdirectories in it ...................................................................... 456
Section 76.18: Writing a file using Channel and Buer .......................................................................................... 456
Section 76.19: Writing a file using PrintStream ....................................................................................................... 457
Section 76.20: Iterating over a directory and filter by file extension ................................................................... 457
Section 76.21: Accessing the contents of a ZIP file ................................................................................................ 458
Chapter 77: Scanner ............................................................................................................................................... 459
Section 77.1: General Pattern that does most commonly asked about tasks .................................................... 459
Section 77.2: Using custom delimiters .................................................................................................................... 461
Section 77.3: Reading system input using Scanner ............................................................................................... 461
Section 77.4: Reading file input using Scanner ...................................................................................................... 461
Section 77.5: Read the entire input as a String using Scanner ............................................................................. 462
Section 77.6: Carefully Closing a Scanner .............................................................................................................. 462
Section 77.7: Read an int from the command line ................................................................................................ 463
Chapter 78: Interfaces ........................................................................................................................................... 464
Section 78.1: Implementing multiple interfaces ...................................................................................................... 464
Section 78.2: Declaring and Implementing an Interface ...................................................................................... 465
Section 78.3: Extending an interface ....................................................................................................................... 465
Section 78.4: Usefulness of interfaces .................................................................................................................... 466
Section 78.5: Default methods ................................................................................................................................. 468
Section 78.6: Modifiers in Interfaces ........................................................................................................................ 470
Section 78.7: Using Interfaces with Generics .......................................................................................................... 470
Section 78.8: Strengthen bounded type parameters ............................................................................................ 473
Section 78.9: Implementing interfaces in an abstract class ................................................................................. 473
Chapter 79: Regular Expressions ..................................................................................................................... 475
Section 79.1: Using capture groups ......................................................................................................................... 475
Section 79.2: Using regex with custom behaviour by compiling the Pattern with flags .................................... 476
Section 79.3: Escape Characters ............................................................................................................................. 476
Section 79.4: Not matching a given string .............................................................................................................. 477
Section 79.5: Matching with a regex literal ............................................................................................................. 477
Section 79.6: Matching a backslash ........................................................................................................................ 477
Chapter 80: Comparable and Comparator ................................................................................................ 479
Section 80.1: Sorting a List using Comparable<T> or a Comparator<T> ............................................................ 479
Section 80.2: The compareTo and compare Methods ......................................................................................... 482
Section 80.3: Natural (comparable) vs explicit (comparator) sorting ................................................................ 483
Section 80.4: Creating a Comparator using comparing method ........................................................................ 484
Section 80.5: Sorting Map entries ............................................................................................................................ 484
Chapter 81: Java Floating Point Operations .............................................................................................. 486
Section 81.1: Comparing floating point values ........................................................................................................ 486
Section 81.2: OverFlow and UnderFlow .................................................................................................................. 488
Section 81.3: Formatting the floating point values ................................................................................................ 489
Section 81.4: Strict Adherence to the IEEE Specification ....................................................................................... 489
Chapter 82: Currency and Money .................................................................................................................... 491
Section 82.1: Add custom currency ......................................................................................................................... 491
Chapter 83: Object Cloning .................................................................................................................................. 492
Section 83.1: Cloning performing a deep copy ...................................................................................................... 492
Section 83.2: Cloning using a copy factory ............................................................................................................ 493
Section 83.3: Cloning using a copy constructor ..................................................................................................... 493
Section 83.4: Cloning by implementing Clonable interface .................................................................................. 493
Section 83.5: Cloning performing a shallow copy ................................................................................................. 494
Chapter 84: Recursion ........................................................................................................................................... 496
Section 84.1: The basic idea of recursion ................................................................................................................ 496
Section 84.2: Deep recursion is problematic in Java ............................................................................................ 496
Section 84.3: Types of Recursion ............................................................................................................................ 498
Section 84.4: Computing the Nth Fibonacci Number ............................................................................................ 498
Section 84.5: StackOverflowError & recursion to loop .......................................................................................... 499
Section 84.6: Computing the Nth power of a number ........................................................................................... 501
Section 84.7: Traversing a Tree data structure with recursion ............................................................................ 501
Section 84.8: Reverse a string using Recursion ..................................................................................................... 502
Section 84.9: Computing the sum of integers from 1 to N .................................................................................... 502
Chapter 85: Converting to and from Strings ............................................................................................. 503
Section 85.1: Converting String to other datatypes ............................................................................................... 503
Section 85.2: Conversion to / from bytes ............................................................................................................... 504
Section 85.3: Base64 Encoding / Decoding ........................................................................................................... 504
Section 85.4: Converting other datatypes to String .............................................................................................. 505
Section 85.5: Getting a `String` from an `InputStream` .......................................................................................... 506
Chapter 86: Random Number Generation ................................................................................................... 507
Section 86.1: Pseudo Random Numbers ................................................................................................................. 507
Section 86.2: Pseudo Random Numbers in Specific Range ................................................................................. 507
Section 86.3: Generating cryptographically secure pseudorandom numbers ................................................... 508
Section 86.4: Generating Random Numbers with a Specified Seed .................................................................... 508
Section 86.5: Select random numbers without duplicates .................................................................................... 509
Section 86.6: Generating Random number using apache-common lang3 ........................................................ 510
Chapter 87: Singletons .......................................................................................................................................... 511
Section 87.1: Enum Singleton .................................................................................................................................... 511
Section 87.2: Singleton without use of Enum (eager initialization) ...................................................................... 511
Section 87.3: Thread-safe lazy initialization using holder class | Bill Pugh Singleton implementation ............ 512
Section 87.4: Thread safe Singleton with double checked locking ...................................................................... 512
Section 87.5: Extending singleton (singleton inheritance) .................................................................................... 513
Chapter 88: Autoboxing ........................................................................................................................................ 516
Section 88.1: Using int and Integer interchangeably ............................................................................................. 516
Section 88.2: Auto-unboxing may lead to NullPointerException .......................................................................... 517
Section 88.3: Using Boolean in if statement ........................................................................................................... 517
Section 88.4: Dierent Cases When Integer and int can be used interchangeably .......................................... 518
Section 88.5: Memory and Computational Overhead of Autoboxing ................................................................. 519
Chapter 89: 2D Graphics in Java ...................................................................................................................... 521
Section 89.1: Example 1: Draw and Fill a Rectangle Using Java ........................................................................... 521
Section 89.2: Example 2: Drawing and Filling Oval ................................................................................................ 523
Chapter 90: JAXB ...................................................................................................................................................... 524
Section 90.1: Reading an XML file (unmarshalling) ............................................................................................... 524
Section 90.2: Writing an XML file (marshalling an object) .................................................................................... 524
Section 90.3: Manual field/property XML mapping configuration ...................................................................... 525
Section 90.4: Binding an XML namespace to a serializable Java class .............................................................. 526
Section 90.5: Using XmlAdapter to generate desired xml format ....................................................................... 526
Section 90.6: Using XmlAdapter to trim string ....................................................................................................... 528
Section 90.7: Automatic field/property XML mapping configuration (@XmlAccessorType) ........................... 528
Section 90.8: Specifying a XmlAdapter instance to (re)use existing data .......................................................... 530
Chapter 91: Class - Java Reflection ................................................................................................................. 533
Section 91.1: getClass() method of Object class ..................................................................................................... 533
Chapter 92: Networking ........................................................................................................................................ 534
Section 92.1: Basic Client and Server Communication using a Socket ................................................................ 534
Section 92.2: Basic Client/Server Communication using UDP (Datagram) ....................................................... 536
Section 92.3: Loading TrustStore and KeyStore from InputStream .................................................................... 537
Section 92.4: Socket example - reading a web page using a simple socket ...................................................... 538
Section 92.5: Temporarily disable SSL verification (for testing purposes) ......................................................... 539
Section 92.6: Downloading a file using Channel .................................................................................................... 539
Section 92.7: Multicasting ......................................................................................................................................... 540
Chapter 93: NIO - Networking ............................................................................................................................ 543
Section 93.1: Using Selector to wait for events (example with OP_CONNECT) .................................................. 543
Chapter 94: HttpURLConnection ...................................................................................................................... 545
Section 94.1: Get response body from a URL as a String ..................................................................................... 545
Section 94.2: POST data ........................................................................................................................................... 546
Section 94.3: Delete resource .................................................................................................................................. 546
Section 94.4: Check if resource exists ..................................................................................................................... 547
Chapter 95: JAX-WS ................................................................................................................................................ 549
Section 95.1: Basic Authentication ........................................................................................................................... 549
Chapter 96: Nashorn JavaScript engine ....................................................................................................... 550
Section 96.1: Execute JavaScript file ....................................................................................................................... 550
Section 96.2: Intercept script output ....................................................................................................................... 550
Section 96.3: Hello Nashorn ..................................................................................................................................... 551
Section 96.4: Evaluate Arithmetic Strings ............................................................................................................... 551
Section 96.5: Set global variables ............................................................................................................................ 551
Section 96.6: Set and get global variables ............................................................................................................. 552
Section 96.7: Usage of Java objects in JavaScript in Nashorn ............................................................................ 552
Section 96.8: Implementing an interface from script ............................................................................................ 553
Chapter 97: Java Native Interface .................................................................................................................. 554
Section 97.1: Calling C++ methods from Java ........................................................................................................ 554
Section 97.2: Calling Java methods from C++ (callback) ..................................................................................... 555
Section 97.3: Loading native libraries ..................................................................................................................... 557
Chapter 98: Functional Interfaces ................................................................................................................... 559
Section 98.1: List of standard Java Runtime Library functional interfaces by signature .................................. 559
Chapter 99: Fluent Interface .............................................................................................................................. 560
Section 99.1: Fluent programming style ................................................................................................................. 560
Section 99.2: Truth - Fluent Testing Framework .................................................................................................... 561
Chapter 100: Dequeue Interface ....................................................................................................................... 562
Section 100.1: Adding Elements to Deque ............................................................................................................... 562
Section 100.2: Removing Elements from Deque .................................................................................................... 562
Section 100.3: Retrieving Element without Removing ........................................................................................... 562
Section 100.4: Iterating through Deque .................................................................................................................. 562
Chapter 101: Remote Method Invocation (RMI) ......................................................................................... 564
Section 101.1: Callback: invoking methods on a "client" ......................................................................................... 564
Section 101.2: Simple RMI example with Client and Server implementation ....................................................... 568
Section 101.3: Client-Server: invoking methods in one JVM from another .......................................................... 570
Chapter 102: Iterator and Iterable .................................................................................................................. 573
Section 102.1: Removing elements using an iterator ............................................................................................. 573
Section 102.2: Creating your own Iterable .............................................................................................................. 573
Section 102.3: Using Iterable in for loop .................................................................................................................. 574
Section 102.4: Using the raw iterator ...................................................................................................................... 575
Chapter 103: Reflection API ................................................................................................................................. 576
Section 103.1: Dynamic Proxies ................................................................................................................................ 576
Section 103.2: Introduction ....................................................................................................................................... 577
Section 103.3: Evil Java hacks with Reflection ....................................................................................................... 578
Section 103.4: Misuse of Reflection API to change private and final variables ................................................... 580
Section 103.5: Getting and Setting fields ................................................................................................................. 581
Section 103.6: Call constructor ................................................................................................................................. 582
Section 103.7: Call constructor of nested class ...................................................................................................... 583
Section 103.8: Invoking a method ............................................................................................................................ 583
Section 103.9: Get Class given its (fully qualified) name ....................................................................................... 584
Section 103.10: Getting the Constants of an Enumeration .................................................................................... 584
Section 103.11: Call overloaded constructors using reflection ............................................................................... 585
Chapter 104: ByteBuer ....................................................................................................................................... 587
Section 104.1: Basic Usage - Using DirectByteBuer ............................................................................................ 587
Section 104.2: Basic Usage - Creating a ByteBuer ............................................................................................. 587
Section 104.3: Basic Usage - Write Data to the Buer .......................................................................................... 588
Chapter 105: Applets ............................................................................................................................................... 589
Section 105.1: Minimal Applet ................................................................................................................................... 589
Section 105.2: Creating a GUI ................................................................................................................................... 590
Section 105.3: Open links from within the applet ................................................................................................... 590
Section 105.4: Loading images, audio and other resources ................................................................................. 591
Chapter 106: Expressions ...................................................................................................................................... 593
Section 106.1: Operator Precedence ........................................................................................................................ 593
Section 106.2: Expression Basics .............................................................................................................................. 594
Section 106.3: Expression evaluation order ............................................................................................................ 595
Section 106.4: Constant Expressions ....................................................................................................................... 596
Chapter 107: JSON in Java .................................................................................................................................. 599
Section 107.1: Using Jackson Object Mapper ......................................................................................................... 599
Section 107.2: JSON To Object (Gson Library) ....................................................................................................... 600
Section 107.3: JSONObject.NULL ............................................................................................................................. 600
Section 107.4: JSON Builder - chaining methods ................................................................................................... 601
Section 107.5: Object To JSON (Gson Library) ....................................................................................................... 601
Section 107.6: JSON Iteration ................................................................................................................................... 601
Section 107.7: optXXX vs getXXX methods ............................................................................................................. 602
Section 107.8: Extract single element from JSON .................................................................................................. 602
Section 107.9: JsonArray to Java List (Gson Library) ........................................................................................... 602
Section 107.10: Encoding data as JSON .................................................................................................................. 603
Section 107.11: Decoding JSON data ....................................................................................................................... 603
Chapter 108: XML Parsing using the JAXP APIs ......................................................................................... 605
Section 108.1: Parsing a document using the StAX API .......................................................................................... 605
Section 108.2: Parsing and navigating a document using the DOM API ............................................................. 606
Chapter 109: XML XPath Evaluation ................................................................................................................ 608
Section 109.1: Parsing multiple XPath Expressions in a single XML ...................................................................... 608
Section 109.2: Parsing single XPath Expression multiple times in an XML .......................................................... 608
Section 109.3: Evaluating a NodeList in an XML document .................................................................................. 609
Chapter 110: XOM - XML Object Model ........................................................................................................... 610
Section 110.1: Reading a XML file .............................................................................................................................. 610
Section 110.2: Writing to a XML File ......................................................................................................................... 612
Chapter 111: Polymorphism .................................................................................................................................. 615
Section 111.1: Method Overriding ............................................................................................................................... 615
Section 111.2: Method Overloading ........................................................................................................................... 616
Section 111.3: Polymorphism and dierent types of overriding ............................................................................ 617
Section 111.4: Virtual functions .................................................................................................................................. 620
Section 111.5: Adding behaviour by adding classes without touching existing code .......................................... 621
Chapter 112: Encapsulation .................................................................................................................................. 623
Section 112.1: Encapsulation to maintain invariants ............................................................................................... 623
Section 112.2: Encapsulation to reduce coupling .................................................................................................... 624
Chapter 113: Java Agents ...................................................................................................................................... 625
Section 113.1: Modifying classes with agents ........................................................................................................... 625
Section 113.2: Adding an agent at runtime ............................................................................................................. 625
Section 113.3: Setting up a basic agent .................................................................................................................... 626
Chapter 114: Varargs (Variable Argument) ................................................................................................ 627
Section 114.1: Working with Varargs parameters ................................................................................................... 627
Section 114.2: Specifying a varargs parameter ...................................................................................................... 627
Chapter 115: Logging (java.util.logging) ....................................................................................................... 628
Section 115.1: Logging complex messages (eciently) ......................................................................................... 628
Section 115.2: Using the default logger ................................................................................................................... 629
Section 115.3: Logging levels .................................................................................................................................... 630
Chapter 116: log4j / log4j2 .................................................................................................................................. 632
Section 116.1: Properties-File to log to DB ............................................................................................................... 632
Section 116.2: How to get Log4j ................................................................................................................................ 632
Section 116.3: Setting up property file ...................................................................................................................... 633
Section 116.4: Basic log4j2.xml configuration file ................................................................................................... 634
Section 116.5: How to use Log4j in Java code ........................................................................................................ 634
Section 116.6: Migrating from log4j 1.x to 2.x ........................................................................................................... 635
Section 116.7: Filter Logoutput by level (log4j 1.x) ................................................................................................... 636
Chapter 117: Oracle Ocial Code Standard ............................................................................................... 637
Section 117.1: Naming Conventions .......................................................................................................................... 637
Section 117.2: Class Structure ................................................................................................................................... 638
Section 117.3: Annotations ......................................................................................................................................... 639
Section 117.4: Import statements ............................................................................................................................. 639
Section 117.5: Braces ................................................................................................................................................. 640
Section 117.6: Redundant Parentheses .................................................................................................................... 641
Section 117.7: Modifiers .............................................................................................................................................. 641
Section 117.8: Indentation .......................................................................................................................................... 642
Section 117.9: Literals ................................................................................................................................................. 642
Section 117.10: Package declaration ........................................................................................................................ 642
Section 117.11: Lambda Expressions ......................................................................................................................... 642
Section 117.12: Java Source Files .............................................................................................................................. 643
Section 117.13: Wrapping statements ....................................................................................................................... 643
Section 117.14: Wrapping Method Declarations ...................................................................................................... 644
Section 117.15: Wrapping Expressions ...................................................................................................................... 644
Section 117.16: Whitespace ........................................................................................................................................ 645
Section 117.17: Special Characters ............................................................................................................................ 645
Section 117.18: Variable Declarations ....................................................................................................................... 646
Chapter 118: Character encoding ..................................................................................................................... 647
Section 118.1: Reading text from a file encoded in UTF-8 ..................................................................................... 647
Section 118.2: Writing text to a file in UTF-8 ............................................................................................................ 647
Section 118.3: Getting byte representation of a string in UTF-8 ........................................................................... 648
Chapter 119: Apache Commons Lang ............................................................................................................. 649
Section 119.1: Implement equals() method .............................................................................................................. 649
Section 119.2: Implement hashCode() method ....................................................................................................... 649
Section 119.3: Implement toString() method ........................................................................................................... 650
Chapter 120: Localization and Internationalization ................................................................................ 652
Section 120.1: Locale .................................................................................................................................................. 652
Section 120.2: Automatically formatted Dates using "locale" .............................................................................. 653
Section 120.3: String Comparison ............................................................................................................................ 653
Chapter 121: Parallel programming with Fork/Join framework ...................................................... 654
Section 121.1: Fork/Join Tasks in Java .................................................................................................................... 654
Chapter 122: Non-Access Modifiers ................................................................................................................. 656
Section 122.1: final ...................................................................................................................................................... 656
Section 122.2: static ................................................................................................................................................... 657
Section 122.3: abstract .............................................................................................................................................. 658
Section 122.4: strictfp ................................................................................................................................................ 659
Section 122.5: volatile ................................................................................................................................................ 659
Section 122.6: synchronized ..................................................................................................................................... 660
Section 122.7: transient ............................................................................................................................................. 661
Chapter 123: Process ............................................................................................................................................... 662
Section 123.1: Pitfall: Runtime.exec, Process and ProcessBuilder don't understand shell syntax ...................... 662
Section 123.2: Simple example (Java version < 1.5) ............................................................................................... 664
Chapter 124: Java Native Access ..................................................................................................................... 665
Section 124.1: Introduction to JNA ........................................................................................................................... 665
Chapter 125: Modules .............................................................................................................................................. 666
Section 125.1: Defining a basic module ................................................................................................................... 666
Chapter 126: Concurrent Programming (Threads) .................................................................................. 667
Section 126.1: Callable and Future ........................................................................................................................... 667
Section 126.2: CountDownLatch ............................................................................................................................... 668
Section 126.3: Basic Multithreading ......................................................................................................................... 670
Section 126.4: Locks as Synchronisation aids ......................................................................................................... 671
Section 126.5: Semaphore ........................................................................................................................................ 672
Section 126.6: Synchronization ................................................................................................................................. 673
Section 126.7: Runnable Object ................................................................................................................................ 674
Section 126.8: Creating basic deadlocked system ................................................................................................. 675
Section 126.9: Creating a java.lang.Thread instance ............................................................................................. 677
Section 126.10: Atomic operations ........................................................................................................................... 678
Section 126.11: Exclusive write / Concurrent read access ...................................................................................... 679
Section 126.12: Producer-Consumer ........................................................................................................................ 680
Section 126.13: Visualizing read/write barriers while using synchronized / volatile ........................................... 682
Section 126.14: Get status of all threads started by your program excluding system threads ........................ 683
Section 126.15: Using ThreadLocal ........................................................................................................................... 684
Section 126.16: Multiple producer/consumer example with shared global queue ............................................. 685
Section 126.17: Add two `int` arrays using a Threadpool ....................................................................................... 686
Section 126.18: Pausing Execution ............................................................................................................................ 687
Section 126.19: Thread Interruption / Stopping Threads ....................................................................................... 688
Chapter 127: Executor, ExecutorService and Thread pools ................................................................ 691
Section 127.1: ThreadPoolExecutor .......................................................................................................................... 691
Section 127.2: Retrieving value from computation - Callable ............................................................................... 692
Section 127.3: submit() vs execute() exception handling dierences .................................................................. 693
Section 127.4: Handle Rejected Execution .............................................................................................................. 695
Section 127.5: Fire and Forget - Runnable Tasks ................................................................................................... 695
Section 127.6: Use cases for dierent types of concurrency constructs ............................................................. 696
Section 127.7: Wait for completion of all tasks in ExecutorService ...................................................................... 697
Section 127.8: Use cases for dierent types of ExecutorService .......................................................................... 699
Section 127.9: Scheduling tasks to run at a fixed time, after a delay or repeatedly .......................................... 701
Section 127.10: Using Thread Pools ......................................................................................................................... 702
Chapter 128: ThreadLocal .................................................................................................................................... 703
Section 128.1: Basic ThreadLocal usage .................................................................................................................. 703
Section 128.2: ThreadLocal Java 8 functional initialization .................................................................................. 704
Section 128.3: Multiple threads with one shared object ........................................................................................ 705
Chapter 129: Using ThreadPoolExecutor in MultiThreaded applications. .................................... 707
Section 129.1: Performing Asynchronous Tasks Where No Return Value Is Needed Using a Runnable Class
Instance .............................................................................................................................................................. 707
Section 129.2: Performing Asynchronous Tasks Where a Return Value Is Needed Using a Callable Class
Instance .............................................................................................................................................................. 708
Section 129.3: Defining Asynchronous Tasks Inline using Lambdas .................................................................... 711
Chapter 130: Common Java Pitfalls ................................................................................................................ 713
Section 130.1: Pitfall: using == to compare primitive wrappers objects such as Integer ..................................... 713
Section 130.2: Pitfall: using == to compare strings ................................................................................................. 714
Section 130.3: Pitfall: forgetting to free resources ................................................................................................. 715
Section 130.4: Pitfall: testing a file before attempting to open it .......................................................................... 716
Section 130.5: Pitfall: thinking of variables as objects ........................................................................................... 718
Section 130.6: Pitfall: memory leaks ........................................................................................................................ 721
Section 130.7: Pitfall: Not understanding that String is an immutable class ....................................................... 722
Section 130.8: Pitfall: combining assignment and side-eects ............................................................................. 722
Chapter 131: Java Pitfalls - Exception usage .............................................................................................. 724
Section 131.1: Pitfall - Catching Throwable, Exception, Error or RuntimeException ............................................ 724
Section 131.2: Pitfall - Ignoring or squashing exceptions ....................................................................................... 725
Section 131.3: Pitfall - Throwing Throwable, Exception, Error or RuntimeException ........................................... 726
Section 131.4: Pitfall - Using exceptions for normal flowcontrol ........................................................................... 727
Section 131.5: Pitfall - Directly subclassing `Throwable` ......................................................................................... 728
Section 131.6: Pitfall - Catching InterruptedException ............................................................................................ 728
Section 131.7: Pitfall - Excessive or inappropriate stacktraces .............................................................................. 730
Chapter 132: Java Pitfalls - Language syntax ........................................................................................... 731
Section 132.1: Pitfall - Missing a ‘break’ in a 'switch' case ...................................................................................... 731
Section 132.2: Pitfall - Declaring classes with the same names as standard classes ........................................ 731
Section 132.3: Pitfall - Leaving out braces: the "dangling if" and "dangling else" problems ............................. 732
Section 132.4: Pitfall - Octal literals .......................................................................................................................... 734
Section 132.5: Pitfall - Using '==' to test a boolean ................................................................................................. 734
Section 132.6: Pitfall - Ignoring method visibility .................................................................................................... 735
Section 132.7: Pitfall: Using 'assert' for argument or user input validation ......................................................... 735
Section 132.8: Pitfall - Wildcard imports can make your code fragile ................................................................. 736
Section 132.9: Pitfall - Misplaced semicolons and missing braces ....................................................................... 737
Section 132.10: Pitfall - Overloading instead of overriding .................................................................................... 738
Section 132.11: Pitfall of Auto-Unboxing Null Objects into Primitives .................................................................... 739
Chapter 133: Java Pitfalls - Threads and Concurrency ......................................................................... 740
Section 133.1: Pitfall - Extending 'java.lang.Thread' ................................................................................................ 740
Section 133.2: Pitfall - Too many threads makes an application slower ............................................................. 741
Section 133.3: Pitfall: incorrect use of wait() / notify() ........................................................................................... 742
Section 133.4: Pitfall: Shared variables require proper synchronization .............................................................. 742
Section 133.5: Pitfall - Thread creation is relatively expensive ............................................................................. 745
Chapter 134: Java Pitfalls - Nulls and NullPointerException ............................................................. 748
Section 134.1: Pitfall - "Making good" unexpected nulls ......................................................................................... 748
Section 134.2: Pitfall - Using null to represent an empty array or collection ...................................................... 749
Section 134.3: Pitfall - Not checking if an I/O stream isn't even initialized when closing it ............................... 750
Section 134.4: Pitfall - Returning null instead of throwing an exception .............................................................. 750
Section 134.5: Pitfall - Unnecessary use of Primitive Wrappers can lead to NullPointerExceptions ................ 751
Section 134.6: Pitfall - Using "Yoda notation" to avoid NullPointerException ...................................................... 752
Chapter 135: Java Pitfalls - Performance Issues ...................................................................................... 753
Section 135.1: Pitfall - String concatenation in a loop does not scale .................................................................. 753
Section 135.2: Pitfall - Using size() to test if a collection is empty is inecient .................................................. 754
Section 135.3: Pitfall - Interning strings so that you can use == is a bad idea ..................................................... 754
Section 135.4: Pitfall - Using 'new' to create primitive wrapper instances is inecient ..................................... 756
Section 135.5: Pitfall - Eciency concerns with regular expressions ................................................................... 756
Section 135.6: Pitfall - Small reads / writes on unbuered streams are inecient ........................................... 759
Section 135.7: Pitfall - Over-use of primitive wrapper types is inecient ............................................................ 761
Section 135.8: Pitfall - The overheads of creating log messages ......................................................................... 762
Section 135.9: Pitfall - Iterating a Map's keys can be inecient ........................................................................... 763
Section 135.10: Pitfall - Calling System.gc() is inecient ....................................................................................... 763
Section 135.11: Pitfall - Calling 'new String(String)' is inecient ............................................................................ 764
Chapter 136: ServiceLoader ................................................................................................................................ 765
Section 136.1: Simple ServiceLoader Example ........................................................................................................ 765
Section 136.2: Logger Service ................................................................................................................................... 766
Chapter 137: Classloaders .................................................................................................................................... 768
Section 137.1: Implementing a custom classLoader ............................................................................................... 768
Section 137.2: Loading an external .class file .......................................................................................................... 768
Section 137.3: Instantiating and using a classloader ............................................................................................. 769
Chapter 138: Creating Images Programmatically ................................................................................... 771
Section 138.1: Creating a simple image programmatically and displaying it ..................................................... 771
Section 138.2: Save an Image to disk ...................................................................................................................... 772
Section 138.3: Setting individual pixel's color in BueredImage ........................................................................... 772
Section 138.4: Specifying image rendering quality ................................................................................................ 773
Section 138.5: Creating an image with BueredImage class ............................................................................... 775
Section 138.6: Editing and re-using image with BueredImage ........................................................................... 776
Section 138.7: How to scale a BueredImage ........................................................................................................ 777
Chapter 139: Atomic Types .................................................................................................................................. 778
Section 139.1: Creating Atomic Types ...................................................................................................................... 778
Section 139.2: Motivation for Atomic Types ............................................................................................................ 778
Chapter 140: RSA Encryption ............................................................................................................................. 782
Section 140.1: An example using a hybrid cryptosystem consisting of OAEP and GCM .................................... 782
Chapter 141: Secure objects ................................................................................................................................ 787
Section 141.1: SealedObject (javax.crypto.SealedObject) ...................................................................................... 787
Section 141.2: SignedObject (java.security.SignedObject) ..................................................................................... 787
Chapter 142: Security & Cryptography ......................................................................................................... 789
Section 142.1: Compute Cryptographic Hashes ...................................................................................................... 789
Section 142.2: Encrypt and Decrypt Data with Public / Private Keys .................................................................. 789
Section 142.3: Generate Cryptographically Random Data ................................................................................... 790
Section 142.4: Generate Public / Private Key Pairs ................................................................................................ 790
Section 142.5: Compute and Verify Digital Signatures .......................................................................................... 791
Chapter 143: Security & Cryptography ......................................................................................................... 792
Section 143.1: The JCE ............................................................................................................................................... 792
Section 143.2: Keys and Key Management ............................................................................................................ 792
Section 143.3: Common Java vulnerabilities .......................................................................................................... 792
Section 143.4: Networking Concerns ....................................................................................................................... 792
Section 143.5: Randomness and You ....................................................................................................................... 792
Section 143.6: Hashing and Validation .................................................................................................................... 792
Chapter 144: SecurityManager ......................................................................................................................... 794
Section 144.1: Sandboxing classes loaded by a ClassLoader ............................................................................... 794
Section 144.2: Enabling the SecurityManager ........................................................................................................ 795
Section 144.3: Implementing policy deny rules ...................................................................................................... 795
Chapter 145: JNDI .................................................................................................................................................... 803
Section 145.1: RMI through JNDI .............................................................................................................................. 803
Chapter 146: sun.misc.Unsafe ............................................................................................................................ 807
Section 146.1: Instantiating sun.misc.Unsafe via reflection .................................................................................... 807
Section 146.2: Instantiating sun.misc.Unsafe via bootclasspath ........................................................................... 807
Section 146.3: Getting Instance of Unsafe .............................................................................................................. 807
Section 146.4: Uses of Unsafe .................................................................................................................................. 808
Chapter 147: Java Memory Model ................................................................................................................... 809
Section 147.1: Motivation for the Memory Model .................................................................................................... 809
Section 147.2: Happens-before relationships ......................................................................................................... 811
Section 147.3: How to avoid needing to understand the Memory Model ............................................................ 812
Section 147.4: Happens-before reasoning applied to some examples ............................................................... 813
Chapter 148: Java deployment ......................................................................................................................... 816
Section 148.1: Making an executable JAR from the command line ..................................................................... 816
Section 148.2: Creating an UberJAR for an application and its dependencies .................................................. 817
Section 148.3: Creating JAR, WAR and EAR files ................................................................................................... 818
Section 148.4: Introduction to Java Web Start ....................................................................................................... 819
Chapter 149: Java plugin system implementations ............................................................................... 822
Section 149.1: Using URLClassLoader ...................................................................................................................... 822
Chapter 150: JavaBean ......................................................................................................................................... 826
Section 150.1: Basic Java Bean ................................................................................................................................ 826
Chapter 151: Java SE 7 Features ....................................................................................................................... 827
Section 151.1: New Java SE 7 programming language features .......................................................................... 827
Section 151.2: Binary Literals .................................................................................................................................... 827
Section 151.3: The try-with-resources statement ................................................................................................... 827
Section 151.4: Underscores in Numeric Literals ...................................................................................................... 828
Section 151.5: Type Inference for Generic Instance Creation ................................................................................ 828
Section 151.6: Strings in switch Statements ............................................................................................................. 828
Chapter 152: Java SE 8 Features ...................................................................................................................... 830
Section 152.1: New Java SE 8 programming language features ......................................................................... 830
Chapter 153: Dynamic Method Dispatch ....................................................................................................... 831
Section 153.1: Dynamic Method Dispatch - Example Code ................................................................................... 831
Chapter 154: Generating Java Code .............................................................................................................. 834
Section 154.1: Generate POJO From JSON ............................................................................................................. 834
Chapter 155: JShell .................................................................................................................................................. 835
Section 155.1: Editting Snippets ................................................................................................................................ 835
Section 155.2: Entering and Exiting JShell ............................................................................................................... 836
Section 155.3: Expressions ........................................................................................................................................ 836
Section 155.4: Methods and Classes ........................................................................................................................ 837
Section 155.5: Variables ............................................................................................................................................ 837
Chapter 156: Stack-Walking API ........................................................................................................................ 838
Section 156.1: Print all stack frames of the current thread .................................................................................... 838
Section 156.2: Print current caller class ................................................................................................................... 839
Section 156.3: Showing reflection and other hidden frames ................................................................................. 839
Chapter 157: Sockets .............................................................................................................................................. 841
Section 157.1: Read from socket .............................................................................................................................. 841
Chapter 158: Java Sockets .................................................................................................................................. 842
Section 158.1: A simple TCP echo back server ........................................................................................................ 842
Chapter 159: FTP (File Transfer Protocol) .................................................................................................... 845
Section 159.1: Connecting and Logging Into a FTP Server .................................................................................... 845
Chapter 160: Using Other Scripting Languages in Java ....................................................................... 850
Section 160.1: Evaluating A JavaScript file in -scripting mode of nashorn .......................................................... 850
Chapter 161: C++ Comparison ............................................................................................................................. 853
Section 161.1: Static Class Members ......................................................................................................................... 853
Section 161.2: Classes Defined within Other Constructs ........................................................................................ 853
Section 161.3: Pass-by-value & Pass-by-reference ................................................................................................ 854
Section 161.4: Inheritance vs Composition .............................................................................................................. 855
Section 161.5: Outcast Downcasting ........................................................................................................................ 856
Section 161.6: Abstract Methods & Classes ............................................................................................................. 856
Chapter 162: Audio .................................................................................................................................................... 858
Section 162.1: Play a MIDI file .................................................................................................................................... 858
Section 162.2: Play an Audio file Looped ................................................................................................................ 859
Section 162.3: Basic audio output ............................................................................................................................ 859
Section 162.4: Bare metal sound .............................................................................................................................. 860
Chapter 163: Java Print Service ........................................................................................................................ 862
Section 163.1: Building the Doc that will be printed ................................................................................................ 862
Section 163.2: Discovering the available print services ......................................................................................... 862
Section 163.3: Defining print request attributes ...................................................................................................... 863
Section 163.4: Listening print job request status change ...................................................................................... 863
Section 163.5: Discovering the default print service .............................................................................................. 865
Section 163.6: Creating a print job from a print service ........................................................................................ 865
Chapter 164: CompletableFuture ..................................................................................................................... 867
Section 164.1: Simple Example of CompletableFuture ........................................................................................... 867
Chapter 165: Runtime Commands .................................................................................................................... 868
Section 165.1: Adding shutdown hooks .................................................................................................................... 868
Chapter 166: Unit Testing ...................................................................................................................................... 869
Section 166.1: What is Unit Testing? ......................................................................................................................... 869
Chapter 167: Asserting ........................................................................................................................................... 872
Section 167.1: Checking arithmetic with assert ....................................................................................................... 872
Chapter 168: Multi-Release JAR Files ............................................................................................................. 873
Section 168.1: Example of a multi-release Jar file's contents ............................................................................... 873
Section 168.2: Creating a multi-release Jar using the jar tool .............................................................................. 873
Section 168.3: URL of a loaded class inside a multi-release Jar .......................................................................... 874
Chapter 169: Just in Time (JIT) compiler ...................................................................................................... 876
Section 169.1: Overview ............................................................................................................................................. 876
Chapter 170: Bytecode Modification ............................................................................................................... 878
Section 170.1: What is Bytecode? ............................................................................................................................. 878
Section 170.2: How to edit jar files with ASM .......................................................................................................... 879
Section 170.3: How to load a ClassNode as a Class .............................................................................................. 881
Section 170.4: How to rename classes in a jar file ................................................................................................. 882
Section 170.5: Javassist Basic .................................................................................................................................. 882
Chapter 171: Disassembling and Decompiling ............................................................................................ 884
Section 171.1: Viewing bytecode with javap ............................................................................................................. 884
Chapter 172: JMX ...................................................................................................................................................... 891
Section 172.1: Simple example with Platform MBean Server ................................................................................ 891
Chapter 173: Java Virtual Machine (JVM) .................................................................................................... 895
Section 173.1: These are the basics .......................................................................................................................... 895
Chapter 174: XJC ....................................................................................................................................................... 896
Section 174.1: Generating Java code from simple XSD file ................................................................................... 896
Chapter 175: JVM Flags ......................................................................................................................................... 899
Section 175.1: -XXaggressive .................................................................................................................................... 899
Section 175.2: -XXallocClearChunks ......................................................................................................................... 899
Section 175.3: -XXallocClearChunkSize .................................................................................................................... 899
Section 175.4: -XXcallProfiling .................................................................................................................................. 899
Section 175.5: -XXdisableFatSpin ............................................................................................................................. 900
Section 175.6: -XXdisableGCHeuristics .................................................................................................................... 900
Section 175.7: -XXdumpSize ...................................................................................................................................... 900
Section 175.8: -XXexitOnOutOfMemory ................................................................................................................... 901
Chapter 176: JVM Tool Interface ...................................................................................................................... 902
Section 176.1: Iterate over objects reachable from object (Heap 1.0) .................................................................. 902
Section 176.2: Get JVMTI environment .................................................................................................................... 904
Section 176.3: Example of initialization inside of Agent_OnLoad method .......................................................... 904
Chapter 177: Java Memory Management .................................................................................................... 906
Section 177.1: Setting the Heap, PermGen and Stack sizes ................................................................................... 906
Section 177.2: Garbage collection ............................................................................................................................ 907
Section 177.3: Memory leaks in Java ....................................................................................................................... 909
Section 177.4: Finalization ......................................................................................................................................... 910
Section 177.5: Manually triggering GC ..................................................................................................................... 911
Chapter 178: Java Performance Tuning ....................................................................................................... 912
Section 178.1: An evidence-based approach to Java performance tuning ........................................................ 912
Section 178.2: Reducing amount of Strings ............................................................................................................ 913
Section 178.3: General approach ............................................................................................................................. 913
Chapter 179: Benchmarks ..................................................................................................................................... 915
Section 179.1: Simple JMH example ......................................................................................................................... 915
Chapter 180: FileUpload to AWS ....................................................................................................................... 918
Section 180.1: Upload file to s3 bucket .................................................................................................................... 918
Chapter 181: AppDynamics and TIBCO BusinessWorks Instrumentation for Easy
Integration ................................................................................................................................................................... 920
Section 181.1: Example of Instrumentation of all BW Applications in a Single Step for Appdynamics ............. 920
Appendix A: Installing Java (Standard Edition) ........................................................................................ 921
Section A.1: Setting %PATH% and %JAVA_HOME% after installing on Windows .............................................. 921
Section A.2: Installing a Java JDK on Linux ........................................................................................................... 922
Section A.3: Installing a Java JDK on macOS ........................................................................................................ 924
Section A.4: Installing a Java JDK or JRE on Windows ........................................................................................ 925
Section A.5: Configuring and switching Java versions on Linux using alternatives .......................................... 926
Section A.6: What do I need for Java Development ............................................................................................. 927
Section A.7: Selecting an appropriate Java SE release ........................................................................................ 927
Section A.8: Java release and version naming ...................................................................................................... 928
Section A.9: Installing Oracle Java on Linux with latest tar file ............................................................................ 928
Section A.10: Post-installation checking and configuration on Linux ................................................................... 929
Appendix B: Java Editions, Versions, Releases and Distributions ................................................... 931
Section B.1: Dierences between Java SE JRE or Java SE JDK distributions .................................................... 931
Section B.2: Java SE Versions .................................................................................................................................. 932
Section B.3: Dierences between Java EE, Java SE, Java ME and JavaFX ....................................................... 933
Appendix C: The Classpath .................................................................................................................................. 935
Section C.1: Dierent ways to specify the classpath ............................................................................................. 935
Section C.2: Adding all JARs in a directory to the classpath ................................................................................ 935
Section C.3: Load a resource from the classpath .................................................................................................. 936
Section C.4: Classpath path syntax ......................................................................................................................... 936
Section C.5: Dynamic Classpath .............................................................................................................................. 937
Section C.6: Mapping classnames to pathnames .................................................................................................. 937
Section C.7: The bootstrap classpath ..................................................................................................................... 937
Section C.8: What the classpath means: how searches work .............................................................................. 938
Appendix D: Resources (on classpath) .......................................................................................................... 939
Section D.1: Loading default configuration ............................................................................................................ 939
Section D.2: Loading an image from a resource ................................................................................................... 939
Section D.3: Finding and reading resources using a classloader ........................................................................ 939
Section D.4: Loading same-name resource from multiple JARs ......................................................................... 941
Credits ............................................................................................................................................................................ 942
You may also like ...................................................................................................................................................... 956
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
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 ($).
cd /path/to/containing/folder/
$ 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.
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
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.
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
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:
You will need to use a compiler (javac) and an executor (java) provided by your JVM. To find out which versions you
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.
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).
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()).
An array (typically called args) of Strings passed as arguments to main function (e.g. from command line
arguments).
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.
System.out.println("Hello, World!");
Element Purpose
this denotes that the subsequent expression will call upon the System class, from the java.lang
System
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.
this is the name of the static field of PrintStream type within the System class containing the standard
out
output functionality.
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.
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
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:
class Member {
private String name;
private String type;
private int level;
private int rank;
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.
//Implicit casting
byte byteVar = 42;
short shortVar = byteVar;
int intVar = shortVar;
long longVar = intvar;
float floatVar = longVar;
double doubleVar = floatVar;
Explicit casting has to be done when the source type has larger range than the target type.
//Explicit casting
double doubleVar = 42.0d;
float floatVar = (float) doubleVar;
long longVar = (long) floatVar;
int intVar = (int) longVar;
short shortVar = (short) intVar;
byte byteVar = (byte) shortVar;
When casting floating point primitives (float, double) to whole number primitives, the number is rounded down.
A char can be cast to/from any numeric type by using the code-point mappings specified by Unicode. A char is
represented in memory as an unsigned 16-bit integer value (2 bytes), so casting to byte (1 byte) will drop 8 of those
bits (this is safe for ASCII characters). The utility methods of the Character class use int (4 bytes) to transfer
to/from code-point values, but a short (2 bytes) would also suffice for storing a Unicode code-point.
Implicit casting happens when the source type extends or implements the target type (casting to a superclass or
interface).
Explicit casting has to be done when the source type is extended or implemented by the target type (casting to a
subtype). This can produce a runtime exception (ClassCastException) when the object being cast is not of the
target type (or the target's subtype).
In this Person class, there is a single variable: name. This variable can be accessed using the getName() method and
changed using the setName(String) method, however, setting a name requires the new name to have a length
greater than 2 characters and to not be null. Using a setter method rather than making the variable name public
allows others to set the value of name with certain restrictions. The same can be applied to the getter method:
In the modified getName() method above, the name is returned only if its length is less than or equal to 16.
Otherwise, "Name is too large" is returned. This allows the programmer to create variables that are reachable
and modifiable however they wish, preventing client classes from editing the variables unwantedly.
We can't access the count variable because it's private. But we can access the getCount() and the setCount(int)
methods because they are public. To some, this might raise the question; why introduce the middleman? Why not
just simply make they count public?
For all intents and purposes, these two are exactly the same, functionality-wise. The difference between them is the
extensibility. Consider what each class says:
First: "I have a method that will give you an int value, and a method that will set that value to another int".
Second: "I have an int that you can set and get as you please."
These might sound similar, but the first is actually much more guarded in its nature; it only lets you interact with its
internal nature as it dictates. This leaves the ball in its court; it gets to choose how the internal interactions occur.
The second has exposed its internal implementation externally, and is now not only prone to external users, but, in
the case of an API, committed to maintaining that implementation (or otherwise releasing a non-backward-
compatible API).
Lets consider if we want to synchronize access to modifying and accessing the count. In the first, this is simple:
but in the second example, this is now nearly impossible without going through and modifying each place where
the count variable is referenced. Worse still, if this is an item that you're providing in a library to be consumed by
others, you do not have a way of performing that modification, and are forced to make the hard choice mentioned
above.
So it begs the question; are public variables ever a good thing (or, at least, not evil)?
I'm unsure. On one hand, you can see examples of public variables that have stood the test of time (IE: the out
variable referenced in System.out). On the other, providing a public variable gives no benefit outside of extremely
minimal overhead and potential reduction in wordiness. My guideline here would be that, if you're planning on
making a variable public, you should judge it against these criteria with extreme prejudice:
1. The variable should have no conceivable reason to ever change in its implementation. This is something
that's extremely easy to screw up (and, even if you do get it right, requirements can change), which is why
getters/setters are the common approach. If you're going to have a public variable, this really needs to be
thought through, especially if released in a library/framework/API.
2. The variable needs to be referenced frequently enough that the minimal gains from reducing verbosity
warrants it. I don't even think the overhead for using a method versus directly referencing should be
considered here. It's far too negligible for what I'd conservatively estimate to be 99.9% of applications.
There's probably more than I haven't considered off the top of my head. If you're ever in doubt, always use
getters/setters.
These private variables cannot be accessed directly from outside the class. Hence they are protected from
unauthorized access. But if you want to view or modify them, you can use Getters and Setters.
getXxx() method will return the current value of the variable xxx, while you can set the value of the variable xxx
using setXxx().
The naming convention of the methods are (in example variable is called variableName):
boolean variables
Public Getters and Setters are part of the Property definition of a Java Bean.
Dereferencing follows the memory address stored in a reference, to the place in memory where the actual object
resides. When an object has been found, the requested method is called (toString in this case).
null indicates the absence of a value, i.e. following the memory address leads nowhere. So there is no object on
which the requested method can be called.
Where:
What happens:
int i = 10;
(For an explanation of the above code, please refer to Getting started with Java Language .)
$ javac HelloWorld.java
This produces a file called "HelloWorld.class", which we can then run as follows:
$ java HelloWorld
Hello world!
1. The source filename "HelloWorld.java" must match the class name in the source file ... which is HelloWorld. If
they don't match, you will get a compilation error.
2. The bytecode filename "HelloWorld.class" corresponds to the classname. If you were to rename the
"HelloWorld.class", you would get an error when your tried to run it.
3. When running a Java application using java, you supply the classname NOT the bytecode filename.
Most practical Java code uses packages to organize the namespace for classes and reduce the risk of accidental
class name collision.
If we wanted to declare the HelloWorld class in a package call com.example, the "HelloWorld.java" would contain
the following Java source:
package com.example;
This source code file needs to stored in a directory tree whose structure corresponds to the package naming.
$ javac com/example/HelloWorld.java
This produces a file called "com/example/HelloWorld.class"; i.e. after compilation, the file structure should look like
this:
$ java com.example.HelloWorld
Hello world!
If your application consists of multiple source code files (and most do!) you can compile them one at a time.
Alternatively, you can compile multiple files at the same time by listing the pathnames:
$ javac *.java
$ javac com/example/*.java
$ javac */**/*.java #Only works on Zsh or with globstar enabled on your shell
This will compile all Java source files in the current directory, in the "com/example" directory, and recursively in
child directories respectively. A third alternative is to supply a list of source filenames (and compiler options) as a
file. For example:
$ javac @sourcefiles
Foo.java
Bar.java
Note: compiling code like this is appropriate for small one-person projects, and for once-off programs. Beyond that,
it is advisable to select and use a Java build tool. Alternatively, most programmers use a Java IDE (e.g. NetBeans,
eclipse, IntelliJ IDEA) which offers an embedded compiler and incremental building of "projects".
Here are a few options for the javac command that are likely to be useful to you
The -d option sets a destination directory for writing the ".class" files.
The -sourcepath option sets a source code search path.
The -cp or -classpath option sets the search path for finding external and previously compiled classes. For
more information on the classpath and how to specify it, refer to the The Classpath Topic.
The -version option prints the compiler's version information.
References
The definitive reference for the javac command is the Oracle manual page for javac.
With very few exceptions (for example the enum keyword, changes to some "internal" classes, etc), these changes
are backwards compatible.
A Java program that was compiled using an older version of the Java toolchain will run on a newer version
Java platform without recompilation.
A Java program that was written in an older version of Java will compile successfully with a new Java compiler.
If you need to (re-)compile older Java code on a newer Java platform to run on the newer platform, you generally
don't need to give any special compilation flags. In a few cases (e.g. if you had used enum as an identifier) you could
use the -source option to disable the new syntax. For example, given the following class:
the following is required to compile the class using a Java 5 compiler (or later):
If you need to compile Java to run on an older Java platforms, the simplest approach is to install a JDK for the oldest
version you need to support, and use that JDK's compiler in your builds.
The code you are compiling must not use Java language constructs that were not available in the version of
Java that you are targeting.
The code must not depend on standard Java classes, fields, methods and so on that were not available in the
older platforms.
Third party libraries that the code depends must also be built for the older platform and available at compile-
time and run-time.
Given the preconditions are met, you can recompile code for an older platform using the -target option. For
example,
will compile the above class to produce bytecodes that are compatible with Java 1.4 or later JVM. (In fact, the -
source option implies a compatible -target, so javac -source 1.4 ... would have the same effect. The
relationship between -source and -target is described in the Oracle documentation.)
Having said that, if you simply use -target or -source, you will still be compiling against the standard class libraries
provided by the compiler's JDK. If you are not careful, you can end up with classes with the correct bytecode
version, but with dependencies on APIs that are not available. The solution is to use the -bootclasspath option. For
example:
will compile against an alternative set of runtime libraries. If the class being compiled has (accidental) dependencies
on newer libraries, this will give you compilation errors.
However, these tools are not required to generate the Javadoc HTML; this can be done using the command line
javadoc tool.
javadoc JavaFile.java
A more practical use of the command line tool, which will recursively read all java files in [source-directory],
create documentation for [package.name] and all sub-packages, and place the generated HTML in the [docs-
directory] is:
/**
* Brief summary of this class, ending with a period.
*
* It is common to leave a blank line between the summary and further details.
* The summary (everything before the first period) is used in the class or package
* overview section.
*
* The following inline tags can be used (not an exhaustive list):
* {@link some.other.class.Documentation} for linking to other docs or symbols
* {@link some.other.class.Documentation Some Display Name} the link's appearance can be
* customized by adding a display name after the doc or symbol locator
* {@code code goes here} for formatting as code
* {@literal <>[]()foo} for interpreting literal text without converting to HTML markup
* or other tags.
*
* Optionally, the following tags may be used at the end of class documentation
* (not an exhaustive list):
*
* @author John Doe
* @version 1.0
* @since 5/10/15
* @see some.other.class.Documentation
* @deprecated This class has been replaced by some.other.package.BetterFileReader
*
The same tags and format used for Classes can be used for Enums and Interfaces as well.
/**
* Brief summary of method, ending with a period.
*
* Further description of method and what it does, including as much detail as is
* appropriate. Inline tags such as
* {@code code here}, {@link some.other.Docs}, and {@literal text here} can be used.
*
* If a method overrides a superclass method, {@inheritDoc} can be used to copy the
* documentation
* from the superclass method
*
* @param stream Describe this parameter. Include as much detail as is appropriate
* Parameter docs are commonly aligned as here, but this is optional.
* As with other docs, the documentation before the first period is
* used as a summary.
*
* @return Describe the return values. Include as much detail as is appropriate
* Return type docs are commonly aligned as here, but this is optional.
* As with other docs, the documentation before the first period is used as a
* summary.
*
* @throws IOException Describe when and why this exception can be thrown.
* Exception docs are commonly aligned as here, but this is
* optional.
* As with other docs, the documentation before the first period
* is used as a summary.
* Instead of @throws, @exception can also be used.
*
* @since 2.1.0
* @see some.other.class.Documentation
* @deprecated Describe why this method is outdated. A replacement can also be specified.
*/
public String[] read(InputStream stream) throws IOException {
return null;
}
It is possible to create package-level documentation in Javadocs using a file called package-info.java. This file
must be formatted as below. Leading whitespace and asterisks optional, typically present in each line for formatting
reason
/**
* Package documentation goes here; any documentation before the first period will
* be used as a summary.
*
* It is common practice to leave a blank line between the summary and the rest
* of the documentation; use this space to describe the package in as much detail
* as is appropriate.
*
* Inline tags such as {@code code here}, {@link reference.to.other.Documentation},
* and {@literal text here} can be used in this documentation.
*/
package com.example.foo;
In the above case, you must put this file package-info.java inside the folder of the Java package com.example.foo.
/**
* You can link to the javadoc of an already imported class using {@link ClassName}.
*
* You can also use the fully-qualified name, if the class is not already imported:
* {@link some.other.ClassName}
*
* You can link to members (fields or methods) of a class like so:
* {@link ClassName#someMethod()}
* {@link ClassName#someMethodWithParameters(int, String)}
* {@link ClassName#someField}
* {@link #someMethodInThisClass()} - used to link to members in the current class
*
* You can add a label to a linked javadoc like so:
* {@link ClassName#someMethod() link text}
*/
/**
* This method has a nice explanation but you might found further
* information at the bottom.
*
* @see ClassName#someMethod()
*/
If you want to add links to external resources you can just use the HTML <a> tag. You can use it inline anywhere
or inside both @link and @see tags.
/**
* Wondering how this works? You might want
* to check this <a href="http://stackoverflow.com/">great service</a>.
*
* @see <a href="http://stackoverflow.com/">Stack Overflow</a>
*/
/**
* The Class TestUtils.
* <p>
* This is an {@code inline("code example")}.
* <p>
* You should wrap it in pre tags when writing multiline code.
* <pre>{@code
* Example example1 = new FirstLineExample();
* example1.butYouCanHaveMoreThanOneLine();
* }</pre>
* <p>
* Thanks for reading.
*/
class TestUtils {
Sometimes you may need to put some complex code inside the javadoc comment. The @ sign is specially
problematic. The use of the old <code> tag alongside the {@literal } construct solves the problem.
/**
* Usage:
* <pre><code>
* class SomethingTest {
* {@literal @}Rule
/**
* Fields can be documented as well.
*
* As with other javadocs, the documentation before the first period is used as a
* summary, and is usually separated from the rest of the documentation by a blank
* line.
*
* Documentation for fields can use inline tags, such as:
* {@code code here}
* {@literal text here}
* {@link other.docs.Here}
*
* Field documentation can also make use of the following tags:
*
* @since 2.1.0
* @see some.other.class.Documentation
* @deprecated Describe why this field is outdated
*/
public static final String CONSTANT_STRING = "foo";
Single Line comments are started by // and may be positioned after a statement on the same line, but not before.
Multi-Line comments are defined between /* and */. They can span multiple lines and may even been positioned
between statements.
/*
As too many inline comments may decrease readability of code, they should be used sparsely in case the code isn't
self-explanatory enough or the design decision isn't obvious.
An additional use case for single-line comments is the use of TAGs, which are short, convention driven keywords.
Some development environments recognize certain conventions for such single-comments. Common examples are
//TODO
//FIXME
//PRJ-1234
https://gwt.googlesource.com/gwt/+/2.8.0-beta1/dev/core/src/com/google/gwt/util/tools/ToolBase.java
An example for handling the command-line myprogram -dir "~/Documents" -port 8888 is:
public MyProgramHandler() {
this.registerHandler(new ArgHandlerDir() {
@Override
public void setDir(File dir) {
this.dir = dir;
}
});
this.registerHandler(new ArgHandlerInt() {
@Override
public String[] getTagArgs() {
return new String[]{"port"};
}
@Override
public void setInt(int value) {
this.port = value;
}
});
}
public static void main(String[] args) {
MyProgramHandler myShell = new MyProgramHandler();
if (myShell.processArgs(args)) {
// main program operation
System.out.println(String.format("port: %d; dir: %s",
myShell.getPort(), myShell.getDir()));
}
System.exit(1);
}
}
ArgHandler also has a method isRequired() which can be overwritten to say that the command-line argument is
required (default return is false so that the argument is optional.
In this example, we will present a series of simple case studies. In each case, the code will produce error messages
if the arguments are unacceptable, and then call System.exit(1) to tell the shell that the command has failed. (We
will assume in each case that the Java code is invoked using a wrapper whose name is "myapp".)
In this case-study, the command requires no arguments. The code illustrates that args.length gives us the number
of command line arguments.
Note that if we neglected to check args.length, the command would crash if the user ran it with too few
command-line arguments.
In this case-study, the command has a couple of (optional) flag options, and requires at least one argument after
the options.
package tommy;
public class Main {
public static void main(String[] args) {
boolean feelMe = false;
boolean seeMe = false;
int index;
loop: for (index = 0; index < args.length; index++) {
String opt = args[index];
switch (opt) {
case "-c":
seeMe = true;
break;
case "-f":
feelMe = true;
As you can see, processing the arguments and options gets rather cumbersome if the command syntax is
complicated. It is advisable to use a "command line parsing" library; see the other examples.
When the java command starts the virtual machine, it loads the specified entry-point classes and tries to find main.
If successful, the arguments from command line are converted to Java String objects and assembled into an array.
If main is invoked like this, the array will not be null and won't contain any null entries.
It is conventional to declare the class as public but this not strictly necessary. From Java 5 onward, the main
method's argument type may be a String varargs instead of a string array. main can optionally throw exceptions,
and its parameter can be named anything, but conventionally it is args.
JavaFX entry-points
From Java 8 onwards the java command can also directly launch a JavaFX application. JavaFX is documented in the
JavaFX tag, but a JavaFX entry-point must do the following:
Extend javafx.application.Application
Be public and not abstract
Not be generic or nested
Have an explicit or implicit public no-args constructor
when trying to run the java command, this means that there is no java command on your shell's command search
path. The cause could be:
Refer to "Installing Java" for the steps that you need to take.
This error message is output by the java command if it has been unable to find / load the entry-point class that you
have specified. In general terms, there are three broad reasons that this can happen:
You have specified an entry point class that does not exist.
The class exists, but you have specified it incorrectly.
The class exists and you have specified it correctly, but Java cannot it find it because the classpath is
incorrect.
If you have source code for a class, then the full name consists of the package name and the simple
class name. The instance the "Main" class is declared in the package "com.example.myapp" then its full
name is "com.example.myapp.Main".
If you have a compiled class file, you can find the class name by running javap on it.
If the class file is in a directory, you can infer the full class name from the directory names.
If the class file is in a JAR or ZIP file, you can infer the full class name from the file path in the JAR or ZIP
file.
2. Look at the error message from the java command. The message should end with the full class name that
java is trying to use.
Check that it exactly matches the full classname for the entry-point class.
It should not end with ".java" or ".class".
It should not contain slashes or any other character that is not legal in a Java identifier1.
The casing of the name should exactly match the full class name.
3. If you are using the correct classname, make sure that the class is actually on the classpath:
Work out the pathname that the classname maps to; see Mapping classnames to pathnames
Work out what the classpath is; see this example: Different ways to specify the classpath
Look at each of the JAR and ZIP files on the classpath to see if they contain a class with the required
pathname.
Look at each directory to see if the pathname resolves to a file within the directory.
If checking the classpath by hand did not find the issue, you could add the -Xdiag and -XshowSettings options. The
former lists all classes that are loaded, and the latter prints out settings that include the effective classpath for the
JVM.
An executable JAR file with a Main-Class attribute that specifies a class that does not exist.
An executable JAR file with an incorrect Class-Path attribute.
If you mess up2 the options before the classname, the java command may attempt to interpret one of them
This problem happens when the java command is able to find and load the class that you nominated, but is then
unable to find an entry-point method.
If you are trying to run an executable JAR file, then the JAR's manifest has an incorrect "Main-Class" attribute
that specifies a class that is not a valid entry point class.
You have told the java command a class that is not an entry point class.
The entry point class is incorrect; see Entry point classes for more information.
Other Resources
1 - From Java 8 and later, the java command will helpfully map a filename separator ("/" or "") to a period (".").
However, this behavior is not documented in the manual pages.
2 - A really obscure case is if you copy-and-paste a command from a formatted document where the text editor has
used a "long hyphen" instead of a regular hyphen.
Typical Java applications consist of an application-specific code, and various reusable library code that you have
implemented or that has been implemented by third parties. The latter are commonly referred to as library
dependencies, and are typically packaged as JAR files.
Java is a dynamically bound language. When you run a Java application with library dependencies, the JVM needs to
know where the dependencies are so that it can load classes as required. Broadly speaking, there are two ways to
deal with this:
The application and its dependencies can be repackaged into a single JAR file that contains all of the required
classes and resources.
The JVM can be told where to find the dependent JAR files via the runtime classpath.
For an executable JAR file, the runtime classpath is specified by the "Class-Path" manifest attribute. (Editorial Note:
This should be described in a separate Topic on the jar command.) Otherwise, the runtime classpath needs to be
supplied using the -cp option or using the CLASSPATH environment variable.
For example, suppose that we have a Java application in the "myApp.jar" file whose entry point class is
com.example.MyApp. Suppose also that the application depends on library JAR files "lib/library1.jar" and
"lib/library2.jar". We could launch the application using the java command as follows in a command line:
$ # Alternative 1 (preferred)
$ # Alternative 2
$ export CLASSPATH=myApp.jar:lib/library1.jar:lib/library2.jar
$ java com.example.MyApp
(On Windows, you would use ; instead of : as the classpath separator, and you would set the (local) CLASSPATH
variable using set rather than export.)
While a Java developer would be comfortable with that, it is not "user friendly". So it is common practice to write a
simple shell script (or Windows batch file) to hide the details that the user doesn't need to know about. For
example, if you put the following shell script into a file called "myApp", made it executable, and put it into a
directory on the command search path:
#!/bin/bash
# The 'myApp' wrapper script
export DIR=/usr/libexec/myApp
export CLASSPATH=$DIR/myApp.jar:$DIR/lib/library1.jar:$DIR/lib/library2.jar
java com.example.MyApp
Any arguments on the command line will be passed to the Java application via the "$@" expansion. (You can do
something similar with a Windows batch file, though the syntax is different.)
--
Options must appear before the <classname> or the -jar <jarfile> argument to be recognized. Any
arguments after them will be treated as arguments to be passed to Java app that is being run.
Options that do not start with -X or -XX are standard options. You can rely on all Java implementations1 to
support any standard option.
Options that start with -X are non-standard options, and may be withdrawn from one Java version to the
next.
Options that start with -XX are advanced options, and may also be withdrawn.
The -D<property>=<value> option is used to set a property in the system Properties object. This parameter can be
repeated to set different properties.
The main options for controlling the heap and stack sizes are documented in Setting the Heap, PermGen and Stack
sizes. (Editorial note: Garbage Collector options should be described in the same topic.)
The -ea and -da options respectively enable and disable Java assert checking:
Note that enabling to assertion checking is liable to alter the behavior of a Java programming.
The -client and -server options allow you to select between two different forms of the HotSpot VM:
The "client" form is tuned for user applications and offers faster startup.
The "server" form is tuned for long running applications. It takes longer capturing statistic during JVM "warm
up" which allows the JIT compiler to do a better of job of optimizing the native code.
By default, the JVM will run in 64bit mode if possible, depending on the capabilities of the platform. The -d32 and -
d64 options allow you to select the mode explicitly.
1 - Check the official manual for the java command. Sometimes a standard option is described as "subject to
change".
import java.io.File;
Now suppose that we want print the size of a file whose pathname has spaces in it; e.g. /home/steve/Test
File.txt. If we run the command like this:
the shell won't know that /home/steve/Test File.txt is actually one pathname. Instead, it will pass 2 distinct
arguments to the Java application, which will attempt to find their respective file sizes, and fail because files with
those paths (probably) do not exist.
POSIX shells include sh as well derivatives such as bash and ksh. If you are using one of these shells, then you can
solve the problem by quoting the argument.
The double-quotes around the pathname tell the shell that it should be passed as a single argument. The quotes
will be removed when this happens. There are a couple of other ways to do this:
Single (straight) quotes are treated like double-quotes except that they also suppress various expansions within the
argument.
A backslash escapes the following space, and causes it not to be interpreted as an argument separator.
For more comprehensive documentation, including descriptions of how to deal with other special characters in
arguments, please refer to the quoting topic in the Bash documentation.
The fundamental problem for Windows is that at the OS level, the arguments are passed to a child process as a
single string (source). This means that the ultimate responsibility of parsing (or re-parsing) the command line falls
on either program or its runtime libraries. There is lots of inconsistency.
You can put double-quotes around an argument in a java command, and that will allow you to pass
arguments with spaces in them.
However, when you try to combine this with the use of SET and variable substitution in a batch file, it gets
really complicated as to whether double-quotes get removed.
The cmd.exe shell apparently has other escaping mechanisms; e.g. doubling double-quotes, and using ^
escapes.
Assuming that you have an executable JAR file with pathname <jar-path>, you should be able to run it as follows:
If the command requires command-line arguments, add them after the <jar-path>. For example:
If you need to provide additional JVM options on the java command line, they need to go before the -jar option.
Note that a -cp / -classpath option will be ignored if you use -jar. The application's classpath is determined by the
JAR file manifest.
The "HelloWorld" example is described in Creating a new Java program . It consists of a single class called
HelloWorld which satisfies the requirements for an entry-point.
Assuming that the (compiled) "HelloWorld.class" file is in the current directory, it can be launched as follows:
java HelloWorld
We must provide the name of the class: not the pathname for the ".class" file or the ".java" file.
If the class is declared in a package (as most Java classes are), then the class name we supply to the java
command must be the full classname. For instance if SomeClass is declared in the com.example package, then
the full classname will be com.example.SomeClass.
Specifying a classpath
Unless we are using in the java -jar command syntax, the java command looks for the class to be loaded by
searching the classpath; see The Classpath. The above command is relying on the default classpath being (or
including) the current directory. We can be more explicit about this by specifying the classpath to be used using the
-cp option.
This says to make the current directory (which is what "." refers to) the sole entry on the classpath.
The -cp is an option that is processed by the java command. All options that are intended for the java command
should be before the classname. Anything after the class will be treated as an command line argument for the Java
application, and will be passed to application in the String[] that is passed to the main method.
(If no -cp option is provided, the java will use the classpath that is given by the CLASSPATH environment variable. If
that variable is unset or empty, java uses "." as the default classpath.)
java.sql.Date is a wrapper around millisecond value and is used by JDBC to identify an SQL DATE type
In the below example, we use the java.util.Date() constructor, that creates a Date object and initializes it to
represent time to the nearest millisecond. This date is used in the convert(java.util.Date utilDate) method to
return a java.sql.Date object
Example
Output
java.util.Date has both date and time information, whereas java.sql.Date only has date information
2016/04/19 11:45.36
// print it
System.out.println(formattedDate);
Creates a LocalDate
Creates a LocalDateTime
// LocalDate to Date
Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
// Date to LocalDateTime
LocalDateTime localDateTime = date.toInstant().atZone(defaultZoneId).toLocalDateTime();
// LocalDateTime to Date
Date out = Date.from(localDateTime.atZone(defaultZoneId).toInstant());
To create a new date, you will need a Calendar instance. From there you can set the Calendar instance to the date
that you need.
Calendar c = Calendar.getInstance();
This returns a new Calendar instance set to the current time. Calendar has many methods for mutating it's date
and time or setting it outright. In this case, we'll set it to a specific date.
c.set(1974, 6, 2, 8, 0, 0);
Date d = c.getTime();
The getTime method returns the Date instance that we need. Keep in mind that the Calendar set methods only set
one or more fields, they do not set them all. That is, if you set the year, the other fields remain unchanged.
PITFALL
In many cases, this code snippet fulfills its purpose, but keep in mind that two important parts of the date/time are
not defined.
the (1974, 6, 2, 8, 0, 0) parameters are interpreted within the default timezone, defined somewhere
else,
the milliseconds are not set to zero, but filled from the system clock at the time the Calendar instance is
created.
dateFormat.applyPattern("dd-MM-yyyy");
System.out.println(dateFormat.format(today)); //25-02-2016
Note: Here mm (small letter m) denotes minutes and MM (capital M) denotes month. Pay careful attention when
formatting years: capital "Y" (Y) indicates the "week in the year" while lower-case "y" (y) indicates the year.
LocalTime also has a built in toString method that displays the format very nicely.
System.out.println(time);
you can also get, add and subtract hours, minutes, seconds, and nanoseconds from the LocalTime object i.e.
time.plusMinutes(1);
time.getMinutes();
time.minusMinutes(1);
You can turn it into a Date object with the following code:
this class works very nicely within a timer class to simulate an alarm clock.
/**
* Parses the date using the given format.
*
* @param formattedDate the formatted date string
* @param dateFormat the date format which was used to create the string.
* @return the date
*/
public static Date parseDate(String formattedDate, String dateFormat) {
Date date = null;
Here this Date object contains the current date and time when this object was created.
Date objects are best created through a Calendar instance since the use of the data constructors is deprecated and
discouraged. To do se we need to get an instance of the Calendar class from the factory method. Then we can set
year, month and day of month by using numbers or in case of months constants provided py the Calendar class to
improve readability and reduce errors.
Along with date, we can also pass time in the order of hour, minutes and seconds.
//Before example
System.out.printf("Is %1$tF before %2$tF? %3$b%n", today, birthdate,
Boolean.valueOf(today.before(birthdate)));
System.out.printf("Is %1$tF before %1$tF? %3$b%n", today, today,
Boolean.valueOf(today.before(today)));
System.out.printf("Is %2$tF before %1$tF? %3$b%n", today, birthdate,
Boolean.valueOf(birthdate.before(today)));
//After example
System.out.printf("Is %1$tF after %2$tF? %3$b%n", today, birthdate,
//Compare example
System.out.printf("Compare %1$tF to %2$tF: %3$d%n", today, birthdate,
Integer.valueOf(today.compareTo(birthdate)));
System.out.printf("Compare %1$tF to %1$tF: %3$d%n", today, birthdate,
Integer.valueOf(today.compareTo(today)));
System.out.printf("Compare %2$tF to %1$tF: %3$d%n", today, birthdate,
Integer.valueOf(birthdate.compareTo(today)));
//Equal example
System.out.printf("Is %1$tF equal to %2$tF? %3$b%n", today, birthdate,
Boolean.valueOf(today.equals(birthdate)));
System.out.printf("Is %1$tF equal to %2$tF? %3$b%n", birthdate, samebirthdate,
Boolean.valueOf(birthdate.equals(samebirthdate)));
System.out.printf(
"Because birthdate.getTime() -> %1$d is different from samebirthdate.getTime() -> %2$d,
there are millisecondes!%n",
Long.valueOf(birthdate.getTime()), Long.valueOf(samebirthdate.getTime()));
System.out.printf("Is %1$tF equal to %2$tF after clearing ms? %3$b%n", birthdate, samebirthdate,
Boolean.valueOf(birthdate.equals(samebirthdate)));
Version ≥ Java SE 8
isBefore, isAfter, compareTo and equals methods
//Use of LocalDate
final LocalDate now = LocalDate.now();
final LocalDate birthdate2 = LocalDate.of(2012, 6, 30);
final LocalDate birthdate3 = LocalDate.of(2012, 6, 30);
//Hours, minutes, second and nanoOfsecond can also be configured with an other class LocalDateTime
//LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);
//isBefore example
System.out.printf("Is %1$tF before %2$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.isBefore(birthdate2)));
System.out.printf("Is %1$tF before %1$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.isBefore(now)));
System.out.printf("Is %2$tF before %1$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(birthdate2.isBefore(now)));
//isAfter example
System.out.printf("Is %1$tF after %2$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.isAfter(birthdate2)));
System.out.printf("Is %1$tF after %1$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.isAfter(now)));
System.out.printf("Is %2$tF after %1$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(birthdate2.isAfter(now)));
//compareTo example
System.out.printf("Compare %1$tF to %2$tF %3$d%n", now, birthdate2,
Integer.valueOf(now.compareTo(birthdate2)));
//equals example
System.out.printf("Is %1$tF equal to %2$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.equals(birthdate2)));
System.out.printf("Is %1$tF to %2$tF? %3$b%n", birthdate2, birthdate3,
Boolean.valueOf(birthdate2.equals(birthdate3)));
//isEqual example
System.out.printf("Is %1$tF equal to %2$tF? %3$b%n", now, birthdate2,
Boolean.valueOf(now.isEqual(birthdate2)));
System.out.printf("Is %1$tF to %2$tF? %3$b%n", birthdate2, birthdate3,
Boolean.valueOf(birthdate2.isEqual(birthdate3)));
Before Java 8, dates could be compared using java.util.Calendar and java.util.Date classes. Date class offers 4
methods to compare dates :
after(Date when)
before(Date when)
compareTo(Date anotherDate)
equals(Object obj)
after, before, compareTo and equals methods compare the values returned by getTime() method for each date.
Value greater than 0 : when the Date is after the Date argument
Value greater than 0 : when the Date is before the Date argument
Value equals to 0 : when the Date is equal to the Date argument
equals results can be surprising as shown in the example because values, like milliseconds, are not initialize with
the same value if not explicitly given.
Since Java 8
With Java 8 a new Object to work with Date is available java.time.LocalDate. LocalDate implements
ChronoLocalDate, the abstract representation of a date where the Chronology, or calendar system, is pluggable.
To have the date time precision the Object java.time.LocalDateTime has to be used. LocalDate and LocalDateTime
use the same methods name for comparing.
Comparing dates using a LocalDate is different from using ChronoLocalDate because the chronology, or calendar
system are not taken in account the first one.
Because most application should use LocalDate, ChronoLocalDate is not included in examples. Further reading
here.
Most applications should declare method signatures, fields and variables as LocalDate, not
this[ChronoLocalDate] interface.
In case of LocalDate parameter, isAfter, isBefore, isEqual, equals and compareTo now use this method:
equals method check if the parameter reference equals the date first whereas isEqual directly calls compareTo0.
In case of an other class instance of ChronoLocalDate the dates are compared using the Epoch Day. The Epoch Day
count is a simple incrementing count of days where day 0 is 1970-01-01 (ISO).
There are 4 different styles for the text format, SHORT, MEDIUM (this is the default), LONG and FULL, all of which
depend on the locale. If no locale is specified, the system default locale is used.
However, it is possible to display the date represented by the point in time described by the Date object in a
different time zone using e.g. java.text.SimpleDateFormat:
Output:
now, since the method between of the ChronoUnit enumerator takes 2 Temporals as parameters so you can pass
without a problem the LocalDate instances
Date and time with offset information (i.e. no DST changes taken into account)
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.TimeZone;
public class SomeMethodsExamples {
/**
* Has the methods of the class {@link LocalDateTime}
*/
public static void checkLocalDateTime() {
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Local Date time using static now() method ::: >>> "
+ localDateTime);
System.out
.println("Following is a static map in ZoneId class which has mapping of short timezone
names to their Actual timezone names");
System.out.println(ZoneId.SHORT_IDS);
/**
* This has the methods of the class {@link LocalDate}
*/
public static void checkLocalDate() {
LocalDate localDate = LocalDate.now();
System.out.println("Gives date without Time using now() method. >> "
+ localDate);
LocalDate localDate2 = LocalDate.now(ZoneId.of(ZoneId.SHORT_IDS
.get("ECT")));
System.out
.println("now() is overridden to take ZoneID as parametere using this we can get the
same date under different timezones. >> "
+ localDate2);
}
/**
/**
* This has the {@link Instant} class methods.
*/
public static void checkInstant() {
Instant instant = Instant.now();
/**
* This class checks the methods of the {@link Duration} class.
*/
public static void checkDuration() {
// toString() converts the duration to PTnHnMnS format according to ISO
// 8601 standard. If a field is zero its ignored.
System.out.println(Duration.ofDays(2));
}
/**
* Shows Local time without date. It doesn't store or represenet a date and
* time. Instead its a representation of Time like clock on the wall.
*/
public static void checkLocalTime() {
LocalTime localTime = LocalTime.now();
System.out.println("LocalTime :: " + localTime);
}
/**
}
}
In formatting and parsing first you pass a String object to DateTimeFormatter, and in turn use it for formatting or
parsing.
import java.time.*;
import java.time.format.*;
class DateTimeFormat
{
public static void main(String[] args) {
//Parsing
String pattern = "d-MM-yyyy HH:mm";
DateTimeFormatter dtF1 = DateTimeFormatter.ofPattern(pattern);
//Formatting
DateTimeFormatter dtF2 = DateTimeFormatter.ofPattern("EEE d, MMMM, yyyy HH:mm");
System.out.println(ldtf1.format(dtF2) +"\n"+ldtf1.format(dtF3));
}
}
An important notice, instead of using Custom patterns, it is good practice to use predefined formatters. Your code
look more clear and usage of ISO8061 will definitely help you in the long run.
LocalDate.now()
LocalDate t = LocalDate.now().plusDays(1);
In addition to the plus and minus methods, there are a set of "with" methods that can be used to set a particular
field on a LocalDate instance.
LocalDate.now().withMonth(6);
The example above returns a new instance with the month set to June (this differs from java.util.Date where
setMonth was indexed a 0 making June 5).
Because LocalDate manipulations return immutable LocalDate instances, these methods may also be chained
together.
LocalDate ld = LocalDate.now().plusDays(1).plusYears(1);
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
This class does not store or represent a date or time-zone. Instead, it is a description of the local time as seen on a
wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-
zone. This is a value based class, equals method should be used for comparisons.
Fields
You can also add/subtract hours, minutes or seconds from any object of LocalTime.
now.plusHours(1L);
now1.minusMinutes(20L);
}
}
Version ≥ Java SE 7
int i1 = 123456;
int i2 = 123_456;
System.out.println(i1 == i2); // true
Version ≥ Java SE 7
byte color = 1_2_3;
short yearsAnnoDomini= 2_016;
int socialSecurtyNumber = 999_99_9999;
long creditCardNumber = 1234_5678_9012_3456L;
float piFourDecimals = 3.14_15F;
double piTenDecimals = 3.14_15_92_65_35;
This also works using prefixes for binary, octal and hexadecimal bases:
Version ≥ Java SE 7
short binary= 0b0_1_0_1;
int octal = 07_7_7_7_7_7_7_7_0;
long hexBytes = 0xFF_EC_DE_5E;
There are a few rules about underscores which forbid their placement in the following places:
At the beginning or end of a number (e.g. _123 or 123_ are not valid)
Adjacent to a decimal point in a floating point literal (e.g. 1._23 or 1_.23 are not valid)
Prior to an F or L suffix (e.g. 1.23_F or 9999999_L are not valid)
In positions where a string of digits is expected (e.g. 0_xFFFF is not valid)
The octal literal can easily be a trap for semantic errors. If you define a leading '0' to your decimal literals you will
get the wrong value:
For example:
Note that a single string literal may not span multiple source code lines. It is a compilation error for a line-break (or
the end of the source file) to occur before a literal's closing double-quote. For example:
Long strings
If you need a string that is too long to fit on a line, the conventional way to express it is to split it into multiple
literals and use the concatenation operator (+) to join the pieces. For example
An expression like the above consisting of string literals and + satisfies the requirements to be a Constant
Expression. That means that the expression will be evaluated by the compiler and represented at runtime by a
single String object.
For more information on interning and the string pool, refer to the String pool and heap storage example in the
Strings topic.
myMethod(null);
if (objects != null) {
// Do something
}
The null type is rather unusual. It has no name, so you cannot express it in Java source code. (And it has no runtime
representation either.)
The sole purpose of the null type is to be the type of null. It is assignment compatible with all reference types, and
can be type cast to any reference type. (In the latter case, the cast does not entail a runtime type check.)
Finally, null has the property that null instanceof <SomeReferenceType> will evaluate to false, no matter what
the type is.
The <octal> in the above consists of one, two or three octal digits ('0' through '7') which represent a number
between 0 and 255 (decimal).
Note that a backslash followed by any other character is an invalid escape sequence. Invalid escape sequences are
treated as compilation errors by the JLS.
Reference:
Unicode escapes
In addition to the string and character escape sequences described above, Java has a more general Unicode
escaping mechanism, as defined in JLS 3.3. Unicode Escapes. A Unicode escape has the following syntax:
where <hex-digit> is one of '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C',
'D', 'E', 'F'.
A Unicode escape is mapped by the Java compiler to a character (strictly speaking a 16-bit Unicode code unit), and
can be used anywhere in the source code where the mapped character is valid. It is commonly used in character
and string literals when you need to represent a non-ASCII character in a literal.
Escaping in regexes
TBD
For example:
char a = 'a';
char doubleQuote = '"';
char singleQuote = '\'';
The simplest and most common form of integer literal is a decimal integer literal. For example:
Integer literals are unsigned. If you see something like -10 or +10, these are actually expressions using the unary
The range of integer literals of this form have an intrinsic type of int, and must fall in the range zero to 231 or
2,147,483,648.
Note that 231 is 1 greater than Integer.MAX_VALUE. Literals from 0 through to 2147483647 can be used anywhere,
but it is a compilation error to use 2147483648 without a preceding unary
operator. (In other words, it is reserved for expressing the value of Integer.MIN_VALUE.)
int max = 2147483647; // OK
int min = -2147483648; // OK
int tooBig = 2147483648; // ERROR
Note that the distinction between int and long literals is significant in other places. For example
int i = 2147483647;
long l = i + 1; // Produces a negative value because the operation is
// performed using 32 bit arithmetic, and the
// addition overflows
long l2 = i + 1L; // Produces the (intuitively) correct value.
(The JLS syntax rules combine the two decimal forms into a single form. We treat them separately for ease of
explanation.)
The simplest form of floating point literal consists of one or more decimal digits and a decimal point (.) and an
optional suffix (f, F, d or D). The optional suffix allows you to specify that the literal is a float (f or F) or double (d or
D) value. The default (when no suffix is specified) is double.
For example
The meaning of a decimal literal is the IEEE floating point number that is closest to the infinite precision
mathematical Real number denoted by the decimal floating point form. This conceptual value is converted to IEEE
binary floating point representation using round to nearest. (The precise semantics of decimal conversion are
specified in the javadocs for Double.valueOf(String) and Float.valueOf(String), bearing in mind that there are
differences in the number syntaxes.)
Scaled decimal forms consist of simple decimal with an exponent part introduced by an E or e, and followed by a
signed integer. The exponent part is a short hand for multiplying the decimal form by a power of ten, as shown in
the examples below. There is also an optional suffix to distinguish float and double literals. Here are some
examples:
The size of a literal is limited by the representation (float or double). It is a compilation error if the scale factor
results in a value that is too large or too small.
Hexadecimal forms
Starting with Java 6, it is possible to express floating point literals in hexadecimal. The hexadecimal form have an
analogous syntax to the simple and scaled decimal forms with the following differences:
1. Every hexadecimal floating point literal starts with a zero (0) and then an x or X.
2. The digits of the number (but not the exponent part!) also include the hexadecimal digits a through f and
their uppercase equivalents.
3. The exponent is mandatory, and is introduced by the letter p (or P) instead of an e or E. The exponent
represents a scaling factor that is a power of 2 instead of a power of 10.
Advice: since hexadecimal floating-point forms are unfamiliar to most Java programmers, it is advisable to use them
sparingly.
Underscores
Starting with Java 7, underscores are permitted within the digit strings in all three forms of floating point literal. This
applies to the "exponent" parts as well. See Using underscores to improve readability.
Special cases
It is a compilation error if a floating point literal denotes a number that is too large or too small to represent in the
selected representation; i.e. if the number would overflow to +INF or -INF, or underflow to 0.0. However, it is legal
for a literal to represent a non-zero denormalized number.
The floating point literal syntax does not provide literal representations for IEEE 754 special values such as the INF
and NaN values. If you need to express them in source code, the recommended way is to use the constants defined
by the java.lang.Float and java.lang.Double; e.g. Float.NaN, Float.NEGATIVE_INFINITY and
Float.POSITIVE_INFINITY.
--
operators, respectively.
--
operators follow variables, they are called post-increment and post-decrement respectively.
int a = 10;
a++; // a now equals 11
a--; // a now equals 10 again
--
operators precede the variables the operations are called pre-increment and pre-decrement respectively.
int x = 10;
--x; // x now equals 9
++x; // x now equals 10
If the operator precedes the variable, the value of the expression is the value of the variable after being
incremented or decremented. If the operator follows the variable, the value of the expression is the value of the
variable prior to being incremented or decremented.
int x=10;
System.out.println("x=" + x + " x=" + x++ + " x=" + x); // outputs x=10 x=10 x=11
System.out.println("x=" + x + " x=" + ++x + " x=" + x); // outputs x=11 x=12 x=12
System.out.println("x=" + x + " x=" + x-- + " x=" + x); // outputs x=12 x=12 x=11
System.out.println("x=" + x + " x=" + --x + " x=" + x); // outputs x=11 x=10 x=10
Be careful not to overwrite post-increments or decrements. This happens if you use a post-in/decrement operator
at the end of an expression which is reassigned to the in/decremented variable itself. The in/decrement will not
have an effect. Even though the variable on the left hand side is incremented correctly, its value will be immediately
overwritten with the previously evaluated result from the right hand side of the expression:
int x = 0;
x = x++ + 1 + x++; // x = 0 + 1 + 1
// do not do this - the last increment has no effect (bug!)
System.out.println(x); // prints 2 (not 3!)
Correct:
int x = 0;
x = x++ + 1 + x; // evaluates to x = 0 + 1 + 1
As shown in the syntax, the Conditional Operator (also known as the Ternary Operator1) uses the ? (question mark)
and : (colon) characters to enable a conditional expression of two possible outcomes. It can be used to replace
longer if-else blocks to return one of two values based on condition.
Is equivalent to
if (testCondition) {
result = value1;
} else {
result = value2;
}
It can be read as “If testCondition is true, set result to value1; otherwise, set result to value2”.
For example:
Is equivalent to
Common Usage
You can use the conditional operator for conditional assignments (like null checking).
String x = "";
if (y != null) {
x = y.toString();
}
// parenthesis required
7 * (a > 0 ? 2 : 5)
Conditional operators nesting can also be done in the third part, where it works more like chaining or like a switch
statement.
a ? "a is true" :
b ? "a is false, b is true" :
c ? "a and b are false, c is true" :
"a, b, and c are false"
a ? x : (b ? y : (c ? z : w))
Footnote:
1 - Both the Java Language Specification and the Java Tutorial call the (? :) operator the Conditional Operator. The
Tutorial says that it is "also known as the Ternary Operator" as it is (currently) the only ternary operator defined by
Java. The "Conditional Operator" terminology is consistent with C and C++ and other languages with an equivalent
operator.
The complement (~) operator is a unary operator that performs a bitwise or logical inversion of the bits of
one operand; see JLS 15.15.5..
The AND (&) operator is a binary operator that performs a bitwise or logical "and" of two operands; see JLS
15.22.2..
The OR (|) operator is a binary operator that performs a bitwise or logical "inclusive or" of two operands; see
JLS 15.22.2..
The XOR (^) operator is a binary operator that performs a bitwise or logical "exclusive or" of two operands;
see JLS 15.22.2..
The logical operations performed by these operators when the operands are booleans can be summarized as
follows:
A B ~A A & B A | B A ^ B
001 0 0 0
011 0 1 1
100 0 1 1
110 1 1 0
Note that for integer operands, the above table describes what happens for individual bits. The operators actually
operate on all 32 or 64 bits of the operand or operands in parallel.
The ~ operator is used to reverse a boolean value, or change all the bits in an integer operand.
The & operator is used for "masking out" some of the bits in an integer operand. For example:
The | operator is used to combine the truth values of two operands. For example:
For more examples of the use of the bitwise operators, see Bit Manipulation
In the simple case, the Concatenation operator joins two strings to give a third string. For example:
When one of the two operands is not a string, it is converted to a String as follows:
An operand whose type is a primitive type is converted as if by calling toString() on the boxed value.
An operand whose type is a reference type is converted by calling the operand's toString() method. If the
operand is null, or if the toString() method returns null, then the string literal "null" is used instead.
For example:
int one = 1;
String s3 = "One is " + one; // s3 contains "One is 1"
String s4 = null + " is null"; // s4 contains "null is null"
String s5 = "{1} is " + new int[]{1}; // s5 contains something like
// "{} is [I@xxxxxxxx"
The explanation for the s5 example is that the toString() method on array types is inherited from
java.lang.Object, and the behavior is to produce a string that consists of the type name, and the object's identity
The Concatenation operator is specified to create a new String object, except in the case where the expression is a
Constant Expression. In the latter case, the expression is evaluated at compile type, and its runtime value is
equivalent to a string literal. This means that there is no runtime overhead in splitting a long string literal like this:
As noted above, with the exception of constant expressions, each string concatenation expression creates a new
String object. Consider this code:
In the method above, each iteration of the loop will create a new String that is one character longer than the
previous iteration. Each concatenation copies all of the characters in the operand strings to form the new String.
Thus, stars(N) will:
create N new String objects, and throw away all but the last one,
copy N * (N + 1) / 2 characters, and
generate O(N^2) bytes of garbage.
This is very expensive for large N. Indeed, any code that concatenates strings in a loop is liable to have this problem.
A better way to write this would be as follows:
Ideally, you should set the capacity of the StringBuilder, but if this is not practical, the class will automatically grow
the backing array that the builder uses to hold characters. (Note: the implementation expands the backing array
exponentially. This strategy keeps that amount of character copying to a O(N) rather than O(N^2).)
Some people apply this pattern to all string concatenations. However, this is unnecessary because the JLS allows a
Java compiler to optimize string concatenations within a single expression. For example:
String s1 = ...;
String s2 = ...;
String test = "Hello " + s1 + ". Welcome to " + s2 + "\n";
(The JIT compiler may optimize that further if it can deduce that s1 or s2 cannot be null.) But note that this
optimization is only permitted within a single expression.
operators:
The binary subtraction operator subtracts one number from another one.
The unary minus operator is equivalent to subtracting its operand from zero.
The binary multiply operator (*) multiplies one number by another.
The binary divide operator (/) divides one number by another.
The binary remainder1 operator (%) calculates the remainder when one number is divided by another.
1. This is often incorrectly referred to as the "modulus" operator. "Remainder" is the term that is used by the JLS.
"Modulus" and "remainder" are not the same thing.
The operators require numeric operands and produce numeric results. The operand types can be any primitive
numeric type (i.e. byte, short, char, int, long, float or double) or any numeric wrapper type define in java.lang;
i.e. (Byte, Character, Short, Integer, Long, Float or Double.
The result type is determined base on the types of the operand or operands, as follows:
If either of the operands is a double or Double, then the result type is double.
Otherwise, if either of the operands is a float or Float, then the result type is float.
Otherwise, if either of the operands is a long or Long, then the result type is long.
Otherwise, the result type is int. This covers byte, short and char operands as well as `int.
The result type of the operation determines how the arithmetic operation is performed, and how the operands are
handled
If the result type is double, the operands are promoted to double, and the operation is performed using 64-
bit (double precision binary) IEE 754 floating point arithmetic.
If the result type is float, the operands are promoted to float, and the operation is performed using 32-bit
If the operand type is a wrapper type, the operand value is unboxed to a value of the corresponding primitive
type.
If necessary, the primitive type is promoted to the required type:
Promotion of integers to int or long is loss-less.
Promotion of float to double is loss-less.
Promotion of an integer to a floating point value can lead to loss of precision. The conversion is
performed using IEE 768 "round-to-nearest" semantics.
The / operator divides the left-hand operand n (the dividend) and the right-hand operand d (the divisor) and
produces the result q (the quotient).
Java integer division rounds towards zero. The JLS Section 15.17.2 specifies the behavior of Java integer division as
follows:
The quotient produced for operands n and d is an integer value q whose magnitude is as large as possible
while satisfying |d ? q| ? |n|. Moreover, q is positive when |n| ? |d| and n and d have the same sign,
but q is negative when |n| ? |d| and n and d have opposite signs.
If the n is MIN_VALUE, and the divisor is -1, then integer overflow occurs and the result is MIN_VALUE. No
exception is thrown in this case.
If d is 0, then `ArithmeticException is thrown.
Java floating point division has more edge cases to consider. However the basic idea is that the result q is the value
that is closest to satisfying d . q = n.
Floating point division will never result in an exception. Instead, operations that divide by zero result in an INF and
NaN values; see below.
Unlike C and C++, the remainder operator in Java works with both integer and floating point operations.
For integer cases, the result of a % b is defined to be the number r such that (a / b) * b + r is equal to a, where
/, * and + are the appropriate Java integer operators. This applies in all cases except when b is zero. That case,
remainder results in an ArithmeticException.
It follows from the above definition that a % b can be negative only if a is negative, and it be positive only if a is
positive. Moreover, the magnitude of a % b is always less than the magnitude of b.
Floating point remainder operation is a generalization of the integer case. The result of a % b is the remainder r is
defined by the mathematical relation r = a - (b ? q) where:
Floating point remainder can produce INF and NaN values in edge-cases such as when b is zero; see below. It will not
throw an exception.
Important note:
The result of a floating-point remainder operation as computed by % is not the same as that produced by
the remainder operation defined by IEEE 754. The IEEE 754 remainder may be computed using the
Math.IEEEremainder library method.
Integer Overflow
Java 32 and 64 bit integer values are signed and use twos-complement binary representation. For example, the
range of numbers representable as (32 bit) int -231 through +231 - 1.
When you add, subtract or multiple two N bit integers (N == 32 or 64), the result of the operation may be too large
to represent as an N bit integer. In this case, the operation leads to integer overflow, and the result can be computed
as follows:
It should be noted that integer overflow does not result in exceptions under any circumstances.
Java uses IEE 754 floating point representations for float and double. These representations have some special
values for representing values that fall outside of the domain of Real numbers:
The "infinite" or INF values denote numbers that are too large. The +INF value denote numbers that are too
large and positive. The -INF value denote numbers that are too large and negative.
The "indefinite" / "not a number" or NaN denote values resulting from meaningless operations.
The INF values are produced by floating operations that cause overflow, or by division by zero.
The NaN values are produced by dividing zero by zero, or computing zero remainder zero.
Surprisingly, it is possible perform arithmetic using INF and NaN operands without triggering exceptions. For
example:
For full details, please refer to the relevant subsections of JLS 15. Note that this is largely "academic". For typical
calculations, an INF or NaN means that something has gone wrong; e.g. you have incomplete or incorrect input data,
The << or left shift operator shifts the value given by the first operand leftwards by the number of bit positions
given by the second operand. The empty positions at the right end are filled with zeros.
The '>>' or arithmetic shift operator shifts the value given by the first operand rightwards by the number of bit
positions given by the second operand. The empty positions at the left end are filled by copying the left-most
bit. This process is known as sign extension.
The '>>>' or logical right shift operator shifts the value given by the first operand rightwards by the number of
bit positions given by the second operand. The empty positions at the left end are filled with zeros.
Notes:
1. These operators require an int or long value as the first operand, and produce a value with the same type as
the first operand. (You will need to use an explicit type cast when assigning the result of a shift to a byte,
short or char variable.)
2. If you use a shift operator with a first operand that is a byte, char or short, it is promoted to an int and the
operation produces an int.)
3. The second operand is reduced modulo the number of bits of the operation to give the amount of the shift. For
more about the mod mathematical concept, see Modulus examples.
4. The bits that are shifted off the left or right end by the operation are discarded. (Java does not provide a
primitive "rotate" operator.)
5. The arithmetic shift operator is equivalent dividing a (two's complement) number by a power of 2.
6. The left shift operator is equivalent multiplying a (two's complement) number by a power of 2.
The following table will help you see the effects of the three shift operators. (The numbers have been expressed in
binary notation to aid vizualization.)
Example:
true
This operator will still return true if the object being compared is the assignment compatible with the type on the
right.
Example:
class Vehicle {}
true
Section 13.8: The Assignment Operators (=, +=, -=, *=, /=, %=,
<<=, >>= , >>>=, &=, |= and ^=)
The left hand operand for these operators must be a either a non-final variable or an element of an array. The right
hand operand must be assignment compatible with the left hand operand. This means that either the types must be
the same, or the right operand type must be convertible to the left operands type by a combination of boxing,
unboxing or widening. (For complete details refer to JLS 5.2.)
The precise meaning of the "operation and assign" operators is specified by JLS 15.26.2 as:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)),
where T is the type of E1, except that E1 is evaluated only once.
1.
The simple assignment operator: assigns the value of the right hand operand to the left hand operand.
2. +=
The "add and assign" operator: adds the value of right hand operand to the value of the left hand operand and
assigns the result to left hand operand. If the left hand operand has type String, then this a "concatenate and
assign" operator.
3. -=
The "subtract and assign" operator: subtracts the value of the right operand from the value of the left hand
operand and assign the result to left hand operand.
4. *=
The "multiply and assign" operator: multiplies the value of the right hand operand by the value of the left hand
operand and assign the result to left hand operand. .
5. /=
The "divide and assign" operator: divides the value of the right hand operand by the value of the left hand operand
and assign the result to left hand operand.
6. %=
The "modulus and assign" operator: calculates the modulus of the value of the right hand operand by the value of
the left hand operand and assign the result to left hand operand.
8. >>=
9. >>>=
10. &=
11. |=
12. ^=
|| - the conditional-OR operators. The evaluation of <left-expr> && <right-expr> is equivalent to the
following pseudo-code:
{
boolean L = evaluate(<left-expr>);
if (!L) {
return evaluate(<right-expr>);
} else {
// short-circuit the evaluation of the 2nd operand expression
return true;
}
}
As the pseudo-code above illustrates, the behavior of the short-circuit operators are equivalent to using if / else
statements.
The following example shows the most common usage pattern for the && operator. Compare these two versions of
a method to test if a supplied Integer is zero.
The first version works in most cases, but if the value argument is null, then a NullPointerException will be
thrown.
In the second version we have added a "guard" test. The value != null && value == 0 expression is evaluated by
first performing the value != null test. If the null test succeeds (i.e. it evaluates to true) then the value == 0
expression is evaluated. If the null test fails, then the evaluation of value == 0 is skipped (short-circuited), and we
don't get a NullPointerException.
The following example shows how && can be used to avoid a relatively costly calculation:
- `a < b` tests if the value of `a` is less than the value of `b`.
- `a <= b` tests if the value of `a` is less than or equal to the value of `b`.
- `a > b` tests if the value of `a` is greater than the value of `b`.
- `a >= b` tests if the value of `a` is greater than or equal to the value of `b`.
Relational operators can be used to compare numbers with different types. For example:
int i = 1;
long l = 2;
if (i < l) {
System.out.println("i is smaller");
}
Relational operators can be used when either or both numbers are instances of boxed numeric types. For example:
You need to be careful with relational comparisons that involve floating point numbers:
Expressions that compute floating point numbers often incur rounding errors due to the fact that the
computer floating-point representations have limited precision.
When comparing an integer type and a floating point type, the conversion of the integer to floating point can
also lead to rounding errors.
Finally, Java does bit support the use of relational operators with any types other than the ones listed above. For
example, you cannot use these operators to compare strings, arrays of numbers, and so on.
==
==
operator gives true if the operands are equal and false otherwise. The != operator gives false if the operands are
equal and true otherwise.
These operators can be used operands with primitive and reference types, but the behavior is significantly
different. According to the JLS, there are actually three distinct sets of these operators:
The Boolean
==
and != operators.
The Numeric
==
and != operators.
The Reference
==
and != operators.
==
==
and != operators
==
or != operator is a primitive numeric type (byte, short, char, int, long, float or double), the operator is a numeric
comparison. The second operand must be either a primitive numeric type, or a boxed numeric type.
==
and != operators
If both operands are boolean, or one is boolean and the other is Boolean, these operators the Boolean
==
A B A == B A != B
false false true false
false true false true
true false false true
true true true false
==
If you use
==
or != to compare two Boolean objects, then the Reference operators are used. This may give an unexpected
result; see Pitfall: using == to compare primitive wrappers objects such as Integer
The
==
. For most operand types, this mistake leads to a compilation error. However, for boolean and Boolean
operands the mistake leads to incorrect runtime behavior; see Pitfall - Using '==' to test a boolean
The Reference
==
and != operators
==
and != operators test if the two operands refer to the same object. This often not what you want. To test if two
objects are equal by value, the .equals() method should be used instead.
String s1 = "We are equal";
String s2 = new String("We are equal");
Warning: using
==
==
is false but the result of != is true. Indeed, the test x != x is true if and only if the value of x is NaN.
This behavior is (to most programmers) unexpected. If you test if a NaN value is equal to itself, the answer is "No it
isn't!". In other words,
==
However, this is not a Java "oddity", this behavior is specified in the IEEE 754 floating-point standards, and you will
find that it is implemented by most modern programming languages. (For more information, see
http://stackoverflow.com/a/1573715/139985 ... noting that this is written by someone who was "in the room when
the decisions were made"!)
Version ≥ Java SE 8
a -> a + 1 // a lambda that adds one to its argument
a -> { return a + 1; } // an equivalent lambda using a block.
A lambda expression defines an anonymous function, or more correctly an instance of an anonymous class that
implements a functional interface.
(This example is included here for completeness. Refer to the Lambda Expressions topic for the full treatment.)
It has a minimum value of \u0000 (0 in the decimal representation, also called the null character) and a maximum
value of \uffff (65,535).
In order to define a char of ' value an escape sequence (character preceded by a backslash) has to be used:
It is also possible to add to a char. e.g. to iterate through every lower-case letter, you could do to the following:
default
data type numeric representation range of values
value
Notes:
1. The Java Language Specification mandates that signed integral types (byte through long) use binary twos-
complement representation, and the floating point types use standard IEE 754 binary floating point
representations.
2. Java 8 and later provide methods to perform unsigned arithmetic operations on int and long. While these
methods allow a program to treat values of the respective types as unsigned, the types remain signed types.
3. The smallest floating point shown above are subnormal; i.e. they have less precision than a normal value. The
smallest normal numbers are 1.175494351e?38 and 2.2250738585072014e?308
4. A char conventionally represents a Unicode / UTF-16 code unit.
5. Although a boolean contains just one bit of information, its size in memory varies depending on the Java
Virtual Machine implementation (see boolean type).
Floats handle the five common arithmetical operations: addition, subtraction, multiplication, division, and modulus.
Note: The following may vary slightly as a result of floating point errors. Some results have been rounded for clarity and
readability purposes (i.e. the printed result of the addition example was actually 34.600002).
// addition
float result = 37.2f + -2.6f; // result: 34.6
// subtraction
float result = 45.1f - 10.3f; // result: 34.8
// multiplication
float result = 26.3f * 1.7f; // result: 44.71
// modulus
float result = 37.1f % 4.8f; // result: 3.4999971
Because of the way floating point numbers are stored (i.e. in binary form), many numbers don't have an exact
representation.
While using float is fine for most applications, neither float nor double should be used to store exact
representations of decimal numbers (like monetary amounts), or numbers where higher precision is required.
Instead, the BigDecimal class should be used.
Note: Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NaN are float values. NaN stands for results of
operations that cannot be determined, such as dividing 2 infinite values. Furthermore 0f and -0f are different, but
==
yields true:
float f1 = 0f;
float f2 = -0f;
System.out.println(f1 == f2); // true
System.out.println(1f / f1); // Infinity
System.out.println(1f / f2); // -Infinity
System.out.println(Float.POSITIVE_INFINITY / Float.POSITIVE_INFINITY); // NaN
According to java API: "The Integer class wraps a value of the primitive type int in an object. An object of type
Integer contains a single field whose type is int."
By default, int is a 32-bit signed integer. It can store a minimum value of -231, and a maximum value of 231 - 1.
If you need to store a number outside of this range, long should be used instead. Exceeding the value range of int
leads to an integer overflow, causing the value exceeding the range to be added to the opposite site of the range
(positive becomes negative and vise versa). The value is ((value - MIN_VALUE) % RANGE) + MIN_VALUE, or ((value
+ 2147483648) % 4294967296) - 2147483648
There are two types of conversions: widening conversion and narrowing conversion.
A widening conversion is when a value of one datatype is converted to a value of another datatype that occupies
more bits than the former. There is no issue of data loss in this case.
Correspondingly, A narrowing conversion is when a value of one datatype is converted to a value of another
datatype that occupies fewer bits than the former. Data loss can occur in this case.
Java performs widening conversions automatically. But if you want to perform a narrowing conversion (if you are sure
that no data loss will occur), then you can force Java to perform the conversion using a language construct known
as a cast.
Widening Conversion:
int a = 1;
double d = a; // valid conversion to double, no cast needed (widening)
Narrowing Conversion:
double d = 18.96
int b = d; // invalid conversion to int, will throw a compile-time error
int b = (int) d; // valid conversion to int, but result is truncated (gets rounded down)
// This is type-casting
// Now, b = 18
Boxed objects always require 8 bytes for type and memory management, and because the size of objects is always
a multiple of 8, boxed types all require 16 bytes total. In addition, each usage of a boxed object entails storing a
reference which accounts for another 4 or 8 bytes, depending on the JVM and JVM options.
In data-intensive operations, memory consumption can have a major impact on performance. Memory
consumption grows even more when using arrays: a float[5] array will require only 32 bytes; whereas a Float[5]
storing 5 distinct non-null values will require 112 bytes total (on 64 bit without compressed pointers, this increases
to 152 bytes).
The space overheads of the boxed types can be mitigated to a degree by the boxed value caches. Some of the
boxed types implement a cache of instances. For example, by default, the Integer class will cache instances to
represent numbers in the range -128 to +127. This does not, however, reduce the additional cost arising from the
additional memory indirection.
If you create an instance of a boxed type either by autoboxing or by calling the static valueOf(primitive) method,
the runtime system will attempt to use a cached value. If your application uses a lot of values in the range that is
cached, then this can substantially reduce the memory penalty of using boxed types. Certainly, if you are creating
boxed value instances "by hand", it is better to use valueOf rather than new. (The new operation always creates a
new instance.) If, however, the majority of your values are not in the cached range, it can be faster to call new and
save the cache lookup.
Because of the way floating point numbers are stored, many numbers don't have an exact representation.
While using double is fine for most applications, neither float nor double should be used to store precise numbers
such as currency. Instead, the BigDecimal class should be used
Note: Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN are double values. NaN stands for
results of operations that cannot be determined, such as dividing 2 infinite values. Furthermore 0d and -0d are
different, but
yields true:
double d1 = 0d;
double d2 = -0d;
System.out.println(d1 == d2); // true
System.out.println(1d / d1); // Infinity
System.out.println(1d / d2); // -Infinity
System.out.println(Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY); // NaN
//an "L" must be appended to the end of the number, because by default,
//numbers are assumed to be the int type. Appending an "L" makes it a long
//as 549755813888 (2 ^ 39) is larger than the maximum value of an int (2^31 - 1),
//"L" must be appended
long bigNumber = 549755813888L;
Note: letter "L" appended at the end of long literal is case insensitive, however it is good practice to use capital as it
is easier to distinct from digit one:
2L == 2l; // true
Warning: Java caches Integer objects instances from the range -128 to 127. The reasoning is explained here:
https://blogs.oracle.com/darcy/entry/boxing_and_caches_integer_valueof
To properly compare 2 Object Long values, use the following code(From Java 1.7 onward):
Comparing a primitive long to an Object long will not result in a false negative like comparing 2 objects with ==
does.
For a unique binary representation of a data type using n bits, values are encoded like this:
The least significant n-1 bits store a positive integral number x in integral representation. Most significant value
stores a bit vith value s. The value repesented by those bits is
x - s * 2n-1
i.e. if the most significant bit is 1, then a value that is just by 1 larger than the number you could represent with the
other bits (2n-2 + 2n-3 + ... + 21 + 20 = 2n-1 - 1) is subtracted allowing a unique binary representation for
each value from - 2n-1 (s = 1; x = 0) to 2n-1 - 1 (s = 0; x = 2n-1 - 1).
This also has the nice side effect, that you can add the binary representations as if they were positive binary
numbers:
v1 = x1 - s1 * 2n-1 v2 = x2 - s2 * 2n-1
s1 s2 x1 + x2 overflow addition result
0 0 No x1 + x2 = v1 + v2
0 0 Yes too large to be represented with data type (overflow)
x1 + x2 - 2n-1 = x1 + x2 - s2 * 2n-1
0 1 No
= v1 + v2
(x1 + x2) mod 2n-1 = x1 + x2 - 2n-1
0 1 Yes
= v1 + v2
1 0 * see above (swap summands)
1 1 No too small to be represented with data type (x1 + x2 - 2n < -2n-1 ; underflow)
(x1 + x2) mod 2n-1 - 2n-1 = (x1 + x2 - 2n-1) - 2n-1
1 1 Yes = (x1 - s1 * 2n-1) + (x2 - s2 * 2n-1)
= v1 + v2
Note that this fact makes finding binary representation of the additive inverse (i.e. the negative value) easy:
Observe that adding the bitwise complement to the number results in all bits being 1. Now add 1 to make value
overflow and you get the neutral element 0 (all bits 0).
So the negative value of a number i can be calculated using (ignoring possible promotion to int here)
(~i) + 1
The result of negating 0, is 11111111. Adding 1 gives a value of 100000000 (9 bits). Because a byte can only store 8
bits, the leftmost value is truncated, and the result is 00000000
}
}
The visibility of the default constructor is the same as the visibility of the class. Thus a class defined package-
privately has a package-private default constructor
However, if you have non-default constructor, the compiler will not generate a default constructor for you. So these
are not equivalent:
Beware that the generated constructor performs no non-standard initialization. This means all fields of your class
will have their default value, unless they have an initializer.
public TestClass() {
testData = "Test"
}
}
class Parent {
private String name;
private int age;
// This does not even compile, because name and age are private,
// making them invisible even to the child class.
class Child extends Parent {
public Child() {
// compiler implicitly calls super() here
name = "John";
age = 42;
}
}
class Parent {
private String name;
private int age;
public Parent(String tName, int tAge) {
name = tName;
age = tAge;
}
}
Note: Calls to another constructor (chaining) or the super constructor MUST be the first statement inside the
constructor.
If you call the super(...) constructor explicitly, a matching parent constructor must exist (that's straightforward,
isn't it?).
class Parent{
public Parent(String tName, int tAge) {}
}
The class Parent has no default constructor, so, the compiler can't add super in the Child constructor. This code will
not compile. You must change the constructors to fit both sides, or write your own super call, like that:
A class can have multiple constructors with different signatures. To chain constructor calls (call a different
constructor of the same class when instantiating) use this().
public TestClass() {
this("Test"); // testData defaults to "Test"
}
}
Whenever it is invoked on the same object more than once during an execution of a Java
application, the hashCode method must consistently return the same integer, provided no
information used in equals comparisons on the object is modified. This integer need not remain
consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode
method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct integer results for unequal
objects may improve the performance of hash tables.
Hash codes are used in hash implementations such as HashMap, HashTable, and HashSet. The result of the hashCode
function determines the bucket in which an object will be put. These hash implementations are more efficient if the
provided hashCode implementation is good. An important property of good hashCode implementation is that the
distribution of the hashCode values is uniform. In other words, there is a small probability that numerous instances
will be stored in the same bucket.
An algorithm for computing a hash code value may be similar to the following:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
In Java 1.2 and above, instead of developing an algorithm to compute a hash code, one can be generated using
java.util.Arrays#hashCode by supplying an Object or primitives array containing the field values:
@Override
public int hashCode() {
return Arrays.hashCode(new Object[] {field1, field2, field3});
}
Version ≥ Java SE 7
Java 1.7 introduced the java.util.Objects class which provides a convenience method, hash(Object...
objects), that computes a hash code based on the values of the objects supplied to it. This method works just like
java.util.Arrays#hashCode.
@Override
public int hashCode() {
return Objects.hash(field1, field2, field3);
}
Note: this approach is inefficient, and produces garbage objects each time your custom hashCode() method is
called:
A temporary Object[] is created. (In the Objects.hash() version, the array is created by the "varargs"
mechanism.)
If any of the fields are primitive types, they must be boxed and that may create more temporary objects.
The array must be populated.
The array must iterated by the Arrays.hashCode or Objects.hash method.
The calls to Object.hashCode() that Arrays.hashCode or Objects.hash has to make (probably) cannot be
inlined.
Since the calculation of an object's hash code can be expensive, it can be attractive to cache the hash code value
within the object the first time that it is calculated. For example
// Other methods
@Override
public boolean equals(Object obj) {
@Override
public int hashCode() {
int h = hash;
if (h == 0) {
h = Arrays.hashCode(array);
hash = h;
}
return h;
}
}
This approach trades off the cost of (repeatedly) calculating the hash code against the overhead of an extra field to
cache the hash code. Whether this pays off as a performance optimization will depend on how often a given object
is hashed (looked up) and other factors.
You will also notice that if the true hashcode of an ImmutableArray happens to be zero (one chance in 232), the
cache is ineffective.
Finally, this approach is much harder to implement correctly if the object we are hashing is mutable. However,
there are bigger concerns if hash codes change; see the contract above.
@Override
public String toString() {
return firstName + " " + lastName;
}
Here toString() from Object class is overridden in the User class to provide meaningful data regarding the object
when printing it.
When using println(), the object's toString() method is implicitly called. Therefore, these statements do the
same thing:
If the toString() is not overridden in the above mentioned User class, System.out.println(user) may return
User@659e0bfd or a similar String with almost no useful information except the class name. This will be because the
call will use the toString() implementation of the base Java Object class which does not know anything about the
User class's structure or business rules. If you want to change this functionality in your class, simply override the
method.
==
tests for reference equality (whether they are the same object)
.equals() tests for value equality (whether they are logically "equal")
equals() is a method used to compare two objects for equality. The default implementation of the equals()
method in the Object class returns true if and only if both references are pointing to the same instance. It
therefore behaves the same as comparison by
==
.
public class Foo {
int field1, field2;
String field3;
Even though foo1 and foo2 are created with the same fields, they are pointing to two different objects in memory.
The default equals() implementation therefore evaluates to false.
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
@Override
public int hashCode() {
int hash = 1;
hash = 31 * hash + this.field1;
hash = 31 * hash + this.field2;
hash = 31 * hash + (field3 == null ? 0 : field3.hashCode());
return hash;
}
Here the overridden equals() method decides that the objects are equal if their fields are the same.
Notice that the hashCode() method was also overwritten. The contract for that method states that when two
objects are equal, their hash values must also be the same. That's why one must almost always override
hashCode() and equals() together.
Pay special attention to the argument type of the equals method. It is Object obj, not Foo obj. If you put the latter
in your method, that is not an override of the equals method.
When writing your own class, you will have to write similar logic when overriding equals() and hashCode(). Most
IDEs can automatically generate this for you.
An example of an equals() implementation can be found in the String class, which is part of the core Java API.
Rather than comparing pointers, the String class compares the content of the String.
Version ≥ Java SE 7
Java 1.7 introduced the java.util.Objects class which provides a convenience method, equals, that compares two
potentially null references, so it can be used to simplify implementations of the equals method.
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
Class Comparison
Since the equals method can run against any object, one of the first things the method often does (after checking
for null) is to check if the class of the object being compared matches the current class.
@Override
public boolean equals(Object obj) {
//...check for null
if (getClass() != obj.getClass()) {
return false;
}
//...compare fields
}
This is typically done as above by comparing the class objects. However, that can fail in a few special cases which
may not be obvious. For example, some frameworks generate dynamic proxies of classes and these dynamic
proxies are actually a different class. Here is an example using JPA.
One mechanism to work around that limitation is to compare classes using instanceof
@Override
public final boolean equals(Object obj) {
if (!(obj instanceof Foo)) {
return false;
}
//...compare fields
}
However, there are a few pitfalls that must be avoided when using instanceof. Since Foo could potentially have
other subclasses and those subclasses might override equals() you could get into a case where a Foo is equal to a
FooSubclass but the FooSubclass is not equal to Foo.
This violates the properties of symmetry and transitivity and thus is an invalid implementation of the equals()
method. As a result, when using instanceof, a good practice is to make the equals() method final (as in the
above example). This will ensure that no subclass overrides equals() and violates key assumptions.
package com.example.examples.object;
import java.util.concurrent.atomic.AtomicBoolean;
while (!aHasFinishedWaiting.get()) {
synchronized (obj) {
// notify ONE thread which has called obj.wait()
obj.notify();
}
}
}
};
threadA.join();
threadB.join();
System.out.println("Finished!");
}
}
The getClass() method will return the most specific class type, which is why when getClass() is called on
anotherSpecificUser, the return value is class SpecificUser because that is lower down the inheritance tree
than User.
The actual static type returned by a call to getClass is Class<? extends T> where T is the static type of the object
on which getClass is called.
For the method to be used all classes calling the method must implement the Cloneable interface.
The Cloneable interface itself is just a tag interface used to change the behaviour of the native clone() method
which checks if the calling objects class implements Cloneable. If the caller does not implement this interface a
CloneNotSupportedException will be thrown.
The Object class itself does not implement this interface so a CloneNotSupportedException will be thrown if the
calling object is of class Object.
For a clone to be correct it should be independent of the object it is being cloned from, therefore it may be
necessary to modify the object before it gets returned. This means to essentially create a "deep copy" by also
copying any of the mutable objects that make up the internal structure of the object being cloned. If this is not
implemented correctly the cloned object will not be independent and have the same references to the mutable
objects as the object that it was cloned from. This would result in inconsistent behaviour as any changes to those in
one would affect the other.
} catch (CloneNotSupportedException e) {
// in case any of the cloned mutable fields do not implement Cloneable
throw new AssertionError(e);
}
}
}
If you do not specify the call to super() in a constructor the compiler will put it in for you.
public MyClass() {
super();
}
}
public MyClass() {
// empty
}
}
doSomethingWith(size);
this(initialValues.size());
addInitialValues(initialValues);
}
}
Calling new MyClass(Arrays.asList("a", "b", "c")) will call the second constructor with the List-argument,
which will in turn delegate to the first constructor (which will delegate implicitly to super()) and then call
addInitialValues(int size) with the second size of the list. This is used to reduce code duplication where
multiple constructors need to do the same work.
Given the example above, one can either call new MyClass("argument") or new MyClass("argument", 0). In other
words, much like method overloading, you just call the constructor with the parameters that are necessary for your
chosen constructor.
Nothing more than would happen in a sub-class that has a default empty constructor (minus the call to super()).
The default empty constructor can be explicitly defined but if not the compiler will put it in for you as long as no
other constructors are already defined.
The actual creation of objects is down to the JVM. Every constructor in Java appears as a special method named
<init> which is responsible for instance initializing. This <init> method is supplied by the compiler and because
<init> is not a valid identifier in Java, it cannot be used directly in the language.
The JVM will invoke the <init> method using the invokespecial instruction and can only be invoked on
uninitialized class instances.
For more information take a look at the JVM specification and the Java Language Specification:
According to the doc, this method gets called by the garbage collector on an object when garbage
collection determines that there are no more references to the object.
But there are no guarantees that finalize() method would gets called if the object is still reachable or no Garbage
Collectors run when the object become eligible. That's why it's better not rely on this method.
In Java core libraries some usage examples could be found, for instance in FileInputStream.java:
In this case it's the last chance to close the resource if that resource has not been closed before.
Generally it's considered bad practice to use finalize() method in applications of any kind and should be avoided.
Finalizers are not meant for freeing resources (e.g., closing files). The garbage collector gets called when (if!) the
system runs low on heap space. You can't rely on it to be called when the system is running low on file handles or,
for any other reason.
The intended use-case for finalizers is for an object that is about to be reclaimed to notify some other object about
its impending doom. A better mechanism now exists for that purpose---the java.lang.ref.WeakReference<T>
class. If you think you need write a finalize() method, then you should look into whether you can solve the same
problem using WeakReference instead. If that won't solve your problem, then you may need to re-think your design
on a deeper level.
For further reading here is an Item about finalize() method from "Effective Java" book by Joshua Bloch.
An annotation is a marker which associates information with a program construct, but has no effect at
run time.
Annotations may appear before types or declarations. It is possible for them to appear in a place where they could
apply to both a type or a declaration.
What exactly an annotation applies to is governed by the "meta-annotation" @Target. See "Defining annotation
types" for more information.
Annotations are used for a multitude of purposes. Frameworks like Spring and Spring-MVC make use of
annotations to define where Dependencies should be injected or where requests should be routed.
Other frameworks use annotations for code-generation. Lombok and JPA are prime examples, that use annotations
to generate Java (and SQL) code.
@interface MyAnnotation {
String param1();
boolean param2();
int[] param3(); // array parameter
}
Default values
@interface MyAnnotation {
String param1() default "someValue";
boolean param2() default true;
int[] param3() default {};
}
Meta-Annotations
Meta-annotations are annotations that can be applied to annotation types. Special predefined meta-annotation
define how annotation types can be used.
The @Target meta-annotation restricts the types the annotation can be applied to.
@Target(ElementType.METHOD)
@interface MyAnnotation {
// this annotation can only be applied to methods
}
Multiple values can be added using array notation, e.g. @Target({ElementType.FIELD, ElementType.TYPE})
Available Values
ElementType target example usage on target element
@Retention(RetentionPolicy.RUNTIME) terface
ANNOTATION_TYPE annotation types
MyAnnotation
CONSTRUCTOR constructors @MyAnnotationlic MyClass() {}
FIELD fields, enum constants @XmlAttributevate int count;
for (@LoopVariable int i = 0; i < 100; i++) { @Unused
variable declarations inside
LOCAL_VARIABLE String resultVariable;
methods
}
package (in package-
PACKAGE @Deprecatedkage very.old;
info.java)
METHOD methods @XmlElementlic int getCount() {...}
public Rectangle( @NamedArg("width") double width,
method/constructor @NamedArg("height") double height) {
PARAMETER
parameters ...
}
TYPE classes, interfaces, enums @XmlRootElementlic class Report {}
Version ≥ Java SE 8
ElementType target example usage on target element
TYPE_PARAMETER Type parameter declarations public <@MyAnnotation T> void f(T t) {}
TYPE_USE Use of a type Object o = "42";ing s = (@MyAnnotation String) o;
@Retention
The @Retention meta-annotation defines the annotation visibility during the applications compilation process or
execution. By default, annotations are included in .class files, but are not visible at runtime. To make an
annotation accessible at runtime, RetentionPolicy.RUNTIME has to be set on that annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
// this annotation can be accessed with reflections at runtime
}
Available values
RetentionPolicy Effect
CLASS The annotation is available in the .class file, but not at runtime
RUNTIME The annotation is available at runtime and can be accessed via reflection
The annotation is available at compile time, but not added to the .class files. The annotation can
SOURCE
be used e.g. by an annotation processor.
@Documented
The @Documented meta-annotation is used to mark annotations whose usage should be documented by API
documentation generators like javadoc. It has no values. With @Documented, all classes that use the annotation will
list it on their generated documentation page. Without @Documented, it's not possible to see which classes use the
annotation in the documentation.
@Inherited
For a non-inherited annotation, the query only examines the class being examined.
For an inherited annotation, the query will also check the super-class chain (recursively) until an instance of
the annotation is found.
Note that only the super-classes are queried: any annotations attached to interfaces in the classes hierarchy will be
ignored.
@Repeatable
The @Repeatable meta-annotation was added in Java 8. It indicates that multiple instances of the annotation can be
attached to the annotation's target. This meta-annotation has no values.
@interface MyDefaultAnnotation {
@Retention(RetentionPolicy.RUNTIME)
@interface MyRuntimeVisibleAnnotation {
@MyDefaultAnnotation
static class RuntimeCheck1 {
}
@MyRuntimeVisibleAnnotation
static class RuntimeCheck2 {
}
@Override
Concrete superclass
Abstract class
class Logger1 {
public void log(String logString) {
System.out.prinln(logString);
}
}
class Logger2 {
// This will throw compile-time error. Logger2 is not a subclass of Logger1.
// log method is not overriding anything
@Override
public void log(String logString) {
System.out.println("Log 2" + logString);
}
}
The main purpose is to catch mistyping, where you think you are overriding a method, but are actually defining a
new one.
class Vehicle {
public void drive() {
System.out.println("I am driving");
}
}
In Java 5, it meant that the annotated method had to override a non-abstract method declared in the
superclass chain.
From Java 6 onward, it is also satisfied if the annotated method implements an abstract method declared in
the classes superclass / interface hierarchy.
(This can occasionally cause problems when back-porting code to Java 5.)
@Deprecated
This marks the method as deprecated. There can be several reasons for this:
The specific reason for deprecation can usually be found in the documentation of the API.
The annotation will cause the compiler to emit an error if you use it. IDEs may also highlight this method somehow
as deprecated
class ComplexAlgorithm {
@Deprecated
public void oldSlowUnthreadSafeMethod() {
// stuff here
}
@SuppressWarnings
In almost all cases, when the compiler emits a warning, the most appropriate action is to fix the cause. In some
instances (Generics code using untype-safe pre-generics code, for example) this may not be possible and it's better
to suppress those warnings that you expect and cannot fix, so you can more clearly see unexpected warnings.
This annotation can be applied to a whole class, method or line. It takes the category of warning as a parameter.
@SuppressWarnings("deprecation")
@SuppressWarning("finally")
public boolean checkData() {
// method calling return from within finally block
}
It is better to limit the scope of the annotation as much as possible, to prevent unexpected warnings also being
suppressed. For example, confining the scope of the annotation to a single-line:
The warnings supported by this annotation may vary from compiler to compiler. Only the unchecked and
deprecation warnings are specifically mentioned in the JLS. Unrecognized warning types will be ignored.
@SafeVarargs
Because of type erasure, void method(T... t) will be converted to void method(Object[] t) meaning that the
compiler is not always able to verify that the use of varargs is type-safe. For instance:
There are instances where the use is safe, in which case you can annotate the method with the SafeVarargs
annotation to suppress the warning. This obviously hides the warning if your use is unsafe too.
@FunctionalInterface
This is an optional annotation used to mark a FunctionalInterface. It will cause the compiler to complain if it does
not conform to the FunctionalInterface spec (has a single abstract method)
@FunctionalInterface
public interface ITrade {
public boolean check(Trade t);
}
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
The annotation
The @Setter annotation is a marker can be applied to methods. The annotation will be discarded during
compilation not be available afterwards.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Setter {
}
The SetterProcessor class is used by the compiler to process the annotations. It checks, if the methods annotated
with the @Setter annotation are public, non-static methods with a name starting with set and having a
uppercase letter as 4th letter. If one of these conditions isn't met, a error is written to the Messager. The compiler
writes this to stderr, but other tools could use this information differently. E.g. the NetBeans IDE allows the user
specify annotation processors that are used to display error messages in the editor.
package annotation.processor;
import annotation.Setter;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
@SupportedAnnotationTypes({"annotation.Setter"})
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SetterProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// get elements annotated with the @Setter annotation
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(Setter.class);
@Override
public void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
Packaging
To be applied by the compiler, the annotation processor needs to be made available to the SPI (see ServiceLoader).
annotation.processor.SetterProcessor
The following class is example class in the default package with the annotations being applied to the correct
elements according to the retention policy. However only the annotation processor only considers the second
method a valid annotation target.
import annotation.Setter;
@Setter
@Setter
public void setString(String value) {}
@Setter
public static void main(String[] args) {}
If the annotation processor is discovered using the SPI, it is automatically used to process annotated elements. E.g.
compiling the AnnotationProcessorTest class using
This could be prevented by specifying the -proc:none option for javac. You could also forgo the usual compilation
by specifying -proc:only instead.
IDE integration
Netbeans
Annotation processors can be used in the NetBeans editor. To do this the annotation processor needs to be
specified in the project settings:
2. add check marks for Enable Annotation Processing and Enable Annotation Processing in Editor
4. in the popup that appears enter the fully qualified class name of the annotation processor and click Ok.
Result
// Author.java
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
String value();
}
// Authors.java
@Retention(RetentionPolicy.RUNTIME)
public @interface Authors {
Author[] value();
}
// Test.java
@Authors({
@Author("Mary"),
@Author("Sam")
})
public class Test {
public static void main(String[] args) {
Author[] authors = Test.class.getAnnotation(Authors.class).value();
for (Author author : authors) {
System.out.println(author.value());
// Output:
// Mary
// Sam
}
}
}
Version ≥ Java SE 8
Java 8 provides a cleaner, more transparent way of using container annotations, using the @Repeatable annotation.
First we add this to the Author class:
@Repeatable(Authors.class)
This tells Java to treat multiple @Author annotations as though they were surrounded by the @Authors container.
We can also use Class.getAnnotationsByType() to access the @Author array by its own class, instead of through its
@Author("Mary")
@Author("Sam")
public class Test {
public static void main(String[] args) {
Author[] authors = Test.class.getAnnotationsByType(Author.class);
for (Author author : authors) {
System.out.println(author.value());
// Output:
// Mary
// Sam
}
}
}
Example
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotationType {
}
and
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface UninheritedAnnotationType {
}
@UninheritedAnnotationType
class A {
}
@InheritedAnnotationType
class B extends A {
}
class C extends B {
}
System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class));
System.out.println("_________________________________");
System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class));
will print a result similar to this (depending on the packages of the annotation):
null
@InheritedAnnotationType()
@InheritedAnnotationType()
_________________________________
@UninheritedAnnotationType()
null
null
Note that annotations can only be inherited from classes, not interfaces.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String key() default "foo";
String value() default "bar";
}
class AnnotationExample {
// Put the Annotation on the method, but leave the defaults
@MyAnnotation
public void testDefaults() throws Exception {
// Using reflection, get the public method "testDefaults", which is this method with no args
Method method = AnnotationExample.class.getMethod("testDefaults", null);
foo = bar
baz = buzz
The receiver parameter is an optional syntactic device for an instance method or an inner class's
constructor. For an instance method, the receiver parameter represents the object for which the method
is invoked. For an inner class's constructor, the receiver parameter represents the immediately enclosing
instance of the newly constructed object. Either way, the receiver parameter exists solely to allow the type
of the represented object to be denoted in source code, so that the type may be annotated. The receiver
parameter is not a formal parameter; more precisely, it is not a declaration of any kind of variable
(§4.12.3), it is never bound to any value passed as an argument in a method invocation expression or
qualified class instance creation expression, and it has no effect whatsoever at run time.
The following example illustrates the syntax for both kinds of receiver parameter:
The sole purpose of receiver parameters is to allow you to add annotations. For example, you might have a custom
annotation @IsOpen whose purpose is to assert that a Closeable object has not been closed when a method is
called. For example:
At one level, the @IsOpen annotation on this could simply serve as documentation. However, we could potentially
do more. For example:
An annotation processor could insert a runtime check that this is not in closed state when update is called.
A code checker could perform a static code analysis to find cases where this could be closed when update is
called.
The value parameter is an array of Strings. You can set multiple values by using a notation similar to Array
initializers:
@SuppressWarnings({"unused"})
@SuppressWarnings({"unused", "javadoc"})
If you only need to set a single value, the brackets can be omitted:
@SuppressWarnings("unused")
By having an immutable object, one can ensure that all threads that are looking at the object will be seeing the
same state, as the state of an immutable object will not change.
1. Don't provide "setter" methods - methods that modify fields or objects referred to by fields.
2. Make all fields final and private.
3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A
more sophisticated approach is to make the constructor private and construct instances in factory methods.
4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
5. Don't provide methods that modify the mutable objects.
6. Don't share references to the mutable objects. Never store references to external, mutable objects passed to
the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of
your internal mutable objects when necessary to avoid returning the originals in your methods.
class Point {
private int x, y;
//...
One way to deal with this is to create an immutable wrapper for the mutable type. Here is a simple wrapper for an
array of integers
This class works by using defensive copying to isolate the mutable state (the int[]) from any code that might mutate
it:
The constructor uses clone() to create a distinct copy of the parameter array. If the caller of the constructor
subsequent changed the parameter array, it would not affect the state of the ImmutableIntArray.
The getValue() method also uses clone() to create the array that is returned. If the caller were to change
the result array, it would not affect the state of the ImmutableIntArray.
We could also add methods to ImmutableIntArray to perform read-only operations on the wrapped array; e.g. get
its length, get the value at a particular index, and so on.
Note that an immutable wrapper type implemented this way is not type compatible with the original type. You
cannot simply substitute the former for the latter.
A variation on this is to declare the constructor as private and provide a public static factory method instead.
Immutability does not prevent object from being nullable; e.g. null can be assigned to a String variable.
If an immutable classes properties are declared as final, instances are inherently thread-safe. This makes
immutable classes a good building block for implementing multi-threaded applications.
The following snippet shows that the above class is not immutable:
import java.util.List;
import java.util.ArrayList;
public final class Names {
private final List<String> names;
public Names(List<String> names) {
this.names = new ArrayList<String>(names);
}
public List<String> getNames() {
return names;
}
public int size() {
return names.size();
}
}
Names class seems immutable at the first sight, but it is not as the following code shows:
This happened because a change to the reference List returned by getNames() can modify the actual list of Names.
To fix this, simply avoid returning references that reference class's mutable objects either by making defensive
copies, as follows:
or by designing getters in way that only other immutable objects and primitives are returned, as follows:
Injecting constructor with object(s) that can be modified outside the immutable class
This is a variation of the previous flaw. Take a look at the following class:
import java.util.List;
public final class NewNames {
private final List<String> names;
public Names(List<String> names) {
this.names = names;
}
public String getName(int index) {
return names.get(index);
}
public int size() {
return names.size();
}
}
As Names class before, also NewNames class seems immutable at the first sight, but it is not, in fact the following
snippet proves the contrary:
To fix this, as in the previous flaw, simply make defensive copies of the object without assigning it directly to the
immutable class, i.e. constructor can be changed as follows:
Person class seems immutable at the first sight, but suppose a new subclass of Person is defined:
now Person (im)mutability can be exploited through polymorphism by using the new subclass:
To fix this, either mark the class as final so it cannot be extended or declare all of its constructor(s) as private.
class SomeClass {
private int variable;
public Test(){
}
}
Now let's try to create an instance of the class. In this example, we can access number because it is public.
package javax.swing;
public abstract class JComponent extends Container … {
…
static boolean DEBUG_GRAPHICS_LOADED;
…
}
package javax.swing;
public class DebugGraphics extends Graphics {
…
static {
JComponent.DEBUG_GRAPHICS_LOADED = true;
}
…
}
As an example:
package com.stackexchange.docs;
public class MyClass{
protected int variable; //This is the variable that we are trying to access
public MyClass(){
variable = 2;
};
}
Now we'll extend this class and try to access one of its protected members.
package some.other.pack;
import com.stackexchange.docs.MyClass;
public class SubClass extends MyClass{
public SubClass(){
super();
System.out.println(super.variable);
}
}
You would be also able to access a protected member without extending it if you are accessing it from the same
package.
Note that this modifier only works on members of a class, not on the class itself.
There was once a private protected (both keywords at once) modifier that could be applied to methods or
variables to make them accessible from a subclass outside the package, but make them private to the classes in
that package. However, this was removed in Java 1.0's release.
public class X {
}
class Y {
}
}
Interface members always have public visibility, even if the public keyword is omitted. So both foo(), bar(), TEXT,
ANSWER, X, and Y have public visibility. However, access may still be limited by the containing interface - since
MyInterface has public visibility, its members may be accessed from anywhere, but if MyInterface had had
package visibility, its members would only have been accessible from within the same package.
This example uses generic class Param to take a single type parameter T, delimited by angle brackets (<>):
public T getValue() {
return value;
}
To instantiate this class, provide a type argument in place of T. For example, Integer:
The type argument can be any reference type, including arrays and other generic types:
Param<String[]> stringArrayParam;
Param<int[][]> int2dArrayParam;
Param<Param<Object>> objectNestedParam;
In Java SE 7 and later, the type argument can be replaced with an empty set of type arguments (<>) called the
diamond:
Version ≥ Java SE 7
Param<Integer> integerParam = new Param<>();
Unlike other identifiers, type parameters have no naming constraints. However their names are commonly the first
letter of their purpose in upper case. (This is true even throughout the official JavaDocs.)
Examples include T for "type", E for "element" and K/V for "key"/"value".
public T getValue() {
return value;
}
AbstractParam is an abstract class declared with a type parameter of T. When extending this class, that type
parameter can be replaced by a type argument written inside <>, or the type parameter can remain unchanged. In
the first and second examples below, String and Integer replace the type parameter. In the third example, the
type parameter remains unchanged. The fourth example doesn't use generics at all, so it's similar to if the class had
an Object parameter. The compiler will warn about AbstractParam being a raw type, but it will compile the
ObjectParam class. The fifth example has 2 type parameters (see "multiple type parameters" below), choosing the
second parameter as the type parameter passed to the superclass.
Notice that in the Email class, the T getValue() method acts as if it had a signature of String getValue(), and the
void setValue(T) method acts as if it was declared void setValue(String).
It is also possible to instantiate with anonymous inner class with an empty curly braces ({}):
Java provides the ability to use more than one type parameter in a generic class or interface. Multiple type
parameters can be used in a class or interface by placing a comma-separated list of types between the angle
brackets. Example:
public T getFirstParam() {
return firstParam;
}
public S getSecondParam() {
return secondParam;
}
? extends T represents an upper bounded wildcard. The unknown type represents a type that must be a
subtype of T, or type T itself.
? super T represents a lower bounded wildcard. The unknown type represents a type that must be a
supertype of T, or type T itself.
class Shoe {}
class IPhone {}
interface Fruit {}
class Apple implements Fruit {}
class Banana implements Fruit {}
class GrannySmith extends Apple {}
Choosing the right T, ? super T or ? extends T is necessary to allow the use with subtypes. The compiler can then
ensure type safety; you should not need to cast (which is not type safe, and may cause programming errors) if you
use them properly.
Java 7 introduced the Diamond1 to remove some boiler-plate around generic class instantiation. With Java 7+ you
can write:
One limitation is for Anonymous Classes, where you still must provide the type parameter in the instantiation:
Although using the diamond with Anonymous Inner Classes is not supported in Java 7 and 8, it will be included as
a new feature in Java 9.
Footnote:
1 - Some people call the <> usage the "diamond operator". This is incorrect. The diamond does not behave as an
operator, and is not described or listed anywhere in the JLS or the (official) Java Tutorials as an operator. Indeed, <>
is not even a distinct Java token. Rather it is a < token followed by a > token, and it is legal (though bad style) to have
whitespace or comments between the two. The JLS and the Tutorials consistently refer to <> as "the diamond", and
that is therefore the correct term for it.
Notice that we don't have to pass an actual type argument to a generic method. The compiler infers the type
argument for us, based on the target type (e.g. the variable we assign the result to), or on the types of the actual
arguments. It will generally infer the most specific type argument that will make the call type-correct.
Sometimes, albeit rarely, it can be necessary to override this type inference with explicit type arguments:
void usage() {
consumeObjects(this.<Object>makeList("Jeff", "Atwood").stream());
}
It's necessary in this example because the compiler can't "look ahead" to see that Object is desired for T after
calling stream() and it would otherwise infer String based on the makeList arguments. Note that the Java
language doesn't support omitting the class or object on which the method is called (this in the above example)
when type arguments are explicitly provided.
Example: we want to sort a list of numbers but Number doesn't implement Comparable.
In this example T must extend Number and implement Comparable<T> which should fit all "normal" built-in number
implementations like Integer or BigDecimal but doesn't fit the more exotic ones like Striped64.
Since multiple inheritance is not allowed, you can use at most one class as a bound and it must be the first listed.
For example, <T extends Comparable<T> & Number> is not allowed because Comparable is an interface, and not a
class.
Generic parameterization on a class can be inspected by creating an anonymous inner class. This class will capture
the type information. In general this mechanism is referred to as super type tokens, which are detailed in Neal
Gafter's blog post.
Implementations
Guava's TypeToken
Spring's ParameterizedTypeReference
Jackson's TypeReference
Example usage
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing
compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Elimination of casts
When re-written to use generics, the code does not require casting:
By using generics, programmers can implement generic algorithms that work on collections of different types, can
be customized, and are type safe and easier to read.
The type T is erased. Since, at runtime, the JVM does not know what T originally was, it does not know which
constructor to call.
Workarounds
genericMethod(String.class);
Which throws exceptions, since there is no way to know if the passed class has an accessible default
constructor.
Version ≥ Java SE 8
genericMethod(String::new);
Without bounded generics, we cannot make a container class that is both generic and knows that each element is
an animal:
public AnimalContainer() {
col = new ArrayList<T>();
}
public BoundedAnimalContainer() {
col = new ArrayList<T>();
}
// Legal
AnimalContainer<Cat> a = new AnimalContainer<Cat>();
// Legal
AnimalContainer<String> a = new AnimalContainer<String>();
Assume we have a DataSeries<T> type (interface here), which defines a generic data series containing values of
type T. It is cumbersome to work with this type directly when we want to perform a lot of operations with e.g.
double values, so we define DoubleSeries extends DataSeries<Double>. Now assume, the original DataSeries<T>
type has a method add(values) which adds another series of the same length and returns a new one. How do we
enforce the type of values and the type of the return to be DoubleSeries rather than DataSeries<Double> in our
derived class?
The problem can be solved by adding a generic type parameter referring back to and extending the type being
declared (applied to an interface here, but the same stands for classes):
Here T represents the data type the series holds, e.g. Double and DS the series itself. An inherited type (or types) can
now be easily implemented by substituting the above mentioned parameter by a corresponding derived type, thus,
yielding a concrete Double-based definition of the form:
At this moment even an IDE will implement the above interface with correct types in place, which, after a bit of
content filling may look like this:
DoubleSeriesImpl(Collection<Double> data) {
this.data = new ArrayList<>(data);
}
@Override
@Override
public List<Double> data() {
return Collections.unmodifiableList(data);
}
}
As you can see the add method is declared as DoubleSeries add(DoubleSeries values) and the compiler is
happy.
Let's say you want to create a class whose Generic type should implement both Flushable and Closeable, you can
write
Now, the ExampleClass only accepts as generic parameters, types which implement both Flushable and
Closeable.
ExampleClass<Console> arg4; // Does NOT work because Console only implements Flushable
ExampleClass<ZipFile> arg5; // Does NOT work because ZipFile only implements Closeable
ExampleClass<Flushable> arg2; // Does NOT work because Closeable bound is not satisfied.
ExampleClass<Closeable> arg3; // Does NOT work because Flushable bound is not satisfied.
The class methods can choose to infer generic type arguments as either Closeable or Flushable.
/* You can even invoke the methods of any valid type directly. */
public void test2 (T param) {
param.flush(); // Method of Flushable called on T and works fine.
param.close(); // Method of Closeable called on T and works fine too.
Note:
You cannot bind the generic parameter to either of the type using OR (|) clause. Only the AND (&) clause is
supported. Generic type can extends only one class and many interfaces. Class must be placed at the beginning of
the list.
The method will compile with a warning. The code is actually more safe than it looks because the Java runtime will
do a cast when you use it:
Here, the cast will work when the returned type is any kind of List (i.e. returning List<String> would not trigger a
ClassCastException; you'd eventually get it when taking elements out of the list).
To work around this problem, you can create an API which uses typed keys:
With this approach, you can't put the wrong type into the map, so the result will always be correct (unless you
accidentally create two keys with the same name but different types).
Related:
Type-safe Map
Consider the following generic class Example declared with the formal parameter <T>:
class Example<T> {
public boolean isTypeAString(String s) {
return s instanceof T; // Compilation error, cannot use T as class type here
}
This will always give a Compilation error because as soon as the compiler compiles the Java source into Java
bytecode it applies a process known as type erasure, which converts all generic code into non-generic code, making
impossible to distinguish among T types at runtime. The type used with instanceof has to be reifiable, which
means that all information about the type has to be available at runtime, and this is usually not the case for generic
types.
The following class represents what two different classes of Example, Example<String> and Example<Number>, look
like after generics has stripped off by type erasure:
Since types are gone, it's not possible for the JVM to know which type is T.
You can always use unbounded wildcard (?) for specifying a type in the instanceof as follows:
The other side of the coin is that using an instance t of T with instanceof is legal, as shown in the following
example:
class Example<T> {
public boolean isTypeAString(T t) {
return t instanceof String; // No compilation error this time
}
}
because after the type erasure the class will look like the following:
Since, even if the type erasure happen anyway, now the JVM can distinguish among different types in memory, even
if they use the same reference type (Object), as the following snippet shows:
Choose a specific type to replace the formal type parameter <T> of MyGenericClass and implement it, as the
following example does:
This class only deals with String, and this means that using MyGenericInterface with different parameters (e.g.
Integer, Object etc.) won't compile, as the following snippet shows:
Declare another generic interface with the formal type parameter <T> which implements MyGenericInterface, as
follows:
Note that a different formal type parameter may have been used, as follows:
Declare a non-generic class which implements MyGenericInteface as a raw type (not using generic at all), as follows:
This way is not recommended, since it is not 100% safe at runtime because it mixes up raw type (of the subclass)
with generics (of the interface) and it is also confusing. Modern Java compilers will raise a warning with this kind of
implementation, nevertheless the code - for compatibility reasons with older JVM (1.4 or earlier) - will compile.
All the ways listed above are also allowed when using a generic class as a supertype instead of a generic interface.
Class ? A class can be defined as a template/blueprint that describes the behavior/state that the object of its type
support.
The advantage is that the same functionality is called with two different numbers of inputs. While invoking the
method according to the input we are passing, (In this case either one string value or two string values) the
corresponding method is executed.
Note: Methods cannot be overloaded by changing just the return type (int method() is considered the same as String
method() and will throw a RuntimeException if attempted). If you change the return type you must also change the
parameters in order to overload.
Method Overloading
Method overloading (also known as static Polymorphism) is a way you can have two (or more) methods (functions)
with same name in a single class. Yes its as simple as that.
This way user can call the same method for area depending on the type of shape it has.
But the real question now is, how will java compiler will distinguish which method body is to be executed?
Well Java have made it clear that even though the method names (area() in our case) can be same but the
arguments method is taking should be different.
Overloaded methods must have different arguments list (quantity and types).
That being said we cannot add another method to calculate area of a square like this : public Double area(Long
side) because in this case, it will conflict with area method of circle and will cause ambiguity for java compiler.
Thank god, there are some relaxations while writing overloaded methods like
Well that's because which overloaded methods is to be invoked is decided at compile time, based on the actual
number of arguments and the compile-time types of the arguments.
Method Overriding
Well, method overriding (yes you guess it right, it is also known as dynamic polymorphism) is somewhat more
interesting and complex topic.
In method overriding we overwrite the method body provided by the parent class. Got it? No? Let's go through an
example.
So we have a class called Shape and it has method called area which will probably return the area of the shape.
Let's say now we have two classes called Circle and Rectangle.
// See this annotation @Override, it is telling that this method is from parent
// class Shape and is overridden here
@Override
public Double area(){
return 3.14 * radius * radius;
}
}
// See this annotation @Override, it is telling that this method is from parent
// class Shape and is overridden here
@Override
public Double area(){
return length * breadth;
}
So, now both of your children classes have updated method body provided by the parent (Shape) class. Now
question is how to see the result? Well lets do it the old psvm way.
// Drumbeats ......
//This should print 78.5
System.out.println("Shape of circle : "+circle.area());
}
}
Wow! isn't it great? Two objects of same type calling same methods and returning different values. My friend, that's
the power of dynamic polymorphism.
It is important to understand that constructors are different from methods in several ways:
1. Constructors can only take the modifiers public, private, and protected, and cannot be declared abstract,
final, static, or synchronized.
3. Constructors MUST be named the same as the class name. In the Hello example, the Hello object's
constructor name is the same as the class name.
4. The this keyword has an additional usage inside constructors. this.method(...) calls a method on the
current instance, while this(...) refers to another constructor in the current class with different signatures.
Constructors also can be called through inheritance using the keyword super.
public SuperManClass(){
// some implementation
}
// ... methods
}
static {
Set<String> set = new HashSet<>();
set.add("Hello");
set.add("World");
set.add("foo");
set.add("bar");
set.add("42");
WORDS = Collections.unmodifiableSet(set);
}
}
public Car(){
milesPerGallon = 0;
name = "";
color = "";
numGallonsInTank = 0;
}
Objects are instances of their class. So, the way you would create an object would be by calling the Car class in
one of two ways in your main class (main method in Java or onCreate in Android).
Option 1
Option 1 is where you essentially tell the program everything about the Car upon creation of the object. Changing
any property of the car would require calling one of the methods such as the repaintCar method. Example:
newCar.repaintCar("Blue");
Note: Make sure you pass the correct data type to the method. In the example above, you may also pass a variable
to the repaintCar method as long as the data type is correct`.
That was an example of changing properties of an object, receiving properties of an object would require using a
method from the Car class that has a return value (meaning a method that is not void). Example:
Option 1 is the best option when you have all the object's data at the time of creation.
Option 2
Option 2 gets the same effect but required more work to create an object correctly. I want to recall this Constructor
in the Car class:
Notice that you do not have to actually pass any parameters into the object to create it. This is very useful for when
you do not have all the aspects of the object but you need to use the parts that you do have. This sets generic data
into each of the instance variables of the object so that, if you call for a piece of data that does not exist, no errors
are thrown.
This is a common mistake amongst objects that are not initialized with all their data. Errors were avoided because
there is a Constructor that allows an empty Car object to be created with stand-in variables (public Car(){}), but
no part of the myCar was actually customized. Correct example of creating Car Object:
And, as a reminder, get an object's properties by calling a method in your main class. Example:
A class consists at a minimum of the class keyword, a name, and a body, which might be empty.
class ObjectMemberVsStaticMember {
void increment() {
staticCounter ++;
memberCounter++;
}
}
o1.increment();
o2.increment();
o2.increment();
System.out.println("ObjectMemberVsStaticMember.staticCounter = " +
ObjectMemberVsStaticMember.staticCounter);
o1 static counter 3
o1 member counter 1
o2 static counter 3
o2 member counter 2
ObjectMemberVsStaticMember.staticCounter = 3
Note: You should not call static members on objects, but on classes. While it does not make a difference for the
JVM, human readers will appreciate it.
static members are part of the class and exists only once per class. Non-static members exist on instances, there
is an independent copy for each instance. This also means that you need access to an object of that class to access
its members.
And the use thereof, which (notably) does not at all acknowledge the existence of the nested class.
//prints: 0, 1, 2, 3, 4,
for(int i = 0; i < 5; i++) {
System.out.print(s.pop() + ", ");
}
}
}
Or non-static:
At its core, static nested classes do not have a surrounding instance of the outer class, whereas non-static nested
classes do. This affects both where/when one is allowed to instantiate a nested class, and what instances of those
nested classes are allowed to access. Adding to the above example:
private StaticNestedClass() {
innerField = aField; //Illegal, can't access aField from static context
aMethod(); //Illegal, can't call aMethod from static context
}
private NestedClass() {
innerField = aField; //Legal
aMethod(); //Legal
Thus, your decision of static vs non-static mainly depends on whether or not you need to be able to directly access
fields and methods of the outer class, though it also has consequences for when and where you can construct the
nested class.
As a rule of thumb, make your nested classes static unless you need to access fields and methods of the outer
class. Similar to making your fields private unless you need them public, this decreases the visibility available to the
nested class (by not allowing access to an outer instance), reducing the likelihood of error.
public, as usual, gives unrestricted access to any scope able to access the type.
public int x = 5;
both protected and the default modifier (of nothing) behave as expected as well, the same as they do for non-
nested classes.
private, interestingly enough, does not restrict to the class it belongs to. Rather, it restricts to the compilation unit -
the .java file. This means that Outer classes have full access to Inner class fields and methods, even if they are
marked private.
private int x;
private void anInnerMethod() {}
}
The Inner Class itself can have a visibility other than public. By marking it private or another restricted access
modifier, other (external) classes will not be allowed to import and assign the type. They can still get references to
objects of that type, however.
Anonymous classes are typically used in situations where you need to be able to create a light-weight class to be
passed as a parameter. This is typically done with an interface. For example:
This anonymous class defines a Comparator<String> object (CASE_INSENSITIVE) that compares two strings ignoring
differences in case.
Other interfaces that are frequently implemented and instantiated using anonymous classes are Runnable and
Anonymous inner classes can also be based on classes. In this case, the anonymous class implicitly extends the
existing class. If the class being extended is abstract, then the anonymous class must implement all abstract
methods. It may also override non-abstract methods.
Constructors
An anonymous class cannot have an explicit constructor. Instead, an implicit constructor is defined that uses
super(...) to pass any parameters to a constructor in the class that is being extended. For example:
The implicit constructor for our anonymous subclass of SomeClass will call a constructor of SomeClass that matches
the call signature SomeClass(int, String). If no constructor is available, you will get a compilation error. Any
exceptions that are thrown by the matched constructor are also thrown by the implicit constructor.
Naturally, this does not work when extending an interface. When you create an anonymous class from an interface,
the classes superclass is java.lang.Object which only has a no-args constructor.
The inner class depends on the outside class and requires a reference to an instance of it. To create an instance of
the inner class, the new operator only needs to be called on an instance of the outer class.
class OuterClass {
class InnerClass {
}
}
class OutsideClass {
OuterClass.InnerClass createInner() {
return outer.new InnerClass();
}
}
A method-local inner class can be instantiated only within the method where the inner class is defined.
You can access fields and methods of the outer class directly.
But in case of name collision you can use the outer class reference.
// updating my counter
counter = OuterClass.this.counter;
}
}
}
With the Objects.nonNull method and Java8 Stream API, we can do the above in this way:
/**
* Class which falls back to default implementation of {@link #printString()}
*/
public class WithDefault
implements Printable
{
}
/**
* Custom implementation of {@link #printString()}
*/
public class OverrideDefault
implements Printable {
@Override
public void printString() {
System.out.println( "overridden implementation" );
}
}
new WithDefault().printString();
new OverrideDefault().printString();
default implementation
overridden implementation
For example, you have Swim interface that you published 20 years ago.
We did a great job, our interface is very popular, there are many implementation on that around the world and you
don't have control over their source code.
After 20 years, you've decided to add new functionality to the interface, but it looks like our interface is frozen
because it will break existing implementations.
Now all existing implementations of our interface can still work. But most importantly they can implement the
newly added method in their own time.
One of the biggest reasons for this change, and one of its biggest uses, is in the Java Collections framework. Oracle
could not add a foreach method to the existing Iterable interface without breaking all existing code which
implemented Iterable. By adding default methods, existing Iterable implementation will inherit the default
implementation.
int getB();
@Override
public int getB() {
return 2;
}
}
System.out.println(new Sum().calculateSum());
Default methods could be used along with interface static methods as well:
System.out.println(new Sum().calculateSum());
public interface A {
default void foo() { System.out.println("A.foo"); }
}
public interface B {
default void foo() { System.out.println("B.foo"); }
Here are two interfaces declaring default method foo with the same signature.
If you will try to extend these both interfaces in the new interface you have to make choice of two, because Java
forces you to resolve this collision explicitly.
First, you can declare method foo with the same signature as abstract, which will override A and B behaviour.
And when you will implement ABExtendsAbstract in the class you will have to provide foo implementation:
Or second, you can provide a completely new default implementation. You also may reuse code of A and B foo
methods by Accessing overridden default methods from implementing class.
And when you will implement ABExtends in the class you will not have to provide foo implementation:
Will produce
AbstractSwimmer.backStroke
new FooSwimmer().backStroke();
Will produce
FooSwimmer.backStroke
package foo.bar
package foo.bar.baz
The above is fine because the two classes exist in different packages.
package foo.bar
public ExampleClass() {
exampleNumber = 3;
exampleString = "Test String";
}
//No getters or setters
}
package foo.bar
package baz.foo
Additional content can be added to a subclass. Doing so allows for additional functionality in the subclass without
any change to the base class or any other subclasses from that same base class:
public int x;
public SubClassWithField(int x) {
this.x = x; //Can access fields
}
}
private fields and methods still exist within the subclass, but are not accessible:
private int x = 5;
This is known as multiple inheritance, and while it is legal in some languages, Java does not permit it with classes.
As a result of this, every class has an unbranching ancestral chain of classes leading to Object, from which all
classes descend.
An abstract class cannot be instantiated. It can be sub-classed (extended) as long as the sub-class is either also
abstract, or implements all methods marked as abstract by super classes.
The class must be marked abstract, when it has at least one abstract method. An abstract method is a method that
has no implementation. Other methods can be declared within an abstract class that have implementation in order
to provide common code for any sub-classes.
However a class that extends Component, and provides an implementation for all of its abstract methods and can be
instantiated.
@Override
public void render() {
//render a button
}
}
@Override
public void render() {
//render a textbox
}
}
Instances of inheriting classes also can be cast as the parent class (normal inheritance) and they provide a
polymorphic effect when the abstract method is called.
Abstract classes and interfaces both provide a way to define method signatures while requiring the
extending/implementing class to provide the implementation.
There are two key differences between abstract classes and interfaces:
A class may only extend a single class, but may implement many interfaces.
An abstract class can contain instance (non-static) fields, but interfaces may only contain static fields.
Methods declared in interfaces could not contain implementations, so abstract classes were used when it was
useful to provide additional methods which implementations called the abstract methods.
Version ≥ Java SE 8
Java 8 allows interfaces to contain default methods, usually implemented using the other methods of the interface,
making interfaces and abstract classes equally powerful in this regard.
As a convenience java allows for instantiation of anonymous instances of subclasses of abstract classes, which
provide implementations for the abstract methods upon creating the new object. Using the above example this
could look like this:
When used in a class declaration, the final modifier prevents other classes from being declared that extend the
class. A final class is a "leaf" class in the inheritance class hierarchy.
Final classes can be combined with a private constructor to control or prevent the instantiation of a class. This can
be used to create a so-called "utility class" that only defines static members; i.e. constants and static methods.
Immutable classes should also be declared as final. (An immutable class is one whose instances cannot be
changed after they have been created; see the Immutable Objects topic. ) By doing this, you make it impossible to
create a mutable subclass of an immutable class. That would violate the Liskov Substitution Principle which
requires that a subtype should obey the "behavioral contract" of its supertypes.
From a practical perspective, declaring an immutable class to be final makes it easier to reason about program
behavior. It also addresses security concerns in the scenario where untrusted code is executed in a security
sandbox. (For instance, since String is declared as final, a trusted class does not need to worry that it might be
tricked into accepting mutable subclass, which the untrusted caller could then surreptitiously change.)
One disadvantage of final classes is that they do not work with some mocking frameworks such as Mockito.
Update: Mockito version 2 now support mocking of final classes.
Final methods
The final modifier can also be applied to methods to prevent them being overridden in sub-classes:
@Override
public void someMethod() { // Compiler error (overridden method is final)
}
}
Final methods are typically used when you want to restrict what a subclass can change in a class without forbidding
subclasses entirely.
The final modifier can also be applied to variables, but the meaning of final for variables is unrelated to
inheritance.
class A {...}
class B extends A {...}
This also applies when the type is an interface, where there doesn't need to any hierarchical relationship between
the objects:
interface Foo {
void bar();
}
Now the list contains objects that are not from the same class hierarchy.
Abstract classes create "is a" relations while interfaces provide "has a" capability.
System.out.println("Dog:"+dog);
System.out.println("Cat:"+cat);
dog.remember();
dog.protectOwner();
Learn dl = dog;
dl.learn();
cat.remember();
cat.protectOwner();
Climb c = cat;
c.climb();
Climb cm = man;
cm.climb();
Think t = man;
t.think();
Learn l = man;
l.learn();
Apply a = man;
a.apply();
}
}
interface Learn {
void learn();
}
interface Apply{
void apply();
}
output:
Key notes:
1. Animal is an abstract class with shared attributes: name and lifeExpectancy and abstract methods:
remember() and protectOwner(). Dog and Cat are Animals that have implemented the remember() and
protectOwner() methods.
2. Cat can climb() but Dog cannot. Dog can think() but Cat cannot. These specific capabilities are added to Cat
and Dog by implementation.
3. Man is not an Animal but he can Think , Learn, Apply, and Climb.
6. Man is neither a Cat nor a Dog but can have some of the capabilities of the latter two without extending
Animal, Cat, or Dog. This is done with Interfaces.
TL;DR:
Unrelated classes can have capabilities through interfaces, but related classes change the behaviour through extension of
base classes.
Refer to the Java documentation page to understand which one to use in a specific use case.
1. You expect that unrelated classes would implement your interface. For example, many unrelated objects can
implement the Serializable interface.
2. You want to specify the behaviour of a particular data type but are not concerned about who implements its
behaviour.
3. You want to take advantage of multiple inheritance of type.
SubClass.sayHello();
//This will be different than the above statement's output, since it runs
//A different method
SubClass.sayHello(true);
StaticOverride.sayHello();
System.out.println("StaticOverride's num: " + StaticOverride.num);
}
}
Hello
BaseClass's num: 5
Hello
Hey
Static says Hi
StaticOverride's num: test
Not only the former can be applied to a wider choice of arguments, its results will be more compatible with code
provided by other developers that generally adhere to the concept of programming to an interface. However, the
most important reasons to use the former are:
most of the time the context, in which the result is used, does not and should not need that many details as
the concrete implementation provides;
adhering to an interface forces cleaner code and less hacks such as yet another public method gets added to
a class serving some specific scenario;
the code is more testable as interfaces are easily mockable;
finally, the concept helps even if only one implementation is expected (at least for testability).
So how can one easily apply the concept of programming to an interface when writing new code having in mind
one particular implementation? One option that we commonly use is a combination of the following patterns:
programming to an interface
factory
builder
The following example based on these principles is a simplified and truncated version of an RPC implementation
written for a number of different protocols:
The above interface is not supposed to be instantiated directly via a factory, instead we derive further more
concrete interfaces, one for HTTP invocation and one for AMQP, each then having a factory and a builder to
construct instances, which in turn are also instances of the above interface:
Instances of RemoteInvoker for the use with AMQP can now be constructed as easy as (or more involved depending
on the builder):
Due to Java 8 permitting placing of static methods directly into interfaces, the intermediate factory has become
implicit in the above code replaced with AmqpInvoker.with(). In Java prior to version 8, the same effect can be
achieved with an inner Factory class:
The builder used above could look like this (although this is a simplification as the actual one permits defining of up
to 15 parameters deviating from defaults). Note that the construct is not public, so it is specifically usable only from
the above AmqpInvoker interface:
@Override
public <RQ, RS> CompletableFuture<RS> invoke(final RQ request, final Class<RS> respClass) {
...
}
}
Meanwhile, this pattern proved to be very efficient in developing all our new code not matter how simple or
complex the functionality is.
The following example demonstrates how ClassB overrides the functionality of ClassA by changing what gets sent
out through the printing method:
Example:
class ClassA {
public void printing() {
System.out.println("A");
}
}
Output:
class Car {
public int gearRatio = 8;
Casting an instance of a subclass to a base class as in: A a = b; is called widening and does not need a type-cast.
class Vehicle {
}
class Test {
The statement Vehicle vehicle = new Car(); is a valid Java statement. Every instance of Car is also a Vehicle.
Therefore, the assignment is legal without the need for an explicit type-cast.
On the other hand, Car c = vehicle; is not valid. The static type of the vehicle variable is Vehicle which means
that it could refer to an instance of Car, Truck,MotorCycle, or any other current or future subclass
ofVehicle. (Or indeed, an instance ofVehicleitself, since we did not declare it as anabstractclass.)
The assignment cannot be allowed, since that might lead tocarreferring to aTruck` instance.
The type-cast tells the compiler that we expect the value of vehicle to be a Car or a subclass of Car. If necessary,
compiler will insert code to perform a run-time type check. If the check fails, then a ClassCastException will be
thrown when the code is executed.
The Java compiler knows that an instance that is type compatible with Vehicle cannot ever be type compatible with
String. The type-cast could never succeed, and the JLS mandates that this gives in a compilation error.
class StaticMethodTest {
Static methods are bind to a class not to an instance and this method binding happens at compile time. Since in the
first call to staticMethod(), parent class reference p was used, Parent's version of staticMethod() is invoked. In
second case, we did cast p into Child class, Child's staticMethod() executed.
Strong Reference
Weak Reference
Soft Reference
Phantom Reference
1. Strong Reference
The variable holder is holding a strong reference to the object created. As long as this variable is live and holds this
value, the MyObject instance will not be collected by the garbage collector.
2. Weak Reference
When you do not want to keep an object longer, and you need to clear/free the memory allocated for an object as
soon as possible, this is the way to do so.
Simply, a weak reference is a reference that isn't strong enough to force an object to remain in memory. Weak
references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have
to do it yourself.
When you need the object you created, just use .get() method:
myObjectRef.get();
3. Soft Reference
Soft references are slightly stronger than weak references. You can create a soft referenced object as following:
They can hold onto the memory more strongly than the weak reference. If you have enough memory
supply/resources, garbage collector will not clean the soft references as enthusiastically as weak references.
4. Phantom Reference
This is the weakest referencing type. If you created an object reference using Phantom Reference, the get()
method will always return null!
The use of this referencing is that "Phantom reference objects, which are enqueued after the collector determines
that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-
mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism." - From
Phantom Reference Javadoc from Oracle.
In Java, Strings are immutable, meaning that they cannot be changed. (Click here for a more thorough explanation
of immutability.)
For example, the following snippet will determine if the two instances of String are equal on all characters:
if (firstString.equals(secondString)) {
// Both Strings have the same content.
}
Live demo
if (firstString.equalsIgnoreCase(secondString)) {
// Both Strings are equal, ignoring the case of the individual characters.
}
Live demo
Note that equalsIgnoreCase does not let you specify a Locale. For instance, if you compare the two words "Taki"
and "TAKI" in English they are equal; however, in Turkish they are different (in Turkish, the lowercase I is ?). For
cases like this, converting both strings to lowercase (or uppercase) with Locale and then comparing with equals is
the solution.
System.out.println(firstString.toLowerCase(locale).equals(
secondString.toLowerCase(locale))); //prints false
Live demo
Unless you can guarantee that all strings have been interned (see below), you should not use the
==
Instead, use the String.equals(Object) method, which will compare the String objects based on their values. For a
detailed explanation, please refer to Pitfall: using == to compare strings.
As of Java 1.7, it is possible to compare a String variable to literals in a switch statement. Make sure that the String
is not null, otherwise it will always throw a NullPointerException. Values are compared using String.equals, i.e.
case sensitive.
switch (stringToSwitch) {
case "a":
System.out.println("a");
break;
case "A":
System.out.println("A"); //the code goes here
break;
case "B":
System.out.println("B");
break;
default:
break;
}
Live demo
When comparing a String to a constant value, you can put the constant value on the left side of equals to ensure
that you won't get a NullPointerException if the other String is null.
"baz".equals(foo)
While foo.equals("baz") will throw a NullPointerException if foo is null, "baz".equals(foo) will evaluate to
false.
Version ≥ Java SE 7
A more readable alternative is to use Objects.equals(), which does a null check on both parameters:
Objects.equals(foo, "baz").
(Note: It is debatable as to whether it is better to avoid NullPointerExceptions in general, or let them happen and
then fix the root cause; see here and here. Certainly, calling the avoidance strategy "best practice" is not justifiable.)
String orderings
The String class implements Comparable<String> with the String.compareTo method (as described at the start of
this example). This makes the natural ordering of String objects case-sensitive order. The String class provide a
Comparator<String> constant called CASE_INSENSITIVE_ORDER suitable for case-insensitive sorting.
"Moreover, a string literal always refers to the same instance of class String. This is because string literals
- or, more generally, strings that are the values of constant expressions - are interned so as to share
unique instances, using the method String.intern."
==
. Moreover, the same is true for references to String objects that have been produced using the String.intern()
method.
For example:
// The two string references point two strings that are equal
if (strObj.equals(str)) {
System.out.println("The strings are equal");
}
if (internedStr == str) {
System.out.println("The interned string and the literal are the same object");
}
Behind the scenes, the interning mechanism maintains a hash table that contains all interned strings that are still
reachable. When you call intern() on a String, the method looks up the object in the hash table:
If the string is found, then that value is returned as the interned string.
Otherwise, a copy of the string is added to the hash table and that string is returned as the interned string.
==
. However, there are significant problems with doing this; see Pitfall - Interning strings so that you can use == is a
bad idea for details. It is not recommended in most cases.
Non-alphabetic characters, such as digits and punctuation marks, are unaffected by these methods. Note that these
methods may also incorrectly deal with certain Unicode characters under certain conditions.
Note: These methods are locale-sensitive, and may produce unexpected results if used on strings that are intended
to be interpreted independent of the locale. Examples are programming language identifiers, protocol keys, and
HTML tags.
For instance, "TITLE".toLowerCase() in a Turkish locale returns "t?tle", where ? (\u0131) is the LATIN SMALL
LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, pass Locale.ROOT as a
parameter to the corresponding case converting method (e.g. toLowerCase(Locale.ROOT) or
toUpperCase(Locale.ROOT)).
Although using Locale.ENGLISH is also correct for most cases, the language invariant way is Locale.ROOT.
A detailed list of Unicode characters that require special casing can be found on the Unicode Consortium website.
To change the case of a specific character of an ASCII string following algorithm can be used:
Steps:
1. Declare a string.
2. Input the string.
3. Convert the string into a character array.
4. Input the character that is to be searched.
5. Search for the character into the character array.
6. If found,check if the character is lowercase or uppercase.
If Uppercase, add 32 to the ASCII code of the character.
If Lowercase, subtract 32 from the ASCII code of the character.
7. Change the original character from the Character array.
8. Convert the character array back into the string.
The String.contains() method can be used to verify if a CharSequence can be found in the String. The method
looks for the String a in the String b in a case-sensitive way.
To find the exact position where a String starts within another String, use String.indexOf():
The String.indexOf() method returns the first index of a char or String in another String. The method returns
-1 if it is not found.
class Strings
{
public static void main (String[] args)
{
String a = "alpha";
String b = "alpha";
String c = new String("alpha");
true
true
true
true
However using new operator, we force String class to create a new String object in heap space. We can use intern()
method to put it into the pool or refer to other String object from string pool having same value.
Before Java 7, String literals were stored in the runtime constant pool in the method area of PermGen, that had a
fixed size.
Version ≥ Java SE 7
RFC: 6962931
In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are
instead allocated in the main part of the Java heap (known as the young and old generations), along with
the other objects created by the application. This change will result in more data residing in the main Java
heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most
applications will see only relatively small differences in heap usage due to this change, but larger
applications that load many classes or make heavy use of the String.intern() method will see more
significant differences.
Note that delimiting character or regular expression gets removed from the resulting String Array.
In the previous example . is treated as the regular expression wildcard that matches any character, and since every
character is a delimiter, the result is an empty array.
< > - = ! ( ) [ ] { } \ ^ $ | ? * + .
To split a string based on one of the above delimiters, you need to either escape them using \\ or use
Pattern.quote():
Using Pattern.quote():
String s = "a|b|c";
String regex = Pattern.quote("|");
String[] arr = s.split(regex);
String s = "a|b|c";
String[] arr = s.split("\\|");
split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need
to use overloaded version of split(delimiter, limit) with limit set to negative value like
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the
resulting array.
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no
greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
If n is negative, then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing
empty strings will be discarded.
Besides the split() method Strings can also be split using a StringTokenizer.
StringTokenizer is even more restrictive than String.split(), and also a bit harder to use. It is essentially
designed for pulling out tokens delimited by a fixed set of characters (given as a String). Each character will act as a
separator. Because of this restriction, it's about twice as fast as String.split().
Default set of characters are empty spaces (\t\n\r\f). The following example will print out each word separately.
the
lazy
fox
jumped
over
the
brown
fence
j
mp
d ov
r
To have a fine-grained control over joining, you may use StringJoiner class:
sj.add("foo");
sj.add("bar");
sj.add("foobar");
String s1 = "a";
String s2 = "b";
String s3 = "c";
String s = s1 + s2 + s3; // abc
Normally a compiler implementation will perform the above concatenation using methods involving a
StringBuilder under the hood. When compiled, the code would look similar to the below:
StringBuilder has several overloaded methods for appending different types, for example, to append an int
instead of a String. For example, an implementation can convert:
String s1 = "a";
String s2 = "b";
String s = s1 + s2 + 2; // ab2
to the following:
The above examples illustrate a simple concatenation operation that is effectively done in a single place in the code.
The concatenation involves a single instance of the StringBuilder. In some cases, a concatenation is carried out in
a cumulative way such as in a loop:
In such cases, the compiler optimization is usually not applied, and each iteration will create a new StringBuilder
object. This can be optimized by explicitly transforming the code to use a single StringBuilder:
A StringBuilder will be initialized with an empty space of only 16 characters. If you know in advance that you will
be building larger strings, it can be beneficial to initialize it with sufficient size in advance, so that the internal buffer
does not need to be resized:
If (and only if) multiple threads are writing to the same buffer, use StringBuffer, which is a synchronized version of
StringBuilder. But because usually only a single thread writes to a buffer, it is usually faster to use StringBuilder
without synchronization.
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method
with string literals, as in:
Substrings may also be applied to slice and add/replace character into its original String. For instance, you faced a
Chinese date containing Chinese characters but you want to store it as a well format Date String.
The substring method extracts a piece of a String. When provided one parameter, the parameter is the start and
the piece extends until the end of the String. When given two parameters, the first parameter is the starting
In JDK <7u6 versions the substring method instantiates a String that shares the same backing char[] as the
original String and has the internal offset and count fields set to the result start and length. Such sharing may
cause memory leaks, that can be prevented by calling new String(s.substring(...)) to force creation of a copy,
after which the char[] can be garbage collected.
Version ≥ Java SE 7
From JDK 7u6 the substring method always copies the entire underlying char[] array, making the complexity
linear compared to the previous constant one but guaranteeing the absence of memory leaks at the same time.
System.getProperty("line.separator")
Version ≥ Java SE 7
Because the new line separator is so commonly needed, from Java 7 on a shortcut method returning exactly the
same result as the code above is available:
System.lineSeparator()
Note: Since it is very unlikely that the new line separator changes during the program's execution, it is a good idea
to store it in in a static final variable instead of retrieving it from the system property every time it is needed.
When using String.format, use %n rather than \n or '\r\n' to output a platform independent new line separator.
1. StringBuilder/StringBuffer:
System.out.println(code);
2. Char array:
// print reversed
System.out.println(new String(array));
String name;
int age;
and later in your code you use the following statement in order to print the object:
System.out.println(person.toString());
Person@7ab89d
This is the result of the implementation of the toString() method defined in the Object class, a superclass of
Person. The documentation of Object.toString() states:
The toString method for class Object returns a string consisting of the name of the class of which the
object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal to the value of:
So, for meaningful output, you'll have to override the toString() method:
@Override
public String toString() {
System.out.println(person);
If you trim a String that doesn't have any whitespace to remove, you will be returned the same String instance.
Note that the trim() method has its own notion of whitespace, which differs from the notion used by the
Character.isWhitespace() method:
All ASCII control characters with codes U+0000 to U+0020 are considered whitespace and are removed by
trim(). This includes U+0020 'SPACE', U+0009 'CHARACTER TABULATION', U+000A 'LINE FEED' and U+000D
'CARRIAGE RETURN' characters, but also the characters like U+0007 'BELL'.
Unicode whitespace like U+00A0 'NO-BREAK SPACE' or U+2003 'EM SPACE' are not recognized by trim().
switch itself can not be parameterised to be case insensitive, but if absolutely required, can behave insensitive to
the input string by using toLowerCase() or toUpperCase:
switch (myString.toLowerCase()) {
case "case1" :
...
break;
case "case2" :
...
break;
}
Beware
Note: the original String object will be unchanged, the return value holds the changed String.
Exact match
Replace single character with another single character:
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String s = "popcorn";
System.out.println(s.replace('p','W'));
Result:
WoWcorn
Replaces each substring of this string that matches the literal target sequence with the specified literal
replacement sequence.
Result:
Regex
Note: the grouping uses the $ character to reference the groups, like $1.
Replaces each substring of this string that matches the given regular expression with the given
replacement.
Result:
Result:
A char in a String is UTF-16 value. Unicode codepoints whose values are ? 0x1000 (for example, most emojis) use
two char positions. To count the number of Unicode codepoints in a String, regardless of whether each codepoint
fits in a UTF-16 char value, you can use the codePointCount method:
System.out.println(str.charAt(0)); // "M"
System.out.println(str.charAt(1)); // "y"
System.out.println(str.charAt(2)); // " "
System.out.println(str.charAt(str.length-1)); // Last character "g"
To get the nth character in a string, simply call charAt(n) on a String, where n is the index of the character you
would like to retrieve
import org.apache.commons.lang3.StringUtils;
String text = "One fish, two fish, red fish, blue fish";
Otherwise for does the same with standard Java API's you could use Regular Expressions:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String text = "One fish, two fish, red fish, blue fish";
System.out.println(countStringInString("fish", text)); // prints 4
System.out.println(countStringInString(",", text)); // prints 3
int stringOccurrences = 0;
while (matcher.find()) {
stringOccurrences++;
}
return stringOccurrences;
}
Methods:
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study
The StringBuffer class has been present since Java 1.0, and provides a variety of methods for building and
modifying a "buffer" containing a sequence of characters.
The StringBuilder class was added in Java 5 to address performance issues with the original StringBuffer
class. The APIs for the two clases are essentially the same. The main difference between StringBuffer and
StringBuilder is that the former is thread-safe and synchronized and the latter is not.
int one = 1;
String color = "red";
StringBuilder sb = new StringBuilder();
sb.append("One=").append(one).append(", Color=").append(color).append('\n');
System.out.print(sb);
// Prints "One=1, Colour=red" followed by an ASCII newline.
(The StringBuffer class is used the same way: just change StringBuilder to StringBuffer in the above)
The StringBuffer and StringBuilder classes are suitable for both assembling and modifying strings; i.e they
provide methods for replacing and removing characters as well as adding them in various. The remining two
classes are specific to the task of assembling strings.
The Formatter class was added in Java 5, and is loosely modeled on the sprintf function in the C standard
library. It takes a format string with embedded format specifiers and a sequences of other arguments, and
generates a string by converting the arguments into text and substituting them in place of the format
specifiers. The details of the format specifiers say how the arguments are converted into text.
The StringJoiner class was added in Java 8. It is a special purpose formatter that succinctly formats a
sequence of strings with separators between them. It is designed with a fluent API, and can be used with Java
8 streams.
This creates n new string instances containing 1 to n repetitions of s resulting in a runtime of O(s.length() * n²) =
O(s.length() * (1+2+...+(n-1)+n)).
To avoid this StringBuilder should be used, which allows creating the String in O(s.length() * n) instead:
The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-
token basis.
Output:
apple
ball
cat
dog
Output:
apple
ball cat
dog
The regex matches 8 characters after the end of the last match. Since in this case the match is zero-width, we could
more simply say "8 characters after the last match".
Conveniently, \G is initialized to start of input, so it works for the first part of the input too.
int length = 5;
String[] parts = str.split("(?<=\\G.{" + length + "})");
which will widen the intValue integer to long, using sign bit extension for negative values, so that negative values
will stay negative.
Following constructor is used to translate the String representation of a BigInteger in the specified radix into a
BigInteger.
Java also supports direct conversion of bytes to an instance of BigInteger. Currently only signed and unsigned big
endian encoding may be used:
This will generate a BigInteger instance with value -128 as the first bit is interpreted as the sign bit.
This will generate a BigInteger instance with value 128 as the bytes are interpreted as unsigned number, and the
sign is explicitly set to 1, a positive number.
There's also BigInteger.TWO (value of "2"), but you can't use it in your code because it's private.
Addition: 10 + 10 = 20
output: 20
Substraction: 10 - 9 = 1
output: 1
Division: 10 / 5 = 2
output: 2
Division: 17/4 = 4
output: 4
output: 50
Power: 10 ^ 3 = 1000
output: 1000
Remainder: 10 % 6 = 4
output: 4
System.out.println(value1.gcd(value2));
Output: 6
System.out.println(value1.max(value2));
Output: 11
System.out.println(value1.min(value2));
Output: 10
For example:
if(one.equals(two)){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
Output:
Not Equal
Note:
==
==
operator: compares references; i.e. whether two values refer to the same object
equals() method: compares the content of two BigIntegers.
if (firstBigInteger == secondBigInteger) {
// Only checks for reference equality, not content equality!
}
==
operator only checks for reference equality. If both BigIntegers contain the same content, but do not refer to the
same object, this will fail. Instead, compare BigIntegers using the equals methods, as explained above.
You can also compare your BigInteger to constant values like 0,1,10.
for example:
You can also compare two BigIntegers by using compareTo() method, as following: compareTo() returns 3 values.
if(reallyBig.compareTo(reallyBig1) == 0){
//code when both are equal.
}
else if(reallyBig.compareTo(reallyBig1) == 1){
//code when reallyBig is greater than reallyBig1.
}
else if(reallyBig.compareTo(reallyBig1) == -1){
//code when reallyBig is less than reallyBig1.
}
Binary Or:
val1.or(val2);
Binary And:
val1.and(val2);
Binary Xor:
val1.xor(val2);
RightShift:
LeftShift:
val1.not();
Output: 5
NAND (And-Not):*
val1.andNot(val2);
Output: 7
then you'll end up with a BigInteger whose value is between 0 (inclusive) and 2bitCount (exclusive).
This also means that new BigInteger(2147483647, sourceOfRandomness) may return all positive BigIntegers
given enough time.
If you're willing to give up speed for higher-quality random numbers, you can use a new
="https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html" rel="nofollow
noreferrer">SecureRandom() instead:
import java.security.SecureRandom;