{"id":22513435,"url":"https://github.com/emahtab/java-refresher","last_synced_at":"2025-08-19T09:06:06.960Z","repository":{"id":79525562,"uuid":"247438536","full_name":"eMahtab/java-refresher","owner":"eMahtab","description":"Java Refresher","archived":false,"fork":false,"pushed_at":"2025-02-11T16:03:16.000Z","size":71,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-02-11T16:37:57.387Z","etag":null,"topics":["java","programming","refresher"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-03-15T09:46:04.000Z","updated_at":"2025-02-11T16:03:20.000Z","dependencies_parsed_at":"2024-10-31T17:22:18.823Z","dependency_job_id":"0077f986-e22a-4023-b6d9-df27c4cd8f23","html_url":"https://github.com/eMahtab/java-refresher","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/eMahtab%2Fjava-refresher","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fjava-refresher/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fjava-refresher/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fjava-refresher/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/java-refresher/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245950637,"owners_count":20699102,"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":["java","programming","refresher"],"created_at":"2024-12-07T03:12:20.779Z","updated_at":"2025-03-28T01:23:47.903Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Java Refresher\n\n\n## Empty array\n\n`int[] emptyArray = new int[0];` , but this won't even compile `int[] compileError = new int[];`\n\n## static and instance blocks\n\n**Execution Order:**\n\n1.Static block(s) → **Executed only once** when the class is loaded (before objects are created).\n\n2.Instance block(s) → Executed before the constructor **when an object is created.**\n\n3.Constructor(s) → **Executed after instance blocks when an object is created.**\n\n```java\nclass Main {\n    \n    static {\n        System.out.println(\"1. Static Block\");\n    }\n\n    {\n        System.out.println(\"2. Instance Block\");\n    }\n\n    Main() {\n        System.out.println(\"3. Constructor\");\n    }\n\n    public static void main(String[] args) {\n        System.out.println(\"main Method Starts\");\n        Main obj1 = new Main();\n        Main obj2 = new Main();\n    }\n}\n```\n\n```\n1. Static Block\nmain Method Starts\n2. Instance Block\n3. Constructor\n2. Instance Block\n3. Constructor\n```\n## static and instance blocks execution order in inheritance\n\n**Execution Order in Inheritance:**\n\nWhen a subclass B extends a superclass A, the order of execution is:\n\n1. Static blocks of superclass (A)\n2. Static blocks of subclass (B)\n3. Instance blocks of superclass (A)\n4. Constructor of superclass (A)\n5. Instance blocks of subclass (B)\n6. Constructor of subclass (B)\n\n```java\nclass A {\n    static {\n        System.out.println(\"Static Block of A\");\n    }\n    {\n        System.out.println(\"Instance Block of A\");\n    }\n\n    A() {\n        System.out.println(\"Constructor of A\");\n    }\n}\n\nclass B extends A {\n\n    static {\n        System.out.println(\"Static Block of B\");\n    }\n    {\n        System.out.println(\"Instance Block of B\");\n    }\n\n    B() {\n        System.out.println(\"Constructor of B\");\n    }\n}\n\nclass Main {\n    public static void main(String[] args) {\n        System.out.println(\"main Method Starts\");\n\n        A a = new A();\n        System.out.println(\"----------------------\");\n        B obj1 = new B();\n        System.out.println(\"----------------------\");\n        B obj2 = new B();\n    }\n}\n```\n\n```\nmain Method Starts\nStatic Block of A\nInstance Block of A\nConstructor of A\n----------------------\nStatic Block of B\nInstance Block of A\nConstructor of A\nInstance Block of B\nConstructor of B\n----------------------\nInstance Block of A\nConstructor of A\nInstance Block of B\nConstructor of B\n```\n\n## final class \n\nMarking a class as final in Java means that it cannot be subclassed (extended). This is done for several reasons e.g. Ensuring that the class's behavior remains as designed.\n\njava.lang.String, java.lang.Integer, java.lang.Double, java.lang.Boolean (All wrapper classes) etc. are final classes in JDK.\n\n## == and equals(), comparing references vs comparing content\n```java\npublic class Main {\n    public static void main(String[] args) {\n       String s1 = \"Hello\";\n       String s2 = new String(\"Hello\");\n       String s3 = s1; \n       System.out.println(s1 == s2); // false\n       System.out.println(s1.equals(s2)); // true\n       System.out.println(s1.equals(s3)); // true\n       System.out.println(s1 == s3); // true\n    }\n}\n```\n\n## Immutable Collections\n```java\nimport java.util.List;\n\npublic class Main {\n    public static void main(String[] args) {\n        List\u003cString\u003e immutableList = List.of(\"banana\", \"apple\", \"cherry\");\n\n        // Trying to sort the immutable list, will throw java.lang.UnsupportedOperationException\n        // Collections.sort(immutableList);\n\n        // Trying to add element to a immutable list, , will throw java.lang.UnsupportedOperationException\n        // immutableList.add(\"orange\");\n    }\n}\n```\n\n## Returning empty Immutbale collections when there is no data\nImmutable empty collections are often returned from methods when there is no data, rather than returning null, its better to return empty immutable collection.\nReturning empty collection is safe way to guard against NullPointerException, any by returning immutable empty collection we can enfore that the collection can not be modified.\n\n```java\nCollections.emptyList() or Collections.\u003cString\u003eemptyList()\nCollections.emptySet() or Collections.\u003cInteger\u003eemptySet() \nCollections.emptyMap() or Collections.\u003cString,Integer\u003eemptyMap()\n```\n\n## Collectors.partitioningBy(Predicate)\n\nCollectors.partitioningBy() is a collector in Java used to partition elements of a stream into two groups based on a given predicate. The result is a Map\u003cBoolean, List\u003cT\u003e\u003e where:\n\ntrue key contains elements that satisfy the predicate.\n\nfalse key contains elements that do not satisfy the predicate.\n\n```java\nimport java.util.Map;\nimport java.util.stream.Collectors;\nimport java.util.List;\nimport java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        List\u003cInteger\u003e numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n\n        // Partition numbers into even and odd\n        Map\u003cBoolean, List\u003cInteger\u003e\u003e partitioned = numbers.stream()\n                .collect(Collectors.partitioningBy(n -\u003e n % 2 == 0));\n\n        System.out.println(\"Even numbers: \" + partitioned.get(true));\n        System.out.println(\"Odd numbers: \" + partitioned.get(false));\n    }\n}\n```\n\n\n## Default implementation of equals() method in Object class\n\nThe default implementation of equals method is, two objects are same only if both refer to same instance.\n\nThe default implementation is the most discriminating possible equivalence relation on objects, most of the time you would want two objects having exact same values of some properties to return true, even if they are two distinct instances.\n\n```java\n\npublic boolean equals(Object obj) {\n    return (this == obj);\n}\n```\n## Implementation of equals() method in String class\nReturns true if the given object represents a String equivalent to this string, false otherwise.\n```java\npublic boolean equals(Object anObject) {\n        if (this == anObject) {\n            return true;\n        }\n        return (anObject instanceof String aString)\n                \u0026\u0026 (!COMPACT_STRINGS || this.coder == aString.coder)\n                \u0026\u0026 StringLatin1.equals(value, aString.value);\n}\n```\n\n## Implementation of equals() method in Integer class\nCompares this object to the specified object.  The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.\n\n```java\npublic boolean equals(Object obj) {\n        if (obj instanceof Integer) {\n            return value == ((Integer)obj).intValue();\n        }\n        return false;\n}\n```\n\n## Default implementation of hashCode() method in Object class\n\n**The exact algorithm depends on the JVM implementation**, the returned hash code is typically based on the memory address of the object.\n\n**The default hashCode() implementation, does not guarantee different hash codes for two different objects.**\n\nCalling hashCode() on the same object multiple times must return same hash code.\n\n## equals() and hashCode() contract\n\nIf for two objects equals() method returns true, means they match, then calling hashcode() on those two objects should return exact same value.\n\n## Instant\n```java\nimport java.time.Instant;\npublic class Test {\n\tpublic static void main(String[] args) {\n\t\tInstant now = Instant.now();\n\t\tSystem.out.println(\"Now : \"+now); // Now : 2024-11-08T16:10:02.367923Z\n\t\tlong millis = now.toEpochMilli();\n\t\tSystem.out.println(\"Milis from Epoch :\"+millis);\n\t\t// Milis from Epoch :1731082202367\n\t}\n}\n```\n## ArrayDeque Vs. LinkedList\n\n`java.util.ArrayDeque` doesn't allow null while `java.util.LinkedList` does allow adding null.\n\n## Cloning a 1D/2D array of primitives with .clone()\n```java\n    int[] arr1 = {5, 6, 3, 2, 10};\n    int[] arr2 =  arr1.clone();\n    System.out.println(\"Arr 2 : \" + Arrays.toString(arr2)); // {5, 6, 3, 2, 10}\n    int[][] arr3 = {{1, 2, 3}, {4, 5, 6}};\n    int[][] arr4 = arr3.clone();\n    for(int[] nums : arr4)\n    System.out.println(\"Arr 4 : \" + Arrays.toString(nums));  // {{1, 2, 3}, {4, 5, 6}}\n```\n## HashMap does not guarantee any particular order of keys\n```java\nimport java.util.*;\n\npublic class Test {\n    public static void main(String[] args) {\n       Map\u003cInteger,String\u003e map = new HashMap\u003c\u003e();\n       map.put(1, \"one\"); map.put(3, \"three\");\n       map.put(2, \"two\"); map.put(5, \"five\");\n       map.put(6, \"six\"); map.put(4,  \"four\");\n       for(int key : map.keySet())\n    \t   System.out.print(key+\" , \"); // the output order can't be guaranteed\n       // 1 , 2 , 3 , 4 , 5 , 6 , \n    }\n}\n```\n# Iterating over a map with Java 8 forEach\n```java\nimport java.util.Map;\n\npublic class Test {\n\tpublic static void main(String[] args) {\n        Map\u003cString,Integer\u003e map = Map.of(\"one\", 1, \"two\", 2, \"three\", 3);\n        map.forEach((k,v) -\u003e System.out.println(k + \"=\" + v));\n        // two=2\n        // three=3\n        // one=1\n\t}\n}\n```\n\n## Use LinkedHashMap if you want to maintain insertion order\n```java\nimport java.util.*;\n\npublic class Test {\n    public static void main(String[] args) {\n       Map\u003cInteger,String\u003e map = new LinkedHashMap\u003c\u003e();\n       map.put(1, \"one\"); map.put(3, \"three\");\n       map.put(2, \"two\"); map.put(5, \"five\");\n       map.put(6, \"six\"); map.put(4,  \"four\");\n       for(int key : map.keySet())\n    \t   System.out.print(key+\" , \");\n       // 1 , 3 , 2 , 5 , 6 , 4 ,\n    }\n}\n```\n## Removing a key from Map while iterating over the map, results in ConcurrentModificationException\n```java\nimport java.util.*;\n\nclass Main {\n   public static void main(String[] args) {\n      Map\u003cInteger, List\u003cInteger\u003e\u003e map = new HashMap\u003c\u003e();\n      map.put(9, Arrays.asList(1, 4));\n      map.put(2, new ArrayList\u003cInteger\u003e());\n      for (int key : map.keySet()) {\n         if (map.get(key).size() == 0) {\n            map.remove(key);\n         }\n      }\n   }\n}\n```\n\n```\nException in thread \"main\" java.util.ConcurrentModificationException\n\tat java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1606)\n\tat java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1629)\n\tat Test/net.mahtabalam.Main.main(Main.java:15)\n```\n\n## To remove keys while iterating over map keys, use iterator.remove()\n```java\nimport java.util.*;\n\nclass Main {\n   public static void main(String[] args) {\n      Map\u003cInteger, List\u003cInteger\u003e\u003e map = new HashMap\u003c\u003e();\n      map.put(9, Arrays.asList(1, 4));\n      map.put(2, new ArrayList\u003cInteger\u003e());\n      Iterator\u003cInteger\u003e iterator =  map.keySet().iterator();\n      while (iterator.hasNext()) {\n    \t Integer key = iterator.next();\n         if (map.get(key).size() == 0) {\n            iterator.remove();\n         }\n      }\n      System.out.println(map); // {9=[1, 4]}\n   }\n}\n```\n\n\n## ConcurrentHashMap : For higher throughput, doesn't lock entire map while performing a write\n\n```\nRead operations are guaranteed not to be blocked or block a key.\nWrite operations are blocked and block other writes at the map Entry level.\nThese two ideas are important in environments where we want to achieve high throughput and eventual consistency.\n\nHashTable and Collections.synchronizedMap collections also implement concurrency for reads and writes.\nHowever, they are less efficient because they lock the entire collection\ninstead of locking just the Entry at which the thread is writing.\n\nOn the other hand, the ConcurrentHashMap class locks at a map Entry level.\nThus, other threads are not blocked from writing on other map keys.\nTherefore, to achieve high throughput, ConcurrentHashMap in multi-thread environments is a better option\nwhen compared to HashTable and synchronizedMap collections.\n```\n\n## Collections.reverse() - works fine with list of lists 👍\n\n```\nlist = [[1,2], [3], [4,5] , [6]]\nCollections.reverse(list) \n// [[6], [4,5], [3], [1,2]]\n``` \n\n## Convert an int to binary string\n```\nInteger.toBinaryString(2) =\u003e 10\nInteger.toBinaryString(-2) =\u003e 11111111111111111111111111111110\n```\n\n## Bitwise OR(|) and AND(\u0026) operation\n```\nint num5 = 5;\nint num8 = 8;\nint or = 5 | 8;\nint and = 5 \u0026 8;\nSystem.out.println(\"5 | 8 =\" + or);  // 13\nSystem.out.println(\"5 \u0026 8 =\" + and); // 0\n```\n\n## String substring() method\n```\nString s = \"a\";\nSystem.out.println(s.substring(1));   =\u003e \"\" (empty string)\nSystem.out.println(s.substring(2));   =\u003e StringIndexOutOfBoundsException  \n```\n\n## Concat String and char\n```\nString s = \"a\" + \"hello\".charAt(1);\nSystem.out.println(s); //ae\n```\n\n## StringBuilder apppend\n```\nStringBuilder sb = new StringBuilder();\nsb.append('a');\nsb.append(1);\nsb.append(\"ABC\");\nSystem.out.println(sb); // a1ABC\n```\n\n## List add(int index, T element)\n```\nList\u003cInteger\u003e list = new ArrayList\u003c\u003e();\nlist.add(1); list.add(2); list.add(3);\nlist.add(1, 5);\nSystem.out.println(list);  // [1, 5, 2, 3]\n```\n\n## List set(int index, T element)\n```\nList\u003cInteger\u003e list = new ArrayList\u003c\u003e();\nlist.add(1); list.add(2); list.add(3);\nlist.set(1, 5);\nSystem.out.println(list);  // [1, 5, 3]\n```\n\n## Set contains()\n```java\n\nimport java.util.*;\nclass Main {\n  class Employee {\n    int id;\n    Employee(int id){\n      this.id = id;\n    }\n  }\n  public static void main(String[] args) {\n    new Main().check();\n  }\n\n  private void check() {\n    Employee e1 = new Employee(1);\n    Employee e2 = new Employee(1);\n    Set\u003cEmployee\u003e set = new HashSet\u003c\u003e();\n    set.add(e1);\n    System.out.println(set.contains(e2)); // false\n    set.add(e2);\n    Employee e3 = e2;\n    System.out.println(set.contains(e3)); // true\n  }\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fjava-refresher","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fjava-refresher","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fjava-refresher/lists"}