{"id":13619968,"url":"https://github.com/yungnickyoung/Java-Cheatsheet","last_synced_at":"2025-04-14T18:32:48.101Z","repository":{"id":37273606,"uuid":"190073069","full_name":"yungnickyoung/Java-Cheatsheet","owner":"yungnickyoung","description":"Java notes cheatsheet, focusing on fundamentals and useful interview tips","archived":false,"fork":false,"pushed_at":"2021-09-11T23:23:55.000Z","size":58,"stargazers_count":197,"open_issues_count":10,"forks_count":52,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-02T01:24:21.095Z","etag":null,"topics":["cheatsheet","java"],"latest_commit_sha":null,"homepage":"https://yungnickyoung.github.io/Java-Cheatsheet/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yungnickyoung.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-06-03T19:58:05.000Z","updated_at":"2025-04-01T16:31:23.000Z","dependencies_parsed_at":"2022-08-08T19:31:01.751Z","dependency_job_id":null,"html_url":"https://github.com/yungnickyoung/Java-Cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FJava-Cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FJava-Cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FJava-Cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yungnickyoung%2FJava-Cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yungnickyoung","download_url":"https://codeload.github.com/yungnickyoung/Java-Cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248936982,"owners_count":21186136,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","java"],"created_at":"2024-08-01T21:00:50.613Z","updated_at":"2025-04-14T18:32:47.514Z","avatar_url":"https://github.com/yungnickyoung.png","language":null,"readme":"## Table of Contents\n- [Scope of Variables](#scope-of-variables)\n- [Access Modifiers and Visibility](#access-modifiers-and-visibility)\n- [Bitwise Operations](#bitwise-operations)\n  - [Width vs. Possible Values](#width-vs-possible-values)\n  - [Numerical Primitives](#numerical-primitives)\n  - [Operators](#operators)\n  - [Useful Tricks](#useful-tricks)\n- [Exceptions](#exceptions)\n- [Polymorphism](#polymorphism)\n  - [Static Polymorphism](#static-polymorphism)\n  - [Dynamic Polymorphism](#dynamic-polymorphism)\n  - [Overriding Methods](#method-overriding)\n- [Static vs Dynamic Binding](#static-vs-dynamic-binding)\n- [Interfaces](#interfaces)\n  - [Tagging Interfaces](#tagging-interfaces)\n- [Nested Classes](#nested-classes)\n- [Generics](#java-generics)\n- [Serialization](#serialization)\n- [Multithreading](#multithreading)\n  - [Thread Synchronization](#thread-synchronization)\n  - [Inter-thread Communication](#inter-thread-communication)\n- [Java Collections Framework](#java-collections-framework)\n  - [Overview](#overview)\n  - [Maps](#maps)\n  - [ArrayList vs. Vector](#arraylist-vs-vector)\n- [Common Design Patterns](#common-design-patterns)\n  - [Singleton Class](#singleton-class)\n- [`Number` Wrapper Classes](#number-wrapper-classes)\n- [Cloning Arrays](#cloning-arrays)\n- [Other Useful Keywords](#other-useful-keywords)\n  - [`final`](#final-keyword)\n  - [`abstract`](#abstract-keyword)\n  - [`synchronized`](#synchronized-keyword)\n  - [`transient`](#transient-keyword)\n  - [`throws`](#throws-keyword)\n  - [`volatile`](#volatile-keyword)\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Scope of Variables\n\n| **Local**| **Instance** | **Class/Static**  |\n|---|---|---|\n| Declared in methods, constructors, or blocks| Declared in a class, but outside a method/block | Same as instance, but with `static` keyword |\n| Created when block is entered, destroyed upon block exit | Created when an object is created (`new`). When space is allocated for a block on the heap, a slot for each instance var is created. | Created when program starts, destroyed when program ends. |\n| No access modifiers | Access modifiers OK. Visible to all methods \u0026 constructors in class. | Access modifiers OK. Visible to all methods \u0026 constructors in class. |\n| No default values. | Have default values. | Have default values. |\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Access Modifiers and Visibility\n\n| N/A | Public| Protected | Default | Private |\n|:---:|:---:|:---:|:---:|:---:|\n| Same Class                     | Y | Y | Y | Y |\n| Same Package Subclass          | Y | Y | Y | N |\n| Same Package Non-subclass      | Y | Y | Y | N |\n| Different Package Subclass     | Y | Y | N | N |\n| Different Package Non-subclass | Y | N | N | N |\n\n- Top-level Classes \u0026 interfaces cannot be `private` or `protected`\n- Methods declared `public` in superclass must be `public` in all subclasses\n- Methods declared `protected` in superclass must be `public` or `protected` in subclasses\n- Private methods are not inherited\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Bitwise Operations\n### Width vs. Possible Values\nThe number of bits used (width) determines the numbers that can be encoded: 2^n total.\n- Unsigned: 0 through 2^n - 1\n- 2's Complement: -2^(n-1) through 2^(n-1) - 1\n\n### Numerical primitives\n- **byte:** 8 bits, e.g. from -128 to 127\n- **short:** 16 bits\n- **char:** *unsigned* 16 bits\n- **int:** 32 bits\n- **long:** 64 bits\n\n### Operators\n\nFor the following examples, assume a = 60, b = 13, c= -2. Their binary 2's complement representations are below.  \na = 0011 1100  \nb = 0000 1101  \nc = 1111 1110  \n\n| Operation | Function | Example |\n|:---:|:---:|---|\n| `\u0026`   |AND                            | `a\u0026b` = `0000 1100 (12)` |\n| `\\|`  |OR                             | `a\\|b` = `0011 1101 (61)` |\n| `^`   |XOR                            | `a^b` = `0011 0001 (49)` |\n| `~`   |Complement (bitwise inversion) | `~a` = `1100 0011 (-61 in 2's complement)` |\n| `\u003c\u003c`  |Left shift                     | `a \u003c\u003c 2` = `1111 0000 (-16 in 2's complement)` |\n| `\u003e\u003e`  |Arithmetic shift right         | `c \u003e\u003e 2` = `1111 1111 (-1)` |\n| `\u003e\u003e\u003e` |Logical shift right (zero-fill)| `c \u003e\u003e\u003e 2` = `0111 1111 (127)` |\n\n### Useful Tricks\n- Note that in the following examples, x, 0, and 1 refer to a single bit, not a multi-bit integer\n  - **XOR**\n    - x ^ 0 = x\n    - x ^ 1 = ~x\n      - For a multi-bit integer n, n ^ -1 = ~n. This works because -1 in 2's complement is represented as 11111111..., so each bit gets XOR'd with 1\n    - x ^ x = 0\n  - **AND**\n    - x \u0026 0 = 0\n    - x \u0026 1 = x\n      - For a multi-bit integer n, n \u0026 -1 = n. This works because -1 in 2's complement is represented as 11111111..., so each bit gets AND'd with 1\n    - x \u0026 x = x\n  - **OR**\n    - x \\| 0 = x\n    - x \\| 1 = 1\n    - x \\| x = x\n- Swapping two values without a temporary variable\n  ```\n  // E.g. a = 2 (0b0010), b = 5 (0b0101)\n  a = a ^ b    // a = 7 (0b0111)\n  b = a ^ b    // b = 2 (0b0010)\n  a = a ^ b    // a = 5 (0b0101)\n  ```\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Exceptions\nThree types:\n1. **Checked Exceptions:** Notified by the compiler at compile-time\n2. **Unchecked Exceptions:** Runtime Exceptions\n3. **Errors:** Problems that arise beyond the control of the user and programmer, e.g. stack overflow\n\n### Exception Hierarchy\n![alt text](http://cdncontribute.geeksforgeeks.org/wp-content/uploads/Exception-in-java1.png \"Java Exceptions Hierarchy\")\n\n![alt text](http://www.benchresources.net/wp-content/uploads/2017/02/exception-hierarchy-in-java.png \"Java Exceptions Hierarchy\")\n\n### try-with-resources\nAutomatically closes the resources used, e.g.\n```java\ntry (FileReader fr = new FileReader(filepath)) {\n    // use the resource\n} catch () {\n    // handle the exception\n}\n```\n\n### User-defined Exceptions\n- Must be a child of `Throwable`\n- If checked exception, must extend `Exception`\n- If unchecked exception, must extend `RuntimeException`\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Polymorphism\n- Any object that can pass an IS-A test is polymorphic\n  - All objects are polymorphic to the `Object` class\n- Objects can **only** be accessed through reference variables\n  - A reference variable can only be of one type, and that type cannot be changed once declared. However, the reference variable can be reassigned to other objects (given that it is not `final`)\n    - The type of a reference variable determines the methods it can invoke on an object\n    - A reference variable can refer to any object of its declared type or any subtype\n    - A reference variable can be declared as a class or interface type\n    \nExample:\nGiven the following:  \n```java\npublic interface Vegetarian { ... }\npublic class Animal { ... }\npublic class Deer extends Animal implements Vegetarian { ... }\n```\nthen a Deer IS-A Animal, Vegetarian, Deer, and Object\n\nThus the following are all legal:\n```java\nDeer d = new Deer();\nAnimal a = d;\nVegetarian v = d;\nObject o = d;\n```\nAll four of these references refer to the same Deer object on the heap.\n\n### Static Polymorphism\n*Static Polymorphism* is polymorphism that is resolved at compile time. Method *overloading* is an example of static polymorphism.\n\nFor example, say we have the following code:\n```java\nint add(int a, int b) {\n    return a + b;\n}\n\nint add(int a, int b, int c) {\n    return a + b + c;\n}\n\n...\n\nint x = add(1, 2);    // Calls the first add method. x = 3\nint y = add(1, 2, 3); // Calls the second add method. y = 6\n```\n\nWhen we make a call to the `add` function, we can tell which function will be called before even running our code, based on the type and number of our arguments. And, in fact, the compiler does just this -- it resolves which method will be called at compile time, rather than waiting until runtime.\n\n### Dynamic Polymorphism\n*Dynamic Polymorphism* is polymorphism that is resolved at runtime. Method *overriding* is an example of dynamic polymorphism.\n\nFor example, consider the following code:\n```java\nclass Parent {\n    public void myMethod() {\n        System.out.printline(\"I am the parent\");\n    }\n}\n\npublic class Child extends Parent {\n    public void myMethod() {\n        System.out.printline(\"I am the child\");\n    }\n    \n    public static void main(String[] args) {\n        Parent p = new Child();\n        Child c = new Child();\n        p.myMethod(); // I am the child\n        c.myMethod(); // I am the child\n    }\n}\n```\n\nHere, we instantiate two Child objects, one using a Parent reference `p`, and the other using a Child reference `c`.\n\nWhile invoking `c.myMethod()`, the compiler sees `myMethod()` in the `Child` class at compile time, and the JVM invokes `myMethod()` in the `Child` class at run time.\n\n`myMethod()` on `p` is quite different because `p` is a Parent reference. When the compiler sees `p.myMethod()`, the compiler sees the `myMethod()` method in the `Parent` class.  Here, at compile time, the compiler used `myMethod()` in `Parent` to validate this statement. At run time, however, the JVM invokes `myMethod()` in the `Child` class.\n\nThis behavior is also referred to as **virtual method invocation**, and these methods are referred to as **virtual methods**. An overriding method is invoked at runtime, no matter the data type the reference is that was used in the source code at compile time.\n\n### Method Overriding\nRules for *overriding* methods (**NOT** overloading!)\n- The argument list must be the same\n- The return type must be the same or a subtype of the return type declared in the overriden method\n- The access level cannot be more restrictive than the overidden method's\n- Instance methods can only be overridden if they are inherited by the subclass\n- `final` methods cannot be overriden\n- A `static` method can be redeclared, but not overridden\n- If a method cannot be inherited, it cannot be overriden\n- Constructors cannot be overriden\n\n---------------------------------\n\nFor more information, see [Static vs Dynamic Binding](#static-vs-dynamic-binding).\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Static vs Dynamic Binding\nAssociation of a method call to a method body is known as **binding**. There are two types of binding:\n1. **Static Binding** (aka Early Binding): Binding resolved at compile time\n2. **Dynamic Binding** (aka Late Binding): Binding resolved at run time\n\nIn Java, static binding is used for the binding of `static`, `private`, and `final` methods. This is because these methods cannot be overridden, and thus calls to such methods are necessarily unambiguous. The type of the class these methods belong to can be determined at compile time.\n\nThis is important to know, for example, in situations where you might call a `static` method via an object (all though this is generally ill-advised), like in the example below.\n\n```java\nclass Human {\n   public static void walk() {\n       System.out.println(\"Human walks\");\n   }\n}\nclass Boy extends Human {\n   public static void walk(){\n       System.out.println(\"Boy walks\");\n   }\n   \n   public static void main(String args[]) {\n       Human b = new Boy();    // Reference is type Human, object is type Boy\n       Human h = new Human();  // Reference is type Human, object is type Human\n       b.walk();  // Human walks\n       h.walk();  // Human walks\n   }\n}\n```\n\nOn the other hand, dynamic binding is used when the compiler is not able to resolve the binding at compile time:\n\n```java\nclass Human {\n   public void walk() {\n       System.out.println(\"Human walks\");\n   }\n}\nclass Boy extends Human {\n   public void walk(){\n       System.out.println(\"Boy walks\");\n   }\n   \n   public static void main(String args[]) {\n       Human b = new Boy();    // Reference is type Human, object is type Boy\n       Human h = new Human();  // Reference is type Human, object is type Human\n       b.walk();  // Boy walks\n       h.walk();  // Human walks\n   }\n}\n```\n\nNote that, as detailed in the [Polymorphism](#polymorphism) section, the binding of *overloaded* methods is static, while the binding of *overridden* methods is dynamic.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Interfaces\nAn interface may have abstract methods, default methods, static methods, constants, and nested types. Method bodies exist only for default and static methods.\n\nAn interface contains behaviors that a class implements. All methods of an interface must be defined in the implementing class, unless the class itself is abstract.\n\nInterfaces are **similar** to classes in that:\n- They can contain any number of methods\n- Saved as InterfaceName.java\n\nInterfaces are **different** from classes in that:\n- Interfaces cannot be instantiated\n- Interfaces don't have constructors\n- All interface methods are *implicitly* abstract\n- An interface cannot have instance fields; only `static final` fields (constants)\n- An interface can extend multiple interfaces (classes can implement multiple interfaces - but they *cannot* extend multiple classes)\n\nInterfaces and their methods are implicitly `abstract`. Their methods are implicitly `public`.\n\n### Tagging Interfaces\nThe most common use of extending interfaces occurs when the parent interface doesn't have any methods.\nExample:\nThe MouseListener interface in `java.awt.event` extends `java.util.EventListener`, which is defined as follows:  \n```java\npackage java.util;\npublic interface EventListener {}\n```\nThus, an interface with no methods is a **tagging interface**.  \nThese have two basic design purposes:  \n1. Creates a common parent\n2. Adds a data type to a class. A class that implements a tagging interface becomes an interface type through polymorphism\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Nested Classes\nTypes of nested classes:\n```\n                                Nested classes\n                                      |\n                   ___________________|__________________\n                  |                                      |\n            Inner classes                      Static nested classes\n    ______________|_________________\n   |              |                 |\n Inner      Method-local        Anonymous\nclasses     inner classes     inner classes\n```\n\n**Java does NOT support multiple inheritance.**  \nThis means a class cannot inherit multiple classes.  \nHowever, a class **can** implement multiple interfaces.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Java Generics\n```java\npublic static \u003cE\u003e void printArray(E[] array) {\n    for (E element : array)\n        System.out.print(element + \" \");\n}\n...\n// Example usage:\nInteger[] intArr = {1, 2, 3};\nDouble[] doubleArr = {1.1, 2.2, 3.3};\n\nprintArray(intArr);\nprintArray(doubleArr);\n```\n\nYou can also bound the type of the Generic parameters, e.g.  \n```java\npublic static \u003cT extends Comparable\u003cT\u003e\u003e T max(T x, T y) { ... }\n```\n\nCan be applied to Generic classes as well, e.g.  \n```java\npublic class Box\u003cT\u003e {\n    private T t;\n    ....\n }\n ```\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Serialization\nSerialization allows an object to be represented as a sequence of bytes that includes the object's data as well as info about the object's type and the types of data stored in the object.\n\nAfter a serialized object has been written to a file, it can be read from the file and deserialized to recreate the object in memory.\n\nFor a class to be serialized, it must meet two conditions:\n1. It must implement the `java.io.Serializable` interface\n2. All of the fields must be serializable. If a field is not serializable, it must be marked with the `transient` keyword\n\nExample of serialization:\n```java\ntry {\n    FileOutputStream fileOut = new FileOutputStream(\"/tmp/employee.ser\");\n    ObjectOutputStream out = new ObjectOutputStream(fileOut);\n    out.writeObject(e); // Assume e is an Employee object\n    out.close();\n    fileOut.close();\n}\n```\nThe data for object `e` is now saved in `/tmp/employee.ser`.  \nNote: convention is to use `.ser` (?)\n\nExample of deserialization:\n```java\nEmployee e = null;\ntry {\n    FileInputStream fileIn = new FileInputStream(\"/tmp/employee.ser\");\n    ObjectInputStream in = new ObjectInputStream(fileIn);\n    e = (Employee)in.readObject();\n    in.close();\n    fileIn.close();\n}\n```\nThe return value of `readObject()` should be cast to the proper class.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Multithreading\nLifecycle of a thread:\n- **New:** a new thread begins in this state where it remains until the program starts the thread\n- **Runnable:** executing its task\n- **Waiting:** waiting for another thread to finish a task\n- **Timed Waiting:** waiting for a certain amount of time\n- **Terminated:** dead\n\nThread priorities range from `MIN_PRIORITY` (a constant of 1) to `MAX_PRIORITY` (a constant of 10).\n\nThere are two ways of creating a thread:\n1. Implement the `Runnable` interface\n  - If you want a class to be executed as a thread, it must implement `Runnable`. This method takes three basic steps:\n    1. Implement a `run()` method\n    2. Instantiate a `Thread` object, like so: `Thread (Runnable threadObj, String threadName)`, where threadObj is an instance of a class that implements `Runnable`, and threadName is the name given to the new thread\n    3. Start a Thread object with `start()`, which executes a class to the class's `run()` method\n2. Extend the `Thread` class\n  - This approach provides more flexibility in handling multiple threads created using available methods in the `Thread` class.\n    1. Override the `run()` method in `Thread` class\n    2. After creating the `Thread` object, start it with the `start()` method\n    \n### Thread Synchronization\nWhat if two threads try to access the same resources? For example, if multiple threads try to write to the same file at the same time, they could corrupt the file.\n\n**Monitors** allow us to make sure only one thread can access a shared resource at a time. Each object in Java has a monitor associated with it, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.\n\nUse a `synchronized` block to contain shared data.\n\n### Inter-thread Communication\nThreads can be built to exchange information using three simple methods:\n  1. `public void wait()` -- causes the current thread to wait until another thread invokes `notify()`\n  2. `public void notify()` -- wakes up a single thread that is waiting on the object's monitor\n  3. `public void notifyAll()` -- wakes up all threads that called `wait()` on the same object\n  \nAll three methods can **only** be called from within a `synchronized` context.\n\n#### Thread Deadlock\nSituation where two or more threads are blocked forever, waiting for each other. Occurs when multiple threads need the same locks, but obtain them in a different order. Obviously, we want to **avoid this!**\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Java Collections Framework\n### Overview\n![alt text](https://media.geeksforgeeks.org/wp-content/uploads/java-collection.jpg \"Java Collections Framework\")\n\n### Maps\nThere are four commonly used map implementations in Java: HashMap, TreeMap, LinkedHashMap, and Hashtable.\n\n![alt text](https://www.programcreek.com/wp-content/uploads/2009/02/MapClassHierarchy-600x354.jpg \"Map Overview\")\n\nTo summarize them:\n- **HashMap** makes no guarantees on the ordering of keys or values.\n- **TreeMap** will iterate according to the \"natural ordering\" of the keys according to their `compareTo()` method (or an externally supplied `Comparator`). Additionally, it implements the `SortedMap` interface, which contains methods that depend on this sort order. It is implemented via a red-black tree.\n- **LinkedHashMap** is a subclass of HashMap with a linked-list implementation. It will iterate in the order in which the entries were put into the map.\n- **Hashtable** is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Furthermore, in a `Hashtable`, neither the key nor value can be `null`. This is not the case with `HashMap`, which may have a single `null` key and multiple `null` values.\n  - Use [ConcurrentHashMap](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html) instead of `Hashtable` when synchronization is needed.\n\nThe figure below summaries many of these differences.\n```\n╔══════════════╦═════════════════════╦═══════════════════╦═════════════════════╗\n║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap   ║\n╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣\n║ Iteration    ║  no guarantee order ║ sorted according  ║                     ║\n║   Order      ║ will remain constant║ to the natural    ║    insertion-order  ║\n║              ║      over time      ║    ordering       ║                     ║\n╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣\n║  Get/put     ║                     ║                   ║                     ║\n║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)        ║\n║ containsKey  ║                     ║                   ║                     ║\n╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣\n║              ║                     ║   NavigableMap    ║                     ║\n║  Interfaces  ║         Map         ║       Map         ║         Map         ║\n║              ║                     ║    SortedMap      ║                     ║\n╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣\n║              ║                     ║                   ║                     ║\n║     Null     ║       allowed       ║    only values    ║       allowed       ║\n║ values/keys  ║                     ║                   ║                     ║\n╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣\n║              ║   Fail-fast behavior of an iterator cannot be guaranteed      ║\n║   Fail-fast  ║ impossible to make any hard guarantees in the presence of     ║\n║   behavior   ║           unsynchronized concurrent modification              ║\n╠══════════════╬═════════════════════╦═══════════════════╦═════════════════════╣\n║              ║                     ║                   ║                     ║\n║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked    ║\n║              ║                     ║                   ║       buckets       ║\n╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣\n║      Is      ║                                                               ║\n║ synchronized ║              implementation is not synchronized               ║\n╚══════════════╩═══════════════════════════════════════════════════════════════╝\n```\n\n### ArrayList vs. Vector\n1. **Synchronization:** `Vector` is **synchronized**, which means only one thread can access it at a time, while `ArrayList` is not synchronized, which means multiple threads could read it at the same time.\n2. **Performance:** `ArrayList` is faster, as `Vector` incurs slight overhead in acquiring the lock.\n3. **Growth:** `Vector` and `ArrayList` both grow and shrink dynamically, but `ArrayList` increments **50%** of the current array size if the number of elements exceeds its capacity, while `Vector` increments **100%**.\n4. **Traversal:** `Vector` can use both `Enumeration` and `Iterator` for traversing elements, while `ArrayList` can only use `Iterator`.\n\nGenerally, you'll want to use an `ArrayList`; in the single-threaded case it's a better choice, and in the multi-threaded case, you get better control over locking. Want to allow concurrent reads? Fine. Want to perform one synchronization for a batch of ten writes? Also fine. It does require a little more care on your end, but it's likely what you want. Also note that if you have an `ArrayList`, you can use the [`Collections.synchronizedList`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedList-java.util.List-) function to create a synchronized list, thus getting you the equivalent of a `Vector`.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Common Design Patterns\n### Singleton Class\nControls object creation, limiting # of objects to only one. Since there is only one instance, instance fields will occur once per class, similar to static fields.  \nSingletons often control access to resources like database connections or sockets.  \n```java\npublic class Singleton {\n    private static Singleton singleton = new Singleton();\n    private Singleton () {} // private constructor prevents any other class from instantiating\n    \n    public static Singleton getInstance() { return singleton; }\n    protected static void demoMethod() { System.out.println(\"demo\"); }\n}\n```\n\nExample usage:\n```java\nSingleton tmp = Singleton.getInstance();\ntmp.demoMethod();\n```\n\nSome useful posts on the variations of the Singleton pattern in Java:\n- [Singletons in Java - Baeldung](https://www.baeldung.com/java-singleton)\n- [Double-Checked Locking with Singleton](https://www.baeldung.com/java-singleton-double-checked-locking)\n- [Java Singleton Design Pattern Best Practices with Examples](https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples)\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## `Number` Wrapper Classes\n```\n                   Number\n                     |\n  ___________________|_________________\n |       |       |       |      |      |\nByte  Integer  Double  Short  Float  Long\n```\n\nConverting primitive data types into objects is called **boxing**.  \nSimilarly, the reverse operation is called **unboxing**.\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Cloning Arrays\nTwo methods of copying an array are using `System.arraycopy()` and `clone()`.  \nAn example of `System.arraycopy()`:\n```java\nint[] dest = new int[orig.length];\nSystem.arraycopy(orig, 0, dest, 0, orig.length);\n```\n\nAn example of `clone()`:\n```java\nint[] dest = orig.clone();\n```\n\nLong story short, it seems the first method may be quicker on shorter arrays, but on larger datasets they have similar performance. Furthermore, `clone()` is much more compact and easy to read. Thus, tend to prefer `clone()`.\n\nFor more information, see [this article](https://www.javaspecialists.eu/archive/Issue124.html).\n\n\u003csup\u003e\u003csub\u003e[▲ TOP](#table-of-contents)\u003c/sub\u003e\u003c/sup\u003e\n## Other Useful Keywords\n### `final` Keyword\nCan be applied to variables, methods, and classes.\n#### Variables\n- Can be initialized only once\n- A reference variable declared `final` can never be reassigned to refer to a different object. However, the data within the object can be changed (unless it is also `final`). In other words, the state of the object can be changed, but not the reference.\n\n#### Methods\n- Cannot be overriden by subclasses\n\n#### Classes\n- Cannot be subclassed. Thus, no features can be inherited.\n\n### `abstract` Keyword\nCan be applied to both methods and classes.\n#### Methods\n- Have no implementation. Implementation is provided by subclass.\n- Can never be `final` or `strict`\n- Any class that extends an `abstract` class must implement **all** of its `abstract` methods, unless the subclass is also `abstract`\n\n#### Classes\n- Can never be instantiated\n- Cannot be both `abstract` and `final` (there is an obvious conflict of purpose between those two keywords)\n- If a class contains `abstract` methods, the class **must** be declared as `abstract`\n- An `abstract` class may have `abstract` as well as other methods\n- An `abstract` class doesn't have to have `abstract` methods.\n\n### `synchronized` Keyword\nIndicates a block of code that can only be executed by one thread at a time. Can be applied to methods or independent blocks.\n\nA synchronized block can specify an object to use as a lock. This object is referred to as a \"monitor\" object.\n\nSee [this post](http://tutorials.jenkov.com/java-concurrency/synchronized.html) or the [accompanying video](https://youtu.be/eKWjfZ-TUdo) for more information.\n\n### `transient` Keyword\nAn instance variable marked as `transient` tells the JVM to skip that variable when serializing the object containing it\n\n### `throws` Keyword\nUsed to postpone the handling of a checked (compile-time) exception.\nE.g.\n```java\nimport java.io.*;\npublic class MyClass {\n    public void deposit(double amount) throws RemoteException {\n        // Method implementation ...\n        throw new RemoteException();\n    }\n    ...\n}\n```\n\n### `volatile` Keyword\nTells the JVM that a thread accessing the variable must merge its own private copy of the variable with the master copy in memory. In technical terms, any variable marked as volatile will only ever be read from \u0026 written to main memory, bypassing any CPU caching.\n\nIf a variable is not declared `volatile`, we have no guarantee about when exactly the master copy will be accessed or modified. This can subtly cause problems in multithreaded applications that may be difficult to debug. \n\n`volatile` can only be used on instance variables.\n\nSee [this fantastic post](http://tutorials.jenkov.com/java-concurrency/volatile.html) or the [accompanying video](https://www.youtube.com/watch?v=nhYIEqt-jvY\u0026ab_channel=JakobJenkov) for more information.\n\n","funding_links":[],"categories":["Others"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyungnickyoung%2FJava-Cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyungnickyoung%2FJava-Cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyungnickyoung%2FJava-Cheatsheet/lists"}