Java Language #java
Table of Contents 1 2 About 2 Chapter 1: Getting started with Java Language 2 3 Remarks 3 Java Editions and Versions 3 Installing Java 3 Compiling and running Java programs 3 What's next? 4 Testing 4 Other 4 Versions Examples 6 11 Creating Your First Java Program 11 11 A closer look at the Hello World program Chapter 2: 2D Graphics in Java 11 13 Introduction Examples 14 14 Example 1: Draw and Fill a Rectangle Using Java 14 Example 2: Drawing and Filling Oval 14 Chapter 3: Alternative Collections 14 Remarks 15 Examples 15 16 Apache HashBag, Guava HashMultiset and Eclipse HashBag 16 1. Using SynchronizedSortedBag from Apache: 19 2. Using TreeBag from Eclipse(GC): 19 3. Using LinkedHashMultiset from Guava: 19 More examples: Multimap in Guava, Apache and Eclipse Collections Nore examples: Compare operation with collections - Create collections Compare operation with collections - Create collections
Chapter 4: Annotations 25 Introduction 25 Syntax 25 Remarks 25 25 Parameter types 25 Examples 25 Built-in annotations 29 Runtime annotation checks via reflection 29 Defining annotation types 30 Default values 30 Meta-Annotations 30 @Target 30 Available Values 31 @Retention 32 32 Available values 32 @Documented 32 @Inherited 32 @Repeatable 33 35 Getting Annotation values at run-time 35 Repeating Annotations 36 Inherited Annotations Example 36 Compile time processing using annotation processor 36 38 The annotation 38 The annotation processor 38 Packaging 39 Example annotated class 39 Using the annotation processor with javac IDE integration 39 Netbeans Result
The idea behind Annotations 40 Annotations for 'this' and receiver parameters 40 Add multiple annotation values 41 Chapter 5: Apache Commons Lang 42 Examples 42 Implement equals() method 42 Implement hashCode() method 42 Implement toString() method 43 Chapter 6: AppDynamics and TIBCO BusinessWorks Instrumentation for Easy Integration 45 Introduction 45 Examples 45 Example of Instrumentation of all BW Applications in a Single Step for Appdynamics 45 *** Common variables. Modify these only. *** 45 Chapter 7: Applets 47 47 Introduction 47 Remarks 47 Examples 47 Minimal Applet 48 Creating a GUI 49 Open links from within the applet 49 Loading images, audio and other resources 49 Load and show an image 50 Load and play an audio file 50 Load and display a text file 52 Chapter 8: Arrays 52 Introduction 52 Syntax 52 Parameters 52 Examples 52 Creating and Initializing Arrays 52 Basic cases
Arrays, Collections, and Streams 53 Intro 53 Creating and initializing primitive type arrays 55 Creating and initializing multi-dimensional arrays 56 Multidimensional array representation in Java 57 Creating and initializing reference type arrays 57 Creating and initializing generic type arrays 58 Filling an array after initialization 58 Separate declaration and initialization of arrays 59 Arrays may not be re-initialized with array initializer shortcut syntax 59 60 Creating an Array from a Collection 61 Arrays to a String 62 Creating a List from an Array 63 Important notes related to using Arrays.asList() method 64 Multidimensional and Jagged Arrays 65 How Multidimensional Arrays are represented in Java 66 ArrayIndexOutOfBoundsException 67 Getting the Length of an Array 67 Comparing arrays for equality 68 Arrays to Stream 68 Iterating over arrays 71 Copying arrays 71 71 for loop 72 Object.clone() 72 Arrays.copyOf() 72 System.arraycopy() 73 Arrays.copyOfRange() 73 73 Casting Arrays Remove an element from an array Using ArrayList
Using System.arraycopy 74 Using Apache Commons Lang 74 74 Array Covariance 75 How do you change the size of an array? 76 A better alternatives to array resizing 76 Finding an element in an array 76 Using Arrays.binarySearch (for sorted arrays only) 76 Using a Arrays.asList (for non-primitive arrays only) 77 Using a Stream 77 Linear search using a loop 77 Linear search using 3rd-party libraries such as org.apache.commons 77 Testing if an array contains an element 78 Sorting arrays 79 Converting arrays between primitives and boxed types 81 81 Chapter 9: Asserting 81 Syntax 81 Parameters 81 Remarks 81 Examples 82 82 Checking arithmetic with assert 82 82 Chapter 10: Atomic Types 82 Introduction 82 Parameters 83 Remarks 84 Examples 85 87 Creating Atomic Types 87 Motivation for Atomic Types How does one implement Atomic Types? How do Atomic Types work? Chapter 11: Audio Remarks
Examples 87 Play an Audio file Looped 87 Play a MIDI file 87 Bare metal sound 89 Basic audio output 89 91 Chapter 12: Autoboxing 91 Introduction 91 Remarks 91 Examples 91 92 Using int and Integer interchangeably 93 Using Boolean in if statement 93 Auto-unboxing may lead to NullPointerException 94 Memory and Computational Overhead of Autoboxing 96 Different Cases When Integer and int can be used interchangeably 96 96 Chapter 13: Basic Control Structures 96 Remarks 97 Examples 98 98 If / Else If / Else Control 98 For Loops 99 While Loops 100 do...while Loop 102 For Each 102 If / Else 102 Switch statement 103 Ternary Operator 104 Break 105 Try ... Catch ... Finally 105 Nested break / continue 105 Continue Statement in Java Chapter 14: Benchmarks Introduction Examples
Simple JMH example 105 Chapter 15: BigDecimal 108 Introduction 108 Examples 108 BigDecimal objects are immutable 108 Comparing BigDecimals 108 Mathematical operations with BigDecimal 108 1.Addition 108 2.Subtraction 109 3.Multiplication 109 4.Division 109 5.Remainder or Modulus 110 6.Power 110 7.Max 111 8.Min 111 9.Move Point To Left 111 10.Move Point To Right 111 112 Using BigDecimal instead of float 113 BigDecimal.valueOf() 113 Initialization of BigDecimals with value zero, one or ten 114 Chapter 16: BigInteger 114 Introduction 114 Syntax 114 Remarks 115 Examples 115 Initialization 116 Comparing BigIntegers 117 BigInteger Mathematical Operations Examples 119 Binary Logic Operations on BigInteger 120 Generating random BigIntegers 122 Chapter 17: Bit Manipulation
Remarks 122 Examples 122 122 Packing / unpacking values as bit fragments 123 Checking, setting, clearing, and toggling individual bits. Using long as bit mask 123 Expressing the power of 2 124 Checking if a number is a power of 2 126 java.util.BitSet class 126 Signed vs unsigned shift 128 128 Chapter 18: BufferedWriter 128 Syntax 128 Remarks 128 Examples 130 130 Write a line of text to File 130 130 Chapter 19: ByteBuffer 130 Introduction 131 Syntax 131 Examples 133 133 Basic Usage - Creating a ByteBuffer 133 Basic Usage - Write Data to the Buffer 133 Basic Usage - Using DirectByteBuffer 133 133 Chapter 20: Bytecode Modification 134 Examples 134 137 What is Bytecode? 137 138 What's the logic behind this? Well, there has to be more right? How can I write / edit bytecode? I'd like to learn more about bytecode! How to edit jar files with ASM How to load a ClassNode as a Class How to rename classes in a jar file Javassist Basic
Chapter 21: C++ Comparison 140 Introduction 140 Remarks 140 140 Classes Defined within Other Constructs# 140 Defined within Another Class 140 140 C++ 140 Java 140 Statically Defined within Another Class 141 C++ 141 Java 141 Defined within a Method 141 C++ 141 Java 142 Overriding vs Overloading 142 Polymorphism 142 Order of Construction/Destruction 143 Object Cleanup 143 Abstract Methods & Classes 143 Accessibility Modifiers 144 C++ Friend Example 144 The Dreaded Diamond Problem 144 java.lang.Object Class 144 Java Collections & C++ Containers 144 Java Collections Flowchart 144 C++ Containers Flowchart 145 Integer Types Examples 145 145 Static Class Members 145 C++ Example Java Example
Classes Defined within Other Constructs 146 Defined within Another Class 146 C++ 146 Java 146 146 Statically Defined within Another Class 146 C++ 147 Java 147 147 Defined within a Method 147 C++ Java 147 Pass-by-value & Pass-by-reference 147 148 C++ Example (complete code) 149 Java Example (complete code) 149 149 Inheritance vs Composition 149 Outcast Downcasting 149 C++ Example 149 Java Example 149 Abstract Methods & Classes 149 Abstract Method 149 C++ 150 Java 150 Abstract Class 150 C++ 150 Java 150 Interface 151 C++ 151 Java 151 Chapter 22: Calendar and its Subclasses Remarks 151 Examples Creating Calendar objects
Increasing / Decreasing calendar fields 151 Finding AM/PM 152 Subtracting calendars 152 Chapter 23: Character encoding 153 Examples 153 Reading text from a file encoded in UTF-8 153 Writing text to a file in UTF-8 153 Getting byte representation of a string in UTF-8 154 Chapter 24: Choosing Collections 155 Introduction 155 Examples 155 Java Collections Flowchart 155 Chapter 25: Class - Java Reflection 156 Introduction 156 Examples 156 getClass() method of Object class 156 Chapter 26: Classes and Objects 157 Introduction 157 Syntax 157 Examples 157 Simplest Possible Class 157 Object Member vs Static Member 157 Overloading Methods 158 Basic Object Construction and Use 159 Constructors 162 Initializing static final fields using a static initializer 163 Explaining what is method overloading and overriding. 163 Chapter 27: Classloaders 167 Remarks 167 Examples 167 Instantiating and using a classloader 167 Implementing a custom classLoader 167
Loading an external .class file 168 Chapter 28: Collection Factory Methods 170 Introduction 170 Syntax 170 Parameters 170 Examples 170 List Factory Method Examples 170 Set Factory Method Examples 171 Map Factory Method Examples 171 Chapter 29: Collections 172 Introduction 172 Remarks 172 Examples 173 Declaring an ArrayList and adding objects 173 Constructing collections from existing data 174 Standard Collections 174 Java Collections framework 174 Google Guava Collections framework 174 174 Mapping Collections 175 Java Collections framework 175 Apache Commons Collections framework 175 Google Guava Collections framework 176 Join lists 176 Removing items from a List within a loop 176 INCORRECT 176 Removing in iteration of for statement Skips \"Banana\": 177 Removing in the enhanced for statement Throws Exception: 177 177 CORRECT 178 Removing in while loop using an Iterator 178 Iterating backwards Iterating forward, adjusting the loop index
Using a \"should-be-removed\" list 179 Filtering a Stream 179 Using removeIf 179 179 Unmodifiable Collection 180 Iterating over Collections 180 181 Iterating over List 181 Iterating over Set 182 Iterating over Map 182 183 Immutable Empty Collections 184 Collections and Primitive Values 186 Removing matching items from Lists using Iterator. 186 Creating your own Iterable structure for use with Iterator or for-each loop. 186 Pitfall: concurrent modification exceptions 187 Sub Collections 187 List subList(int fromIndex, int toIndex) 188 Set subSet(fromIndex,toIndex) 188 Map subMap(fromKey,toKey) 188 Chapter 30: Command line Argument Processing 188 Syntax 188 Parameters 188 Remarks 189 Examples 189 190 Argument processing using GWT ToolBase 190 Processing arguments by hand 192 A command with no arguments 192 A command with two arguments 192 A command with \"flag\" options and at least one argument 192 Chapter 31: Common Java Pitfalls Introduction Examples Pitfall: using == to compare primitive wrappers objects such as Integer
Pitfall: forgetting to free resources 193 Pitfall: memory leaks 194 Pitfall: using == to compare strings 195 Pitfall: testing a file before attempting to open it. 197 Pitfall: thinking of variables as objects 198 Example class 199 Multiple variables can point to the same object 199 The equality operator does NOT test that two objects are equal 200 Method calls do NOT pass objects at all 201 Pitfall: combining assignment and side-effects 201 Pitfall: Not understanding that String is an immutable class 202 Chapter 32: Comparable and Comparator 204 Syntax 204 Remarks 204 Examples 204 Sorting a List using Comparable or a Comparator 205 Lambda expression based comparators 208 Comparator default methods 208 Inversing the order of a comparator 208 208 The compareTo and compare Methods 209 Natural (comparable) vs explicit (comparator) sorting 210 Sorting Map entries 211 Creating a Comparator using comparing method 212 Chapter 33: CompletableFuture 212 Introduction 212 Examples 212 Convert blocking method to asynchonous 213 Simple Example of CompletableFuture 214 Chapter 34: Concurrent Collections 214 Introduction 214 Examples
Thread-safe Collections 214 Concurrent Collections 214 Thread safe but non concurrent examples 216 Insertion into ConcurrentHashMap 216 218 Chapter 35: Concurrent Programming (Threads) 218 Introduction 218 Remarks 218 Examples 218 Basic Multithreading 219 Producer-Consumer 220 Using ThreadLocal 221 CountDownLatch 223 Synchronization 224 Atomic operations 225 Creating basic deadlocked system 227 Pausing Execution 228 Visualizing read/write barriers while using synchronized / volatile 229 Creating a java.lang.Thread instance 231 Thread Interruption / Stopping Threads 233 Multiple producer/consumer example with shared global queue 235 Exclusive write / Concurrent read access 237 Runnable Object 237 Semaphore 238 Add two `int` arrays using a Threadpool 239 Get status of all threads started by your program excluding system threads 240 Callable and Future 242 Locks as Synchronisation aids 244 Chapter 36: Console I/O 244 Examples 244 Reading user input from the console 244 Using BufferedReader: 244 Using Scanner:
Using System.console: 245 Implementing Basic Command-Line Behavior 246 Aligning strings in console 247 248 Format strings examples 249 Chapter 37: Constructors 249 249 Introduction 249 Remarks 249 Examples 250 251 Default Constructor 253 Constructor with Arguments 253 Call parent constructor 253 253 Chapter 38: Converting to and from Strings 254 Examples 255 256 Converting other datatypes to String 256 Conversion to / from bytes 259 Base64 Encoding / Decoding 259 Parsing Strings to a Numerical Value 259 Getting a `String` from an `InputStream` 259 Converting String to other datatypes. 260 260 Chapter 39: Creating Images Programmatically 262 Remarks 263 Examples 264 264 Creating a simple image programmatically and displaying it 266 Save an Image to disk 266 Specifying image rendering quality 266 Creating an image with BufferedImage class Editing and re-using image with BufferedImage Setting individual pixel's color in BufferedImage How to scale a BufferedImage Chapter 40: Currency and Money Examples Add custom currency
Chapter 41: Date Class 267 Syntax 267 Parameters 267 Remarks 267 Examples 268 Creating Date objects 268 Comparing Date objects 269 Calendar, Date, and LocalDate 269 before, after, compareTo and equals methods 269 isBefore, isAfter, compareTo and equals methods 270 Date comparison before Java 8 270 Since Java 8 271 272 Converting Date to a certain String format 272 Converting String into Date 273 A basic date output 273 Convert formatted string representation of date to Date object 274 Creating a Specific Date 274 Java 8 LocalDate and LocalDateTime objects 275 Time Zones and java.util.Date 276 Convert java.util.Date to java.sql.Date 277 LocalTime 278 Chapter 42: Dates and Time (java.time.*) 278 Examples 278 Simple Date Manipulations 278 Date and time 279 Operations on dates and times 279 Instant 279 Usage of various classes of Date Time API 281 Date Time Formatting 282 Calculate Difference between 2 LocalDates 283 Chapter 43: Default Methods
Introduction 283 Syntax 283 Remarks 283 Default methods 283 Static methods 283 References : 284 Examples 284 284 Basic usage of default methods 285 Accessing other interface methods within default method 286 Accessing overridden default methods from implementing class 286 Why use Default Methods? 287 Class, Abstract class and Interface method precedence 288 Default method multiple inheritance collision 290 290 Chapter 44: Dequeue Interface 290 Introduction 290 Remarks 290 Examples 290 291 Adding Elements to Deque 291 Removing Elements from Deque 292 Retrieving Element without Removing 292 Iterating through Deque 292 292 Chapter 45: Disassembling and Decompiling 293 Syntax 300 Parameters 300 Examples 300 301 Viewing bytecode with javap 301 301 Chapter 46: Documenting Java Code Introduction Syntax Remarks Examples Class Documentation
Method Documentation 302 Field Documentation 302 Package Documentation 303 Links 303 Building Javadocs From the Command Line 304 Inline Code Documentation 305 Code snippets inside documentation 306 Chapter 47: Dynamic Method Dispatch 307 Introduction 307 Remarks 307 Examples 307 Dynamic Method Dispatch - Example Code 307 Chapter 48: Encapsulation 310 Introduction 310 Remarks 310 Examples 310 Encapsulation to maintain invariants 310 Encapsulation to reduce coupling 311 Chapter 49: Enum Map 313 Introduction 313 Examples 313 Enum Map Book Example 313 Chapter 50: Enum starting with number 314 Introduction 314 Examples 314 Enum with name at begining 314 Chapter 51: Enums 315 Introduction 315 Syntax 315 Remarks 315 Restrictions 315
Tips & Tricks 315 Examples 316 316 Declaring and using a basic enum 319 Enums with constructors 321 Using methods and static blocks 322 Implements Interface 323 Enum Polymorphism Pattern 324 Enums with Abstract Methods 324 Documenting enums 325 Getting the values of an enum 325 Enum as a bounded type parameter 326 Get enum constant by name 326 Implement Singleton pattern with a single-element enum 327 Enum with properties (fields) 328 Convert enum to String 328 328 Convert using name() 328 Convert using toString() 329 329 By default: 330 Example of being overridden 331 332 Enum constant specific body 334 Zero instance enum 334 Enums with static fields 334 Compare and Contains for Enum values 334 335 Chapter 52: EnumSet class 335 Introduction 335 Examples 335 335 Enum Set Example Chapter 53: Exceptions and exception handling Introduction Syntax Examples Catching an exception with try-catch
Try-catch with one catch block 335 Try-catch with multiple catches 336 Multi-exception catch blocks 337 337 Throwing an exception 338 Exception chaining 339 340 Custom Exceptions 341 The try-with-resources statement 341 What is a resource? 341 The basic try-with-resource statement 342 The enhanced try-with-resource statements 342 Managing multiple resources 344 Equivalence of try-with-resource and classical try-catch-finally 344 Creating and reading stacktraces 344 Printing a stacktrace 346 Understanding a stacktrace 347 Exception chaining and nested stacktraces 348 Capturing a stacktrace as a String 349 Handling InterruptedException 349 The Java Exception Hierarchy - Unchecked and Checked Exceptions 350 Checked versus Unchecked Exceptions 352 Checked exception examples 354 Introduction 355 Return statements in try catch block 355 Advanced features of Exceptions 355 Examining the callstack programmatically 356 Optimizing exception construction 356 Erasing or replacing the stacktrace 357 Suppressed exceptions 357 The try-finally and try-catch-finally statements 357 Try-finally 358 try-catch-finally The 'throws' clause in a method declaration
What is the point of declaring unchecked exceptions as thrown? 359 Throws and method overriding 359 Chapter 54: Executor, ExecutorService and Thread pools 361 Introduction 361 Remarks 361 Examples 361 361 Fire and Forget - Runnable Tasks 362 ThreadPoolExecutor 363 Retrieving value from computation - Callable 364 Scheduling tasks to run at a fixed time, after a delay or repeatedly 364 Starting a task after a fixed delay 364 Starting tasks at a fixed rate 365 Starting tasks with a fixed delay 365 Handle Rejected Execution 366 submit() vs execute() exception handling differences 368 Use cases for different types of concurrency constructs 369 Wait for completion of all tasks in ExecutorService 371 Use cases for different types of ExecutorService 373 Using Thread Pools 374 374 Chapter 55: Expressions 374 Introduction 374 Remarks 374 Examples 375 376 Operator Precedence 377 Constant Expressions 377 Uses for Constant Expressions 377 Expression evaluation order 378 Simple Example 379 Example with an operator which has a side-effect 379 Expression Basics The Type of an Expression The value of an Expression
Expression Statements 379 Chapter 56: File I/O 381 381 Introduction 381 Examples 381 381 Reading all bytes to a byte[] 381 Reading an image from a file 382 Writing a byte[] to a file 383 Stream vs Writer/Reader API 384 Reading a whole file at once 384 Reading a file with a Scanner 385 Iterating over a directory and filter by file extension 385 Migrating from java.io.File to Java 7 NIO (java.nio.file.Path) 385 385 Point to a path 385 Paths relative to another path 386 Converting File from/to Path for use with libraries 386 Check if the file exists and delete it if it does 387 Write to a file via an OutputStream 387 Iterating on each file within a folder 389 Recursive folder iteration 389 390 File Read/Write Using FileInputStream/FileOutputStream 390 Reading from a binary file 391 Locking 392 Copying a file using InputStream and OutputStream 392 Reading a file using Channel and Buffer 393 Copying a file using Channel 393 Reading a file using BufferedInputStream 394 Writing a file using Channel and Buffer 394 Writing a file using PrintStream Iterate over a directory printing subdirectories in it Adding Directories Blocking or redirecting standard output / error
Accessing the contents of a ZIP file 395 Reading from an existing file 395 Creating a new file 395 Chapter 57: FileUpload to AWS 397 Introduction 397 Examples 397 397 Upload file to s3 bucket 400 400 Chapter 58: Fluent Interface 400 Remarks 400 Examples 400 403 Truth - Fluent Testing Framework 403 Fluent programming style 403 403 Chapter 59: FTP (File Transfer Protocol) 403 Syntax 409 Parameters 409 Examples 409 409 Connecting and Logging Into a FTP Server 412 412 Chapter 60: Functional Interfaces 412 Introduction 413 Examples 413 413 List of standard Java Runtime Library functional interfaces by signature 413 413 Chapter 61: Generating Java Code 413 Examples 414 Generate POJO From JSON Chapter 62: Generics Introduction Syntax Remarks Examples Creating a Generic Class Extending a generic class
Multiple type parameters 415 Declaring a Generic Method 416 The Diamond 417 Requiring multiple upper bounds (\"extends A & B\") 418 Creating a Bounded Generic Class 418 Deciding between `T`, `? super T`, and `? extends T` 420 Benefits of Generic class and interface 421 421 Stronger type checks at compile time 421 Elimination of casts 422 Enabling programmers to implement generic algorithms 422 423 Binding generic parameter to more than 1 type Note: 423 423 Instantiating a generic type 424 Workarounds 425 426 Referring to the declared generic type within its own declaration 428 Use of instanceof with Generics 428 Different ways for implementing a Generic Interface (or extending a Generic Class) Using Generics to auto-cast 430 Obtain class that satisfies generic parameter at runtime 430 430 Chapter 63: Getters and Setters Introduction 430 Examples 431 431 Adding Getters and Setters Using a setter or getter to implement a constraint 434 Why Use Getters and Setters? 434 434 Chapter 64: Hashtable Introduction 434 Examples 435 Hashtable 435 Chapter 65: HttpURLConnection Remarks
Examples 435 Get response body from a URL as a String 435 POST data 436 437 How it works 437 Delete resource 437 438 How it works 438 Check if resource exists 438 439 Explanation: 439 Example: 439 Chapter 66: Immutable Class 439 439 Introduction 439 Remarks 440 Examples 441 442 Rules to define immutable classes 442 Example without mutable refs 442 Example with mutable refs 442 What is the advantage of immutability? 443 444 Chapter 67: Immutable Objects 448 Remarks 448 Examples 448 448 Creating an immutable version of a type using defensive copying. 448 The recipe for an immutable class 448 Typical design flaws which prevent a class from being immutable 450 451 Chapter 68: Inheritance Introduction Syntax Remarks Examples Abstract Classes Static Inheritance Using 'final' to restrict inheritance and overriding
Final classes 451 Use-cases for final classes 451 Final methods 452 453 The Liskov Substitution Principle 453 Inheritance 455 Inheritance and Static Methods 455 Variable shadowing 456 Narrowing and Widening of object references 457 Programming to an interface 460 Abstract class and Interface usage: \"Is-a\" relation vs \"Has-a\" capability 463 Overriding in Inheritance 465 465 Chapter 69: InputStreams and OutputStreams 465 Syntax 465 Remarks 465 Examples 465 466 Reading InputStream into a String 467 Writing bytes to an OutputStream 467 Closing Streams 467 Copying Input Stream to Output Stream 468 Wrapping Input/Output Streams 468 470 Useful combinations 470 List of Input/Output Stream wrappers 470 470 DataInputStream Example 470 Chapter 70: Installing Java (Standard Edition) 470 471 Introduction 471 Examples 472 Setting %PATH% and %JAVA_HOME% after installing on Windows Assumptions: Setup steps Check your work Selecting an appropriate Java SE release Java release and version naming
About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: java-language It is an unofficial and free Java Language ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official Java Language. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected] https://riptutorial.com/ 1
Chapter 1: Getting started with Java Language Remarks The Java programming language is... • General-purpose: It is designed to be used for writing software in a wide variety of application domains, and lacks specialized features for any specific domain. • Class-based: Its object structure is defined in classes. Class instances always have those fields and methods specified in their class definitions (see Classes and Objects). This is in contrast to non-class-based languages such as JavaScript. • Statically-typed: the compiler checks at compile time that variable types are respected. For example, if a method expects an argument of type String, that argument must in fact be a string when the method is called. • Object-oriented: most things in a Java program are class instances, i.e. bundles of state (fields) and behavior (methods which operate on data and form the object's interface to the outside world). • Portable: It can be compiled on any platform with javac and the resultant class files can run on any platform that has a JVM. Java is intended to let application developers \"write once, run anywhere\" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java code is compiled to bytecode (the .class files) which in turn get interpreted by the Java Virtual Machine (JVM). In theory, bytecode created by one Java compiler should run the same way on any JVM, even on a different kind of computer. The JVM might (and in real-world programs will) choose to compile into native machine commands the parts of the bytecode that are executed often. This is called \"Just-in-time (JIT) compilation\". Java Editions and Versions There are three \"editions\" of Java defined by Sun / Oracle: • Java Standard Edition (SE) is the edition that is designed for general use. • Java Enterprise Edition (EE) adds a range of facilities for building \"enterprise grade\" services in Java. Java EE is covered separately. • Java Micro Edition (ME) is based on a subset of Java SE and is intended for use on small devices with limited resources. There is a separate topic on Java SE / EE / ME editions. https://riptutorial.com/ 2
Each edition has multiple versions. The Java SE versions are listed below. 3 Installing Java There is a separate topic on Installing Java (Standard Edition). Compiling and running Java programs There are separate topics on: • Compiling Java source code • Java deployment including creating JAR files • Running Java applications • The Classpath What's next? Here are links to subjects to continue learning and understanding the Java programming language. These subjects are the basics of the Java programming to get you started. • Primitive Data Types in Java • Operators in Java • Strings in Java • Basic Control Structures in Java • Classes and Objects in Java • Arrays in Java • Java code standards Testing While Java does not have any support for testing in the standard library, there are 3rd-party libraries that are designed to support testing. The two most popular unit testing libraries are: • JUnit (Official Site) • TestNG (Official Site) Other • Design patterns for Java are covered in Design Patterns. • Programming for Android is covered in Android. • Java Enterprise Edition technologies are covered in Java EE. • The Oracle JavaFX technologies are covered in JavaFX. https://riptutorial.com/
1. In Versions section the end-of-life (free) date is when Oracle will stop posting further updates of Java SE to its public download sites. Customers who need continued access to critical bug fixes and security fixes as well as general maintenance for Java SE can get long term support through Oracle Java SE Support. Versions Java SE Version Code Name End-of-life (free1) Release Date Java SE 9 (Early Access) None future 2017-07-27 Java SE 8 Spider future 2014-03-18 Java SE 7 Dolphin 2015-04-14 2011-07-28 Java SE 6 Mustang 2013-04-16 2006-12-23 Java SE 5 Tiger 2009-11-04 2004-10-04 Java SE 1.4 Merlin prior to 2009-11-04 2002-02-06 Java SE 1.3 Kestrel prior to 2009-11-04 2000-05-08 Java SE 1.2 Playground prior to 2009-11-04 1998-12-08 Java SE 1.1 None prior to 2009-11-04 1997-02-19 Java SE 1.0 Oak prior to 2009-11-04 1996-01-21 Examples Creating Your First Java Program Create a new file in your text editor or IDE named HelloWorld.java. Then paste this code block into the file and save: public class HelloWorld { public static void main(String[] args) { System.out.println(\"Hello, World!\"); } } Run live on Ideone Note: For Java to recognize this as a public class (and not throw a compile time error), the filename must be the same as the class name (HelloWorld in this example) with a .java extension. There should also be a public access modifier before it. Naming conventions recommend that Java classes begin with an uppercase character, and be in camel case format (in which the first letter of each word is capitalized). The conventions https://riptutorial.com/ 4
recommend against underscores (_) and dollar signs ($). To compile, open a terminal window and navigate to the directory of HelloWorld.java: cd /path/to/containing/folder/ Note: cd is the terminal command to change directory. Enter javac followed by the file name and extension as follows: $ javac HelloWorld.java It's fairly common to get the error 'javac' is not recognized as an internal or external command, operable program or batch file. even when you have installed the JDK and are able to run the program from IDE ex. eclipse etc. Since the path is not added to the environment by default. In case you get this on windows, to resolve, first try browsing to your javac.exe path, it's most probably in your C:\\Program Files\\Java\\jdk(version number)\\bin. Then try running it with below. $ C:\\Program Files\\Java\\jdk(version number)\\bin\\javac HelloWorld.java Previously when we were calling javac it was same as above command. Only in that case your OS knew where javac resided. So let's tell it now, this way you don't have to type the whole path every-time. We would need to add this to our PATH To edit the PATH environment variable in Windows XP/Vista/7/8/10: • Control Panel ⇒ System ⇒ Advanced system settings • Switch to \"Advanced\" tab ⇒ Environment Variables • In \"System Variables\", scroll down to select \"PATH\" ⇒ Edit You cannot undo this so be careful. First copy your existing path to notepad. Then to get the exact PATH to your javac browse manually to the folder where javac resides and click on the address bar and then copy it. It should look something like c:\\Program Files\\Java\\jdk1.8.0_xx\\bin In \"Variable value\" field, paste this IN FRONT of all the existing directories, followed by a semi- colon (;). DO NOT DELETE any existing entries. Variable name : PATH Variable value : c:\\Program Files\\Java\\jdk1.8.0_xx\\bin;[Existing Entries...] Now this should resolve. For Linux Based systems try here. Note: The javac command invokes the Java compiler. The compiler will then generate a bytecode file called HelloWorld.class which can be executed in the Java Virtual Machine (JVM). The Java programming language compiler, javac, reads source https://riptutorial.com/ 5
files written in the Java programming language and compiles them into bytecode class files. Optionally, the compiler can also process annotations found in source and class files using the Pluggable Annotation Processing API. The compiler is a command line tool but can also be invoked using the Java Compiler API. To run your program, enter java followed by the name of the class which contains the main method (HelloWorld in our example). Note how the .class is omitted: $ java HelloWorld Note: The java command runs a Java application. This will output to your console: Hello, World! You have successfully coded and built your very first Java program! Note: In order for Java commands (java, javac, etc) to be recognized, you will need to make sure: • A JDK is installed (e.g. Oracle, OpenJDK and other sources) • Your environment variables are properly set up You will need to use a compiler (javac) and an executor (java) provided by your JVM. To find out which versions you have installed, enter java -version and javac -version on the command line. The version number of your program will be printed in the terminal (e.g. 1.8.0_73). A closer look at the Hello World program The \"Hello World\" program contains a single file, which consists of a HelloWorld class definition, a main method, and a statement inside the main method. public class HelloWorld { The class keyword begins the class definition for a class named HelloWorld. Every Java application contains at least one class definition (Further information about classes). public static void main(String[] args) { This is an entry point method (defined by its name and signature of public static void main(String[])) from which the JVM can run your program. Every Java program should have one. It is: • public: meaning that the method can be called from anywhere mean from outside the program as well. See Visibility for more information on this. • static: meaning it exists and can be run by itself (at the class level without creating an https://riptutorial.com/ 6
object). • void: meaning it returns no value. Note: This is unlike C and C++ where a return code such as int is expected (Java's way is System.exit()). This main method accepts: • An array (typically called args) of Strings passed as arguments to main function (e.g. from command line arguments). Almost all of this is required for a Java entry point method. Non-required parts: • The name args is a variable name, so it can be called anything you want, although it is typically called args. • Whether its parameter type is an array (String[] args) or Varargs (String... args) does not matter because arrays can be passed into varargs. Note: A single application may have multiple classes containing an entry point (main) method. The entry point of the application is determined by the class name passed as an argument to the java command. Inside the main method, we see the following statement: System.out.println(\"Hello, World!\"); Let's break down this statement element-by-element: Element Purpose System this denotes that the subsequent expression will call upon the System class, from . the java.lang package. out . this is a \"dot operator\". Dot operators provide you access to a classes members println 1; 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 output functionality. this is another dot operator. This dot operator provides access to the println method within the out variable. this is the name of a method within the PrintStream class. This method in particular prints the contents of the parameters into the console and inserts a newline after. this parenthesis indicates that a method is being accessed (and not a field) and begins the parameters being passed into the println method. https://riptutorial.com/ 7
Element Purpose \"Hello, this is the String literal that is passed as a parameter, into the println method. World!\" The double quotation marks on each end delimit the text as a String. ) this parenthesis signifies the closure of the parameters being passed into the println method. ; this semicolon marks the end of the statement. Note: Each statement in Java must end with a semicolon (;). The method body and class body are then closed. } // end of main function scope } // end of class HelloWorld scope Here's another example demonstrating the OO paradigm. Let's model a football team with one (yes, one!) member. There can be more, but we'll discuss that when we get to arrays. First, let's define our Team class: public class Team { Member member; public Team(Member member) { // who is in this Team? this.member = member; // one 'member' is in this Team! } } Now, let's define our Member class: class Member { private String name; private String type; private int level; // note the data type here private int rank; // note the data type here as well public Member(String name, String type, int level, int rank) { this.name = name; this.type = type; this.level = level; this.rank = rank; } } Why do we use private here? Well, if someone wanted to know your name, they should ask you directly, instead of reaching into your pocket and pulling out your Social Security card. This private does something like that: it prevents outside entities from accessing your variables. You can only return private members through getter functions (shown below). After putting it all together, and adding the getters and main method as discussed before, we have: https://riptutorial.com/ 8
public class Team { Member member; public Team(Member member) { this.member = member; } // here's our main method public static void main(String[] args) { Member myMember = new Member(\"Aurieel\", \"light\", 10, 1); Team myTeam = new Team(myMember); System.out.println(myTeam.member.getName()); System.out.println(myTeam.member.getType()); System.out.println(myTeam.member.getLevel()); System.out.println(myTeam.member.getRank()); } } class Member { private String name; private String type; private int level; private int rank; public Member(String name, String type, int level, int rank) { this.name = name; this.type = type; this.level = level; this.rank = rank; } /* let's define our getter functions here */ public String getName() { // what is your name? return this.name; // my name is ... } public String getType() { // what is your type? return this.type; // my type is ... } public int getLevel() { // what is your level? return this.level; // my level is ... } public int getRank() { // what is your rank? return this.rank; // my rank is } } Output: Aurieel light 10 1 Run on ideone Once again, the main method inside the Test class is the entry point to our program. Without the main method, we cannot tell the Java Virtual Machine (JVM) from where to begin execution of the https://riptutorial.com/ 9
program. 1 - Because the HelloWorld class has little relation to the System class, it can only access public data. Read Getting started with Java Language online: https://riptutorial.com/java/topic/84/getting- started-with-java-language https://riptutorial.com/ 10
Chapter 2: 2D Graphics in Java Introduction Graphics are visual images or designs on some surface, such as a wall, canvas, screen, paper, or stone to inform, illustrate, or entertain. It includes: pictorial representation of data, as in computer- aided design and manufacture, in typesetting and the graphic arts, and in educational and recreational software. Images that are generated by a computer are called computer graphics. The Java 2D API is powerful and complex. There are multiple ways to do 2D graphics in Java. Examples Example 1: Draw and Fill a Rectangle Using Java This is an Example which print rectangle and fill color in the rectangle. https://i.stack.imgur.com/dlC5v.jpg Most methods of the Graphics class can be divided into two basic groups: 1. Draw and fill methods, enabling you to render basic shapes, text, and images 2. Attributes setting methods, which affect how that drawing and filling appears Code Example: Let us start this with a little example of drawing a rectangle and filling color in it. There we declare two classes, one class is MyPanel and other Class is Test. In class MyPanel we use drawRect( ) & fillRect( ) mathods to draw rectangle and fill Color in it. We set the color by setColor(Color.blue) method. In Second Class we Test our graphic which is Test Class we make a https://riptutorial.com/ 11
Frame and put MyPanel with p=new MyPanel() object in it.By running Test Class we see a Rectangle and a Blue Color Filled Rectangle. First Class: MyPanel import javax.swing.*; import java.awt.*; // MyPanel extends JPanel, which will eventually be placed in a JFrame public class MyPanel extends JPanel { // custom painting is performed by the paintComponent method @Override public void paintComponent(Graphics g){ // clear the previous painting super.paintComponent(g); // cast Graphics to Graphics2D Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.red); // sets Graphics2D color // draw the rectangle g2.drawRect(0,0,100,100); // drawRect(x-position, y-position, width, height) g2.setColor(Color.blue); g2.fillRect(200,0,100,100); // fill new rectangle with color blue } } Second Class: Test import javax.swing.; import java.awt.; public class Test { //the Class by which we display our rectangle JFrame f; MyPanel p; public Test(){ f = new JFrame(); // get the content area of Panel. Container c = f.getContentPane(); // set the LayoutManager c.setLayout(new BorderLayout()); p = new MyPanel(); // add MyPanel object into container c.add(p); // set the size of the JFrame f.setSize(400,400); // make the JFrame visible f.setVisible(true); // sets close behavior; EXIT_ON_CLOSE invokes System.exit(0) on closing the JFrame f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[ ]){ Test t = new Test(); } } For More Explanation about Border Layout: https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html paintComponent( ) https://riptutorial.com/ 12
• It is a main method for painting • By default, it first paints the background • After that, it performs custom painting (drawing circle, rectangles etc.) Graphic2D refers Graphic2D Class Note: The Java 2D API enables you to easily perform the following tasks: • Draw lines, rectangles and any other geometric shape. • Fill those shapes with solid colors or gradients and textures. • Draw text with options for fine control over the font and rendering process. • Draw images, optionally applying filtering operations. • Apply operations such as compositing and transforming during any of the above rendering operations. Example 2: Drawing and Filling Oval import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { @Override public void paintComponent(Graphics g){ // clear the previous painting super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.blue); g2.drawOval(0, 0, 20,20); g2.fillOval(50,50,20,20); } } g2.drawOval(int x,int y,int height, int width); This method will draw an oval at specified x and y position with given height and width. g2.fillOval(int x,int y,int height, int width); This method will fill an oval at specified x and y position with given height and width. Read 2D Graphics in Java online: https://riptutorial.com/java/topic/10127/2d-graphics-in-java https://riptutorial.com/ 13
Chapter 3: Alternative Collections Remarks This topic about Java collections from guava, apache, eclipse: Multiset, Bag, Multimap, utils function from this lib and so on. Examples Apache HashBag, Guava HashMultiset and Eclipse HashBag A Bag/ultiset stores each object in the collection together with a count of occurrences. Extra methods on the interface allow multiple copies of an object to be added or removed at once. JDK analog is HashMap<T, Integer>, when values is count of copies this key. Type Guava Apache Commons GS Collections JDK Collections Order not HashMultiset HashBag HashBag HashMap defined Sorted TreeMultiset TreeBag TreeBag TreeMap Insertion- LinkedHashMultiset - - LinkedHa order Concurrent ConcurrentHashMultiset SynchronizedBag SynchronizedBag Collection variant Concurrent - SynchronizedSortedBag SynchronizedSortedBag Collection and sorted Immutable ImmutableMultiset UnmodifiableBag UnmodifiableBag Collection collection Immutable ImmutableSortedMultiset UnmodifiableSortedBag UnmodifiableSortedBag Collection and sorted ) Examples: 1. Using SynchronizedSortedBag from Apache: // Parse text to separate words String INPUT_TEXT = \"Hello World! Hello All! Hi World!\"; // Create Multiset Bag bag = SynchronizedSortedBag.synchronizedBag(new https://riptutorial.com/ 14
TreeBag(Arrays.asList(INPUT_TEXT.split(\" \")))); // Print count words System.out.println(bag); // print [1:All!,2:Hello,1:Hi,2:World!]- in natural (alphabet) order // Print all unique words System.out.println(bag.uniqueSet()); // print [All!, Hello, Hi, World!]- in natural (alphabet) order // Print count occurrences of words System.out.println(\"Hello = \" + bag.getCount(\"Hello\")); // print 2 System.out.println(\"World = \" + bag.getCount(\"World!\")); // print 2 System.out.println(\"All = \" + bag.getCount(\"All!\")); // print 1 System.out.println(\"Hi = \" + bag.getCount(\"Hi\")); // print 1 System.out.println(\"Empty = \" + bag.getCount(\"Empty\")); // print 0 // Print count all words //print 6 System.out.println(bag.size()); // Print count unique words //print 4 System.out.println(bag.uniqueSet().size()); 2. Using TreeBag from Eclipse(GC): // Parse text to separate words String INPUT_TEXT = \"Hello World! Hello All! Hi World!\"; // Create Multiset MutableSortedBag<String> bag = TreeBag.newBag(Arrays.asList(INPUT_TEXT.split(\" \"))); // Print count words System.out.println(bag); // print [All!, Hello, Hello, Hi, World!, World!]- in natural order // Print all unique words System.out.println(bag.toSortedSet()); // print [All!, Hello, Hi, World!]- in natural order // Print count occurrences of words System.out.println(\"Hello = \" + bag.occurrencesOf(\"Hello\")); // print 2 System.out.println(\"World = \" + bag.occurrencesOf(\"World!\")); // print 2 System.out.println(\"All = \" + bag.occurrencesOf(\"All!\")); // print 1 System.out.println(\"Hi = \" + bag.occurrencesOf(\"Hi\")); // print 1 System.out.println(\"Empty = \" + bag.occurrencesOf(\"Empty\")); // print 0 // Print count all words //print 6 System.out.println(bag.size()); // Print count unique words //print 4 System.out.println(bag.toSet().size()); 3. Using LinkedHashMultiset from Guava: // Parse text to separate words String INPUT_TEXT = \"Hello World! Hello All! Hi World!\"; // Create Multiset Multiset<String> multiset = LinkedHashMultiset.create(Arrays.asList(INPUT_TEXT.split(\" \"))); https://riptutorial.com/ 15
// Print count words System.out.println(multiset); // print [Hello x 2, World! x 2, All!, Hi]- in predictable iteration order // Print all unique words System.out.println(multiset.elementSet()); // print [Hello, World!, All!, Hi] - in predictable iteration order // Print count occurrences of words System.out.println(\"Hello = \" + multiset.count(\"Hello\")); // print 2 System.out.println(\"World = \" + multiset.count(\"World!\")); // print 2 System.out.println(\"All = \" + multiset.count(\"All!\")); // print 1 System.out.println(\"Hi = \" + multiset.count(\"Hi\")); // print 1 System.out.println(\"Empty = \" + multiset.count(\"Empty\")); // print 0 // Print count all words //print 6 System.out.println(multiset.size()); // Print count unique words //print 4 System.out.println(multiset.elementSet().size()); More examples: I. Apache Collection: 1. HashBag - order not defined 2. SynchronizedBag - concurrent and order not defined 3. SynchronizedSortedBag - - concurrent and sorted order 4. TreeBag - sorted order II. GS / Eclipse Collection 5. MutableBag - order not defined 6. MutableSortedBag - sorted order III. Guava 7. HashMultiset - order not defined 8. TreeMultiset - sorted order 9. LinkedHashMultiset - insertion order 10. ConcurrentHashMultiset - concurrent and order not defined Multimap in Guava, Apache and Eclipse Collections This multimap allows duplicate key-value pairs. JDK analogs are HashMap<K, List>, HashMap<K, Set> and so on. Key's Value's Duplicate Analog key Analog value Guava Apache order order not Insertion- yes HashMap ArrayList ArrayListMultimap MultiVal defined order https://riptutorial.com/ 16
Key's Value's Duplicate Analog key Analog value Guava Apache order order not not no HashMap HashSet HashMultimap MultiVal defined defined multiVal HashMap< HashSet. not sorted no HashMap TreeSet Multimaps. MultiVal defined newMultimap( new Hash HashMap, Supplier TreeSet. <TreeSet>) Insertion- Insertion- yes LinkedHashMap ArrayList LinkedListMultimap MultiVal order order multiVal LinkedH ArrayLis Insertion- Insertion- no LinkedHashMap LinkedHashSet LinkedHashMultimap MultiVal order order multiVal LinkedHa LinkedHa sorted sorted no TreeMap TreeSet TreeMultimap MultiVal Examples using Multimap multiVal TreeMap< Set>(),T Task: Parse \"Hello World! Hello All! Hi World!\" string to separate words and print all indexes of every word using MultiMap (for example, Hello=[0, 2], World!=[1, 5] and so on) 1. MultiValueMap from Apache String INPUT_TEXT = \"Hello World! Hello All! Hi World!\"; // Parse text to words and index List<String> words = Arrays.asList(INPUT_TEXT.split(\" \")); // Create Multimap MultiMap<String, Integer> multiMap = new MultiValueMap<String, Integer>(); // Fill Multimap int i = 0; for(String word: words) { multiMap.put(word, i); i++; } // Print all words System.out.println(multiMap); // print {Hi=[4], Hello=[0, 2], World!=[1, 5], All!=[3]} - in random orders // Print all unique words System.out.println(multiMap.keySet()); // print [Hi, Hello, World!, All!] - in random orders // Print all indexes System.out.println(\"Hello = \" + multiMap.get(\"Hello\")); // print [0, 2] System.out.println(\"World = \" + multiMap.get(\"World!\")); // print [1, 5] System.out.println(\"All = \" + multiMap.get(\"All!\")); // print [3] https://riptutorial.com/ 17
System.out.println(\"Hi = \" + multiMap.get(\"Hi\")); // print [4] System.out.println(\"Empty = \" + multiMap.get(\"Empty\")); // print null // Print count unique words //print 4 System.out.println(multiMap.keySet().size()); 2. HashBiMap from GS / Eclipse Collection String[] englishWords = {\"one\", \"two\", \"three\",\"ball\",\"snow\"}; String[] russianWords = {\"jeden\", \"dwa\", \"trzy\", \"kula\", \"snieg\"}; // Create Multiset MutableBiMap<String, String> biMap = new HashBiMap(englishWords.length); // Create English-Polish dictionary int i = 0; for(String englishWord: englishWords) { biMap.put(englishWord, russianWords[i]); i++; } // Print count words System.out.println(biMap); // print {two=dwa, ball=kula, one=jeden, snow=snieg, three=trzy} - in random orders // Print all unique words System.out.println(biMap.keySet()); // print [snow, two, one, three, ball] - in random orders System.out.println(biMap.values()); // print [dwa, kula, jeden, snieg, trzy] - in random orders // Print translate by words System.out.println(\"one = \" + biMap.get(\"one\")); // print one = jeden System.out.println(\"two = \" + biMap.get(\"two\")); // print two = dwa System.out.println(\"kula = \" + biMap.inverse().get(\"kula\")); // print kula = ball System.out.println(\"snieg = \" + biMap.inverse().get(\"snieg\")); // print snieg = snow System.out.println(\"empty = \" + biMap.get(\"empty\")); // print empty = null // Print count word's pair //print 5 System.out.println(biMap.size()); 3. HashMultiMap from Guava String INPUT_TEXT = \"Hello World! Hello All! Hi World!\"; // Parse text to words and index List<String> words = Arrays.asList(INPUT_TEXT.split(\" \")); // Create Multimap Multimap<String, Integer> multiMap = HashMultimap.create(); // Fill Multimap int i = 0; for(String word: words) { multiMap.put(word, i); i++; } // Print all words System.out.println(multiMap); // print {Hi=[4], Hello=[0, 2], World!=[1, 5], All!=[3]} - keys and values in random orders // Print all unique words https://riptutorial.com/ 18
System.out.println(multiMap.keySet()); // print [Hi, Hello, World!, All!] - in random orders // Print all indexes System.out.println(\"Hello = \" + multiMap.get(\"Hello\")); // print [0, 2] System.out.println(\"World = \" + multiMap.get(\"World!\")); // print [1, 5] System.out.println(\"All = \" + multiMap.get(\"All!\")); // print [3] System.out.println(\"Hi = \" + multiMap.get(\"Hi\")); // print [4] System.out.println(\"Empty = \" + multiMap.get(\"Empty\")); // print [] // Print count all words //print 6 System.out.println(multiMap.size()); // Print count unique words //print 4 System.out.println(multiMap.keySet().size()); Nore examples: I. Apache Collection: 1. MultiValueMap 2. MultiValueMapLinked 3. MultiValueMapTree II. GS / Eclipse Collection 1. FastListMultimap 2. HashBagMultimap 3. TreeSortedSetMultimap 4. UnifiedSetMultimap III. Guava 1. HashMultiMap 2. LinkedHashMultimap 3. LinkedListMultimap 4. TreeMultimap 5. ArrayListMultimap Compare operation with collections - Create collections Compare operation with collections - Create collections 1. Create List guava gs-collections Description JDK FastList.newList() Create new ArrayList<>() Lists.newArrayList() empty list FastList.newListWith(\"1\", \"2\", \"3\") Create list Arrays.asList(\"1\", \"2\", Lists.newArrayList(\"1\", \"2\", \"3\") \"3\") https://riptutorial.com/ 19
Description JDK guava gs-collections from values Create list new ArrayList<>(100) Lists.newArrayListWithCapacity(100) FastList.newList(100) with capacity = 100 Create list new Lists.newArrayList(collection) FastList.newList(collecti from any ArrayList<>(collection) collectin Create list - Lists.newArrayList(iterable) FastList.newList(iterable from any Iterable Create list - Lists.newArrayList(iterator) - from Iterator Create list Arrays.asList(array) Lists.newArrayList(array) FastList.newListWith(arra from array Create list - - FastList.newWithNValues(1 using () -> \"1\") factory Examples: System.out.println(\"createArrayList start\"); // Create empty list List<String> emptyGuava = Lists.newArrayList(); // using guava List<String> emptyJDK = new ArrayList<>(); // using JDK MutableList<String> emptyGS = FastList.newList(); // using gs // Create list with 100 element List < String > exactly100 = Lists.newArrayListWithCapacity(100); // using guava List<String> exactly100JDK = new ArrayList<>(100); // using JDK MutableList<String> empty100GS = FastList.newList(100); // using gs // Create list with about 100 element List<String> approx100 = Lists.newArrayListWithExpectedSize(100); // using guava List<String> approx100JDK = new ArrayList<>(115); // using JDK MutableList<String> approx100GS = FastList.newList(115); // using gs // Create list with some elements List<String> withElements = Lists.newArrayList(\"alpha\", \"beta\", \"gamma\"); // using guava List<String> withElementsJDK = Arrays.asList(\"alpha\", \"beta\", \"gamma\"); // using JDK MutableList<String> withElementsGS = FastList.newListWith(\"alpha\", \"beta\", \"gamma\"); // using gs System.out.println(withElements); System.out.println(withElementsJDK); System.out.println(withElementsGS); https://riptutorial.com/ 20
// Create list from any Iterable interface (any collection) Collection<String> collection = new HashSet<>(3); collection.add(\"1\"); collection.add(\"2\"); collection.add(\"3\"); List<String> fromIterable = Lists.newArrayList(collection); // using guava List<String> fromIterableJDK = new ArrayList<>(collection); // using JDK MutableList<String> fromIterableGS = FastList.newList(collection); // using gs System.out.println(fromIterable); System.out.println(fromIterableJDK); System.out.println(fromIterableGS); /* Attention: JDK create list only from Collection, but guava and gs can create list from Iterable and Collection */ // Create list from any Iterator Iterator<String> iterator = collection.iterator(); List<String> fromIterator = Lists.newArrayList(iterator); // using guava System.out.println(fromIterator); // Create list from any array String[] array = {\"4\", \"5\", \"6\"}; List<String> fromArray = Lists.newArrayList(array); // using guava List<String> fromArrayJDK = Arrays.asList(array); // using JDK MutableList<String> fromArrayGS = FastList.newListWith(array); // using gs System.out.println(fromArray); System.out.println(fromArrayJDK); System.out.println(fromArrayGS); // Create list using fabric MutableList<String> fromFabricGS = FastList.newWithNValues(10, () -> String.valueOf(Math.random())); // using gs System.out.println(fromFabricGS); System.out.println(\"createArrayList end\"); 2 Create Set guava gs-collections Description JDK Create new HashSet<>() Sets.newHashSet() UnifiedSet.newSet() empty set UnifiedSet.newSetWith(\"a Creatre set new Sets.newHashSet(\"alpha\", \"beta\", \"gamma\") from values HashSet<>(Arrays.asList(\"alpha\", \"beta\", \"gamma\") \"beta\", \"gamma\")) Create set new HashSet<>(collection) Sets.newHashSet(collection) UnifiedSet.newSet(collec from any collections Create set - Sets.newHashSet(iterable) UnifiedSet.newSet(iterab from any Iterable Create set - Sets.newHashSet(iterator) - https://riptutorial.com/ 21
Description JDK guava gs-collections from any UnifiedSet.newSetWith(ar Iterator Create set new Sets.newHashSet(array) from Array HashSet<>(Arrays.asList(array)) Examples: System.out.println(\"createHashSet start\"); // Create empty set Set<String> emptyGuava = Sets.newHashSet(); // using guava Set<String> emptyJDK = new HashSet<>(); // using JDK Set<String> emptyGS = UnifiedSet.newSet(); // using gs // Create set with 100 element Set<String> approx100 = Sets.newHashSetWithExpectedSize(100); // using guava Set<String> approx100JDK = new HashSet<>(130); // using JDK Set<String> approx100GS = UnifiedSet.newSet(130); // using gs // Create set from some elements Set<String> withElements = Sets.newHashSet(\"alpha\", \"beta\", \"gamma\"); // using guava Set<String> withElementsJDK = new HashSet<>(Arrays.asList(\"alpha\", \"beta\", \"gamma\")); // using JDK Set<String> withElementsGS = UnifiedSet.newSetWith(\"alpha\", \"beta\", \"gamma\"); // using gs System.out.println(withElements); System.out.println(withElementsJDK); System.out.println(withElementsGS); // Create set from any Iterable interface (any collection) Collection<String> collection = new ArrayList<>(3); collection.add(\"1\"); collection.add(\"2\"); collection.add(\"3\"); Set<String> fromIterable = Sets.newHashSet(collection); // using guava Set<String> fromIterableJDK = new HashSet<>(collection); // using JDK Set<String> fromIterableGS = UnifiedSet.newSet(collection); // using gs System.out.println(fromIterable); System.out.println(fromIterableJDK); System.out.println(fromIterableGS); /* Attention: JDK create set only from Collection, but guava and gs can create set from Iterable and Collection */ // Create set from any Iterator Iterator<String> iterator = collection.iterator(); Set<String> fromIterator = Sets.newHashSet(iterator); // using guava System.out.println(fromIterator); // Create set from any array String[] array = {\"4\", \"5\", \"6\"}; Set<String> fromArray = Sets.newHashSet(array); // using guava Set<String> fromArrayJDK = new HashSet<>(Arrays.asList(array)); // using JDK Set<String> fromArrayGS = UnifiedSet.newSetWith(array); // using gs System.out.println(fromArray); System.out.println(fromArrayJDK); https://riptutorial.com/ 22
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 1 - 50
- 51 - 100
- 101 - 150
- 151 - 200
- 201 - 250
- 251 - 300
- 301 - 350
- 351 - 400
- 401 - 450
- 451 - 492
Pages: