{"id":17514074,"url":"https://github.com/senocak/cracking-the-java-coding-interview","last_synced_at":"2025-04-11T05:38:04.924Z","repository":{"id":252451100,"uuid":"836695767","full_name":"senocak/Cracking-the-Java-Coding-Interview","owner":"senocak","description":"Cracking the Java Coding Interview","archived":false,"fork":false,"pushed_at":"2025-04-09T11:43:06.000Z","size":239,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-09T12:34:03.414Z","etag":null,"topics":["java","jdk","jdk11","jdk17","jdk21","jdk23","jdk8","jvm"],"latest_commit_sha":null,"homepage":"https://www.youtube.com/watch?v=kXWl_Tv5wiU\u0026list=PLX8CzqL3ArzX0zXLKycnQslZaF6viV0oQ","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/senocak.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":"2024-08-01T11:17:00.000Z","updated_at":"2025-04-09T11:43:10.000Z","dependencies_parsed_at":"2024-09-11T13:14:20.993Z","dependency_job_id":"4e430d63-9b6d-4b68-8de8-77f5acfdf473","html_url":"https://github.com/senocak/Cracking-the-Java-Coding-Interview","commit_stats":{"total_commits":201,"total_committers":2,"mean_commits":100.5,"dds":0.00497512437810943,"last_synced_commit":"7365311670379009a719c31018752c5b3de71a28"},"previous_names":["senocak/cracking-the-java-coding-interview"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/senocak%2FCracking-the-Java-Coding-Interview","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/senocak%2FCracking-the-Java-Coding-Interview/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/senocak%2FCracking-the-Java-Coding-Interview/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/senocak%2FCracking-the-Java-Coding-Interview/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/senocak","download_url":"https://codeload.github.com/senocak/Cracking-the-Java-Coding-Interview/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248350200,"owners_count":21089222,"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","jdk","jdk11","jdk17","jdk21","jdk23","jdk8","jvm"],"created_at":"2024-10-20T07:07:51.428Z","updated_at":"2025-04-11T05:38:04.893Z","avatar_url":"https://github.com/senocak.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Cracking the Java Coding Interview\n\n## 1. What is Java?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA programming language\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLesser Short Answer\u003c/summary\u003e\n\nAn object-oriented programming language with some lists of functional programming in it and actually more and more. Object-oriented programming means four things `abstraction`, `encapsulation`, `inheritance` and `polymorphism` that Java supports all that. One restriction though, it does not support multiple linear returns meaning that one class can only extend one other class. And I have a last one for you, Java is a statically typed language meaning that the type of any variable you create or receive is known ad compiled time even if you define the type with vowel the compiler will guess the type of this variable for you\n\u003c/details\u003e\n\n## 2. What is the Object class in Java?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n  \nThe super class of every class you can create\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nWhen you create a class you can explicitly extend another class with the `extends` keyword. You can even declare that you extend the object class, this is fine it's dumb because you don't need it but it's legal.\n  \nRemember a class can only extend one class in Java, multiple linear returns is not allowed. If you do not declare that your class extends anything, which is fine, then the compiler will make your class extend the object class for you so in the end every class in Java extends the Object class\n\u003c/details\u003e\n\n## 3. Can you cite methods from the Object class?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`toString()`, `equals()` and `hashCode()`\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are more. `getClass()` gives you the class of the subject `wait()`, `notify()` and `notifyAll()` these are used in concrete programming and never call these methods unless you really know what you're doing here. `finalize()`, that one you should not override it anymore because it is deprecated and whatever you put in this method is most of the time buggy, most of the time, and the last one is `clone()` same stay away from this method so in a nutshell `toString()`, `equals()` and `hashCode()` these are the most used ones\n\u003c/details\u003e\n\n## 4. What are the differences between String and array of chars (char[])?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nString is an object with many useful methods, An array only has methods from object and they are not very useful\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nString of character is non-modifiable in Java, once you've created one you cannot modify it. The size of an array is fixed, once created you cannot add elements to it, but you can replace one element by another.\n\n- String is a class with useful methods that chat[] has not\n- String is non-modifiable\n\nHow can you compare string? Just use their `equals()` method, trying to compare an array with its `equals()` method doesn't do what you would expect. You need to use `equals()` from the arrays factory class(`Arrays.equals()`) and the same goes for the `toString()` method, you need to use `toString()` from the same arrays factory class(`Arrays.toString()`) to properly print an array.\n\nOne last word, you can create a string a prominent array of chars by calling `new String()` and passing this array as an argument\n\n```java\nchar[] letters = {'h', 'e', 'l', 'l', 'o'};\nString hello = new String(letters);\n```\n\n\u003c/details\u003e\n\n## 5. How do you sum the elements of an array?\n\u003cdetails\u003e\n  \u003csummary\u003eAnswer\u003c/summary\u003e\n\nTwo solutions are, a dumb one \u0026 old-fashioned that everyone knows, and a great one\n\n- The first one iterate over the array, add the elements to the sum variable, don't forget to set it to zero at the start and you're done and the result is 10.\n```java\nint[] ints = {0, 1, 2, 3, 4};\nint sum = 0;\nfor (int element: ints) {\n    sum += element;\n}\nSystem.out.println(\"sum = \" + sum); // sum = 10\n``` \n- The second one, make your stream from your array and just call `sum()`, of course the result is the same and by the way you can also call `min()`, `max()` and `average()` on the stream. Yes this is the one I prefer, it's simpler cleaner and more readable\n```java\nint[] ints = {0, 1, 2, 3, 4};\nint sum = Arrays.stream(ints).sum();\nSystem.out.println(\"sum = \" + sum); // sum = 10\ndouble average = Arrays.stream(ints).average().orElseThrow();\nSystem.out.println(\"average = \" + average); // average = 2.0\n``` \n\u003c/details\u003e\n\n## 6. What is the JVM?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nJava Virtual Machine\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLesser Short Answer\u003c/summary\u003e\n\nThe piece of software that can run your Java code. The JVM does many things for you besides running your application among many other things. It handles the memory of your application with an element called the `Garbage Collector` or `GC`. It optimizes the code that you're running with another element called the `Just In Time` compiler or `JIT` and it handles the security of your application making sure that no undesired code can sneak in and be executed on your behalf.\n\nOne last word, if someone talks to you about HotSpot that's the name of the open sourced jvm developed by defaults at the Open JDK.\n\u003c/details\u003e\n\n## 7. How can you sort an array?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a method for that called `Arrays.sort(tab)` that's all. Pass your retreat and that's it.\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nWhen you need to sort something, forget about writing a sort algorithm yourself. What about the best sorting algorithm?, that's actually a tough question but you don't need to worry about that because a `Arrays.sort(...)` does the job for you. Now if you really want to shine during an interview, you can cite three algorithms, `QuickSort`, `HeapSort` and `TimSort`. The one used in a `Arrays.sort(...)` is called `Dual Pivot Quicksort`.\n\nOne last word, never cite `BubbleSort` unless you want to say that it's a terrible algorithm\n\u003c/details\u003e\n\n## 8. What is the main characteristic of the String class?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThis class(String) is non-modifiable\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere is no way to modify an instance of the string class that one it has been created so if you call `\"string\".toUpperCase()`, it does not change a string, it creates a new strings that holds the results. If you really want a string of characters that you can modify then you can use a specific class called `StringBuilder`. It's not a string it actually wraps an array of chars or bytes you can modify the content of this array and you can create a string from it by calling `toString()` on it.\n\nOne last word, you use a plus(`+`) to concatenate strings, forget about using the old string builder pattern, it's useless well most of the time\n\u003c/details\u003e\n\n## 9. What is the difference between equally call(==) and equals()?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nEqually called(==) compare the references and equals() calls a method\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIf you compare strings with equal equal(==), you may get the answer false even if the strings have the same value. In a nutshell equal equal(==) is good to compare things that are not objects, int, long and alike.\n\nYou should never compare floats or double with equal equal(==) when you need to compare floats or double, what you should be doing is compute the absolute value of their differences and check if it is lesser than a very small value.\n\n```java\nfloat d1, d2;\nif(Math.abs(d1 - d2) \u003c 1e-7) {\n    // d1 and d2 are equals\n}\n```\n\nOne last thing everything is a reference in Java so most of the time calling equal equal(==)  on object is wrong\n\u003c/details\u003e\n\n## 10. What is the relationship between equals() and hashCode()\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nJava specification says, if two objects are equals then they should have the same `hashCode()`\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIt means that when you override `equals()` then you should always override `hashCode()` as well. The Java spec says two objects that are equals must have the same hash code but the contrary is not true, you can have two objects with the same hash code but that are different.\n\nOne last thing, always use your IDE to write these methods, first your IDE, do not forget to override both methods and second it will give you a better implementation than the one you will write well most of the time\n\u003c/details\u003e\n\n## 11. How can you duplicate an array?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou have two solutions `Arrays.copyOf()` and `System.arrayCopy()`\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nYou have a clone method on Arrays `array.clone()` internally, it returns an object that is cast to the right type so performance wise it's not ideal. Both `Arrays.copyOf()` and `System.arrayCopy()` need a destination array in which they copy your source array. `Arrays.copyOf()` of can truncate your source array if it's bigger than the destination array or compact it if it's smaller. `System.arrayCopy()` has a richer API. It can copy a portion of your source array in the destination array.\n\nOne last word, `Arrays.copyOf()` calls `System.arrayCopy()` internally, so you can use the one you prefer\n\u003c/details\u003e\n\n## 12. How can you reverse a String?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nWrap it in a `StringBuilder` and call `reverse()`\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe String.class is non-modifiable, so you cannot change what the string is. All you can do is create another string and that is the reverse of the first one, looping over the letters of your string to reverse it is actually what the reverse method from `StringBuilder` is doing so don't bother re-inventing the wheel, it's there for you to use it. StringBuilder is a modifiable class so the letters are reversed internally.\n  \nOne last word, to get the reversed string, you just need to call `toString()` on your StringBuilder object\n\u003c/details\u003e\n\n## 13. What is the functional interface?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn interface with only one abstract method\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nFunctional interfaces can be implemented with `Lambda Expressions`. Java is a statically typed language so all your variables have a type and all these types are known at compile time. The type of a Lambda is always a functional interface, no exception. A functional interface can contain any number of default all static methods, it can have any method from the object class as abstract methods and only one abstract method that is the one that your Lambda has to implement.\n\nOne last word, you can add the `@FunctionalInterface` annotation on your interface, the compiler will then tell you if you got it right or not\n\u003c/details\u003e\n\n## 14. What is the difference between overriding and overloading?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`overriding` has to do with inheritance, `overloading` does not\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`Overloading` is the same method with different parameters, `overriding` is the redefinition of a method from a superclass in a subclass. When your code calls a method with different overloads, the compiler decides which method to call so overloading is result at compile time. This is called early binding. Overriding is not, the compiler cannot resolve the call, it is result at runtime this is called late binding.\n\nOne last word, you can prevent a method from being overridden by declaring it final with the `final` keyword, you cannot prevent the method from having different overloads\n\u003c/details\u003e\n\n## 15. What is a Map?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn object that maps keys to values\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nMap is an interface from the `collections` framework, it's canonical implementation is a `HashMap`. You cannot have duplicates among the keys of a map and a given key can map a single value. There is no concept of multi-map in the `collections` framework where a key can be bound to several value, but you can map a key to a list of values. Only use non-modifiable objects for your keys, small strings, a few characters are enough or longs prefer them over integers even for small values.\n\nOne last word, the `HashMap` class supports null keys and null values but please don't do that, it will put you in trouble\n\u003c/details\u003e\n\n## 16. What is an ArrayList?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn implementation of the List interface backed by an array\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nArrayList is sometimes called the dynamic array because when the internal array of an ArrayList becomes full, it is transparently copied in a larger array. Be careful though because this array can only grow, it never shrinks so when all the ArrayList can become really fat in your application and eat up a lot of memory.\n\nOne last thing, ArrayList is your best choice for List implementation, forget about LinkedList. LinkedLists are good for Stacks, we'll talk more on that another time\n\u003c/details\u003e\n\n## 17. What is Finally? \u0026 Explain Finally?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`Finally` marks a block after a try block that is always executed when the try block exits\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nAlways means even if there is a return, a continue, a break or an exception that causes the try block to exit. The finally block is the key tool to properly clean up resources that are not `Auto Closable`, your best choice to open an auto closable resource is the try-with-resources statement because it takes care of the closing of this resource for you. Resources that are not Auto-Closable should be released in a finally block that's the case for `ReentrantLock` for instance or for `Semaphores`.\n\n```java\nclass Scratch {\n    public static void main(String[] args) {\n        System.out.println(\"average = \" + age());\n    }\n    private static int age() {\n        try {\n            return 1;\n        } finally {\n            return 2;\n        }\n    }\n}\n// average = 2\n```\n\nOne last word, in case of a return in the try block the finally block is evaluated after the return\n\u003c/details\u003e\n\n## 18. How to make a class Immutable?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nUse `records` if you can\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIf you cannot use record, make all the fields of this class `final` and don't forget to make this class `final` also because if you don't someone could add some mutable state to this class using inner returns and pass it around using polymorphism. Do not forget to make defensive copies of the modifiable objects you get as arguments in your constructor like Lists, Maps and the alike and the same for your accessors make sure they do not leak references to your internal state that could be modifiable, use a defensive copy where you need it.\n\nOne last thing, String, Integer, Long and all the wrapper classes of the jdk are non-modifiable, you can check them to see how they work\n\u003c/details\u003e\n\n## 19. What is the difference between String and StringBuffer and StringBuilder?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`String` is non-modifiable, `StringBuilder` is modifiable and `StringBuffer` is thread safe\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`StringBuffer` is rarely used. `StringBuilder` is nice for certain string manipulations like reversing(`reverse()`) a string or inserting(`insert()`) a character. Should you use StringBuilder to concatenate strings? Most of the time no, if you're using Java 9 and later, string concatenation with plus(+) has been optimized. If you're using Java 8, then in many cases concatenation with plus is in fact compiled with `StringBuilder`\n\nOne last word, if you are joining string elements from a List or an Array consider using `String.join()` the `StringJoiner` class and the `Collectors.joining()` collector.\n\u003c/details\u003e\n\n## 20. How to make a Singleton?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nOne pattern, you use an `enum` with a single value\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe pattern that uses a class with a private constructor, a private static field and a factory method that tests if the private field is new or not is more complex either non-thread safe or buggy or both. Making it thread safe using a double check locking is also buggy, just look for this bug on your favorite search engine. Using an enum is super simple, thread safe, guaranteed bug free at the jvm level and recommended by the best experts.\n\nOne last word, this any based pattern is used in many places in the jdk, you can check the source code of the `Comparator.naturalOrder()` factory method for example\n\u003c/details\u003e\n\n## 21. What is a static method?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA method declared with the `static` keyword\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nA method that you can invoke without creating any object. You can invoke a static method with a class name, you can even invoke a static method through a null object. A static method cannot call a `non-static` method from the same class. Static methods are useful to implement processors or computations, some classes only have static methods like Math, Arrays or Collections.\n\n```java\nclass Scratch {\n    public static void main(String[] args) {\n        Scratch scratch = null;\n        scratch.print();\n    }\n    private static void print() {\n        System.out.println(\"print...\");\n    }\n}\n```\n\nOne last word, static methods are sometimes called Factory methods because they can be used to create objects in a certain way like `List.of()` that creates an empty list. Classes with only static methods are sometimes called Factory classes.\n\u003c/details\u003e\n\n## 22. How can you find a character in a String?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a method for that called `indexOf()`\n\u003c/details\u003e\n\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe `string.indexOf()` method has several overloads, one just take a character in the form of an int, another char and int because Java supports Unicode and some characters cannot be encoded on a single char, another one takes a string because `indexOf()` can also find small strings in bigger strings. Both can also take an index used to start the search from, indexOf returns the index or the first occurrence of the character or the string so if you want to find all the occurrences of a single letter you can loop in that way.\n\n```java\npublic static void main(String[] args) {\n    String s = \"abcabcabd\";\n    int index = s.indexOf('b');\n    System.out.println(\"index: \" + index);\n    while (index \u003e 0) {\n        index = s.indexOf('b', index + 1);\n    }\n    System.out.println(\"index: \" + index);\n}\n```\n\nOne last word, is the character or the string is not found index of returns -1\n\u003c/details\u003e\n\n## 23. What is a method reference?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAnother way of writing a Lambda expression\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are four kinds of method references;\n- `static method references`, this operator can be written in that way, and it also works with other types\n```java\nDoubleUnaryOperator op = d -\u003e Math.sqrt(d);\nDoubleUnaryOperator op = d -\u003e Math::sqrt;\n```\n- `bound method references`, the classical `System.out::println` is a bound method reference\n```java\nConsumer\u003cString\u003e c = s -\u003e System.out.println(s);\nConsumer\u003cString\u003e c = System.out::println;\n```\n- `unbound method references`, are they may look like static calls like this one, but they are not so be careful\n```java\nToIntFunction\u003cString\u003e f = s -\u003e s.length();\nToIntFunction\u003cString\u003e f = String::length;\n```\n- `constructor method references` like this one\n```java\nSupplier\u003cList\u003cString\u003e\u003e sup = () -\u003e new ArrayList\u003c\u003e();\nSupplier\u003cList\u003cString\u003e\u003e sup = () -\u003e ArrayList::new;\n```\n\nOne last word, to translate a method reference to Lambda, you need to know its exact type. One very last word, method references are there to improve the readability of your code so if you feel your code is actually less readable with them don't use them\n\u003c/details\u003e\n\n## 24. What is the default method?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt's a regular method written in an interface\n\n`Default method = Concrete methods in an interface`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nDefault methods have been added to the language in Java 8.\n\n`Java 7: no default methods`\n\nPrior to that all the methods in an interface had to be `abstract` so the abstract keyword for abstract methods is not mandatory in interfaces, for regular concrete methods you need to add the default keyword thus their name default method. Apart from that default methods are just regular methods. A default method from an interface can be used by any object that implements that interface, and they can be overridden in any concrete class.\n\nOne last word, in Java 8 default methods can only be `public` starting with Java 9 they can also be `private`\n\u003c/details\u003e\n\n## 25. What does JIT mean?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nJIT stands for `Just In Time Compiler`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nWhat you have in a class file is the byte code of your class, this bytecode is first interpreted by your Java Virtual Machine. Running your Java code in that way is super slow so a first JIT compiler called `C1` compiled it to machine language. The C1 compiler does a nice job but your compiled code can be optimized even further. That's the job of a second JIT compiler `C2`. C2 carefully analyzes the way your code is running and compiles it again to leverage some more optimization.\n\nOne last word, if at some point C2 sees that it can do better, it will de-optimize your code and optimize it again\n\u003c/details\u003e\n\n## 26. What kind of method can you override?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nInstance methods\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`static` methods cannot be overridden because you call them using an explicit class name so even if a Class B extends a Class A and defines the same static method you can still call each of them. Instance method can be overridden as long as they are non-private, non-final and that their class can be extended. The obvious way to prevent a class from being extended is to make it `final`, but you can also declare it's NoArgConstructor private.\n\n```java\nclass Scratch {\n    public static void main(String[] args) {\n        System.out.println(\"A: \" + A.name());\n        System.out.println(\"B: \" + B.name());\n        // A: A\n        // B: B\n    }\n}\nclass A {\n    public static String name() {\n        return \"A\";\n    }\n}\nclass B extends A {\n    public static String name() {\n        return \"B\";\n    }\n}\n```\n\n- Safe way: copy the method declaration\n\nOne last word, the safest way to override a method, just to copy its declaration in your extending class with the written type, the parameters and the exceptions, but you can be more certain than that and that will be for another time\n\u003c/details\u003e\n\n## 27. What is the signature of a method?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIts name and its parameters\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nNeither the return type of a method nor its declared exceptions are part of its signature because all the methods of a given class must have different signatures, you can have several methods with the same name as long as they have different parameters and these methods can have different written types, but it is not legal to have two methods with the same name, same parameters and just a different return type because they would have the same signature.\n\n```java\nclass Scratch {\n    public void print(String name) {\n        System.out.println(\"print:\" + name);\n    }\n    \n    // Compiled Error: 'print(String)' is already defined in 'Scratch'\n    public String print(String name) throws Exception {\n        System.out.println(\"print:\" + name);\n        return name;\n    }\n}\n```\n\nOne last word, this rule holds even if one of this method is abstract because it would force the implementation to break this rule\n\n```java\nabstract class AbstractScratch {\n    public abstract void print(String name);\n\n    // Compiled Error: 'print(String)' is already defined in 'AbstractScratch'\n    public abstract String print(String name) throws Exception;\n}\n\n```\n\u003c/details\u003e\n\n## 28. What is a marker interface?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn interface with no method that is just here to Mark a class\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nBeing a marker interface is not really a language or an API notion, it's just a way of describing the nature of some interfaces. There are several examples in the JDK of such interfaces `serializable` of course that allows the instance of a class to be serialized and the `cloneable` that allows instances of a class to be cloned.\n\nOne last thing, because there is no method in these interfaces, you need to check if the object you have is an instance of this interface. It can be done with `instanceOf()` or directly at the class level with the method is assignable from defined on the class of Class (`Class.isAssignableFrom()`)\n\u003c/details\u003e\n\n## 29. What is the difference between Collection and Set?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere are no duplicate elements in the Set\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`Collection` and `Set` are interfaces from the collections framework. `Set` extends Collection all the instance method defined in the Set interface override method from collection and are re-defined to modify the semantic. They do not work in the same way. The set interface is implemented by `HashSet` which has another very interesting property, its implementation of the `contains()` method is super fast, much faster than the one from ArrayList.\n\nOne last word, if you need both the iterability property of ArrayList and the fast container implementation, you may take a look at the `LinkedHashSet` class which unfortunately is not a List.\n\u003c/details\u003e\n\n## 30. How does finalize() work?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt does not work\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`finalize()` has been deprecated in Java 9 and deprecated for removal in Java 18, so stop using it. `finalize()` is supposed to be a method called by some undefined elements when the garbage collector detects that an object is not reachable anymore.\n\nHere are two of the major issues with finalizer; First, the thread running finalized is not specified those are that you can get race conditions in this method. Second, it may take a lot of time for this method to be called, the correctness of your code should never rely on the fact that finalize is called.\n\nOne last word, there is a replacement pattern called `The Cleaner Pattern`, you can check the cleaner class for more information\n\u003c/details\u003e\n\n## 31. What are the main features of java 8?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nLambda Expressions\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis version so Lambda expression added to the language but there are many other things that have been added to Java 8. The collections frameworks has been rewritten with many new features and methods. The stream API is a very clean implementation of `map`, `filter`, `reduce` that you can use in parallel. The completable future API is an asynchronous programming model added to the JDK and many many small things here and there to make your developer life better. \n\nOne last word, Java 8 was released in March 2014 as of this recording that was 9 years ago if you're still working on this version, you should really consider moving to a more recent one\n\u003c/details\u003e\n\n## 32. Do streams and collections have common methods?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYes and no, they do have one method that is called the same and take the same parameter\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis method is called `foreach()`, it takes a consumer and you have it on both the `stream` interface and the `iterable` interface that being said even if they are basically doing the same thing, these methods are not implemented in the same way. Most of the time you can call directly `collections.foreach(...)` instead of calling `collections.stream().foreach()` that makes you save the creation of the stream object if you don't use it why would you want to create it.\n\n```java\nList\u003cString\u003e letters = List.of(\"h\", \"e\", \"l\", \"l\", \"o\");\nletters.forEach(System.out::println);\n\nletters.stream().forEach(System.out::println);\n```\n\nOne last word, even if collections and streams are there to process data there are many differences between them but that's for another time\n\u003c/details\u003e\n\n## 33. How can you tell that a string is an anagram of another string?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThe easy way, sort the letters of the strings and just compare them\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere is actually a much smarter way of doing that you can map each letter to prime number, for instance map A to 2, B to 3, C to 5 etc, then multiply all these numbers either two numbers you get are the same these strings are anagrams. It comes from the fact that the decomposition of an integer in a product of prime number is unique. The first method has a complexity of `n*log(n)` the second one is just `n` which is faster.\n\n```\nC -\u003e 5\nA -\u003e 2\nT -\u003e 71\nCAT -\u003e 5*2*71 = 710\nACT- -\u003e 2*5*71 = 710\n```\n\nOne last word, be careful not to overflow when you're doing the multiplication, it can happen for long strings of characters\n\u003c/details\u003e\n\n## 34. On what kind of source can you build a Stream?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is no short answer, there are many sources\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nYou can create streams on the following;\n\nCollections of course this is the most common way but the jdk offers much more than that because you can also create a stream on the lines of a text file on the characters of a string of characters. On the elements of a string you split using a regular expression and several others plus. The stream API gives you what you need to connect the stream on your own source of data.\n\n- Collections and array\n- Lines of a text files\n- Regular expressions\n- You can build your own\n\nOne last word, be careful that the processing of a stream should not modify its source while it is consuming it. If you do that then the result you will get is unpredictable\n\u003c/details\u003e\n\n## 35. What is the groupingBy()?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA collector, you can use to build maps that are in fact histograms from the elements of a stream\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe pattern is `stream().collect(...)` and pass `Collectors.groupingBy(...)` and then you need to pass a function to this groupingBy(). This function maps each element of your stream to a key that is then added to your map. The corresponding element is itself added to a list bound to this key so if several elements of your streams are mapped to the same key you will find them together in this list.\n\n```java\ncities().stream().collect(Collectors.groupingBy(City::state))\n// -\u003e Map\u003cState, List\u003cCity\u003e\u003e\n```\n\nOne last word, you can post process this list with another collector, pass as a second argument to this groupingBy(), this other collector is called the Downstream Collector.\n\u003c/details\u003e\n\n## 36. What is the difference between FIFO and LIFO?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`FIFO` is a queue, `LIFO` is a stack\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`FIFO` stands for `F`irst `I`n `F`irst `O`ut and `LIFO` stands for `L`ast `I`n `F`irst `O`ut.\n\nThere are two interfaces in the jdk to model these, queue, that models the FIFO that is extended by `deque` and that's the second interface that models for LIFO. The preferred implementation for both of these interfaces is `ArrayDeque` but it's not thread safe. If you need a thread safe implementation you can use a `ConcurrentLinkedQueue` for queue or `ConcurrentLinkedDeque` for deque.\n\nOne last word, there is a Stack class in a jdk that is an extension of the Vector class. Both `Stack` and `Vector` have been deprecated a long time ago, so you should not use them anymore\n\u003c/details\u003e\n\n## 37. What is the GOF?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThe nickname of the fundamental book on design patterns\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe full title of this book is `Design patterns; Elements Of Reusable Object-Oriented Software`. It was published in 1994. The four authors are `Erich Gamma`, `Richard Helm`, `Ralph Johnson` and `John Vlissides`. This book contains a 23 design patterns in three categories; \n\n- Creational: with the Builder, the Factory, the Singleton\n- Structural; with the Adapter, the Decorator, the Proxy\n- Behavioral; with the Iterator the Strategy, the Visitor.\n\nOne last word, this book is a must-read. The examples are written in C++ but it's easy enough to convert them to Java or to your favorite language\n\u003c/details\u003e\n\n## 38. How can you create a Comparator?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nJust use the factory methods of the `Comparator` interface\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis interface has a bunch of factory methods to create comparators that compare objects using one of their fields, it also has default methods to modify the behavior of a given comparator. For instance, you can compare people using their last name and in case you have people with the same last name you can then compare them using their first name. In case you want to use this comparator to sort a list of people but need to sort them in the reverse order and then you can call reversed() on an existing comparator.\n\n```java\nvar userComparator = Comparator\n        .comparing(User::lastName)\n        .thenComparing(User::firstName)\n        .reversed();\n```\n\nOne last thing, null values are always painful to handle when you want to sort a list. The comparator interface has also a `nullsFirst()` and `nullsLast()`.\n\n```java\nvar userComparatorWithNullsFirst = Comparator.nullsFirst(userComparator);\nvar userComparatorWithNullsLast = Comparator.nullsLast(userComparator);\n```\n\u003c/details\u003e\n\n## 39. Can you cite functional interfaces that existed before Java 8?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`Runnable`, `Comparator`, `Iterable`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThey are actually more, the definition of a functional interface is such that some existing interfacers became functional with Java 8. Because you can implement a functional interface with a Lambda, it means that if you have old interfaces in your application that qualify for functional interfaces and then you can use lambdas to implement them without having to recompile them. That's why the `@FunctionalInterface` annotation is not mandatory on the functional interface.\n\nOne last word, you want more sure `Executor` even `Comparable` is a functional interface though I'm not sure that you want to implement this one with another expression\n\u003c/details\u003e\n\n## 40. How can you open a file for writing some text?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a factory method for that in the `Files` class\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are actually two patterns; one from the old days of `java.io` and the less old one from `java.nio` and this is the one you should prefer. The exact pattern is the `Files.newBufferedWriter(...)` that takes a path as an argument, it has several overloads.\n\n```java\nvar writer = Files.newBufferedWriter(\n        path,\n        StandardCharsets.ISO_8859_1,\n        StandardOpenOption.CREATE,\n        StandardOpenOption.APPEND\n);\n```\n\nYou can specify the Charsets used by your text file, the default value being utf-8 and you can specify some open options. Do you want to create the file if it does not exist and if it does do you want to erase its content or append to it?\n\nOne last word, what you get is still a buffered writer that you can still decorate if you need\n\u003c/details\u003e\n\n## 41. What is the difference between a Sorted and an Ordered Collection?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nSorted means that you can compare your elements, Ordered means that you can access them using an index\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIt has to do with how you can iterate over the elements of your collection. The sorted collection gives you the smallest element first up to the largest one. If you add an element to a sorted collection, you may change the iteration order. An ordered collection on the other hand respects the order in which you add your elements so the first element is the first that has been added up to the last one.\n\nOne last word, ordered collections are modeled by the Lists in the collection framework, your favorite implementation is a `ArrayList` and sorted collections are modeled by NavigableSet implemented by `TreeSet`\n\u003c/details\u003e\n\n## 42. How can you open a file for reading binary data?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a factory method for that on the `Files` class\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe all patterns from Java 1.1 based on the decoration pattern are still there, but you should use the Files factory class to create your readers, writers, input stream and output stream.\n\n```java\nFiles.newInputStream(path);\n```\n\nThe implementations you will get are built on top of `java.nio` and they are going to give you better performances. You can still use The Decorator pattern if you need to build data input stream or data output streamed, gzip streams or streams that mixed text and data. \n\nOne last word, using the patterns from the Files factory class also give you final control on the opening of files on the `CharSet` you can use to read your text files and they are built to use the path object instead of file objects which is better\n\u003c/details\u003e\n\n## 43. How can you print an array on the console?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nUse the factory method from the `Arrays` class\n\n```java\nArrays.toString(array);\n```\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nAn Array is an object but with a default `toString()` method that you cannot override so printing it on the console directly gives you something that you do not want. You can call `Arrays.toString()` and pass your array it will print the content of your array on called toString() on each element of this array if it is an object. If you are not happy with the formatting you then need to iterate on the elements of this array or create a stream on it and create the strings of characters you need.\n\n```java\nvar result = Arrays.stream(new String[]{\"one\", \"two\"})\n        .map(Object::toString)\n        .collect(Collectors.joining(\",\", \"{\", \"}\"));\nSystem.out.println(result); // {one,two}\n```\n\nOne last word, you can use arrays in the foreach pattern, this pattern works for any object that implements the `iterable` interface, now interval declares a foreach method, but you cannot call it on arrays\n\u003c/details\u003e\n\n## 44. How does a SortedSet work?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt is a Set that keeps its elements sorted\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nFirst point, it's a Set so it does not have any duplicates if you add two elements that are equal then the second one will not be added. Second point the elements you add must be Comparable or if they are not you must provide a comparator when you create your SortedSet. If you provide a comparator, it will be used even if your elements are comparable and when you iterate over them they will be sorted in the increasing order. As of Java 6, you should favor `NavigableSet` instead of SortedSet that gives you more method than total Sets.\n\nOne last word, the default implementation is `TreeSet` which implements a Red Black Tree\n\u003c/details\u003e\n\n## 45. What pattern has been used to create the Java I/O API?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThe Decorator Pattern\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe Decorator Pattern is a `Structural Pattern` from the `Gang of Four` (GoF) book. A decorator is in fact a wrapper on an object that extends the class of that object, it may add more methods or change the way the existing methods are working. Wrapping an existing object means that it's constructor takes an object of the superclass as a parameter so it is both `an extension` and `a composition` for instance `BufferedReader` extends Reader and adds readline() method, plus the reading works with a buffer.\n\nOne last word, you should use the `Files` factory class to build the base objects, you need to read and write content to files, but you can still decorate them to add features to the base objects you get\n\u003c/details\u003e\n\n## 46. What are the different categories of design patterns?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n3 categories; `Creational`, `Structural`, `Behavioral`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIt refers to the `Gang of Four` (GoF) book a must-read for every developer. Some creational patterns; `Factory`, `Builder` and `Singleton`, some structural patterns; `Decorator`, `Facade`, `Proxy`, some behavioral patterns; `Iterator`, `Template Method` and a well-known `Visitor`. The GoF gives you C++ implementations, some of them are updated but the ideas are still excellent.\n\nOne last word, there are many patterns that are so widely used that you use them even if you don't know them. That's the case for the Iterator Pattern or the Factory Pattern\n\u003c/details\u003e\n\n## 47. How can you count how many times a letter appears in a String?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou need to iterate over the string in one way or another\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nTwo ways; first, you can look for your letter in a string with `indexOf()` until you don't find it anymore. `indexOf()` may take an index where it will start its search that's a quick and efficient pattern. Second pattern, you can stream on the letters of the stream removing the letters that do not match and count the result, efficient, more functional, more readable, this is the one I prefer.\n\n```java\npublic void countLoop(String sentence, int letter) {\n  int count = 0;\n  int index = sentence.indexOf(letter);\n  while (index \u003e= 0) {\n      count++;\n      index = sentence.indexOf(letter, index + 1);\n  }\n  System.out.println(count);\n}\npublic void countStream(String sentence, int letter) {\n  long count = sentence.chars()\n          .filter(c -\u003e c == letter)\n          .count();\n  System.out.println(count);\n}\n```\n\nOne last word, the `count()` method return the long that you can safely cast to an end. A string of character is backed by an Array so there is no way you can have more than `Integer.MAX_VALUE` letters\n\u003c/details\u003e\n\n## 48. What is a bucket in a Map?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA cell in an array\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe HashMap class from the collections framework is backed by an `Array`, when you add a key to a HashMap a special hash code is evaluated for that key to choose which cell of the array will receive the key value pair. If there is already a different key value pair in this cell, this is called the `collision` and then a `LinkedList` is created to add this second pair and if there are too many, this LinkedList is actually replaced by your `Red Black Tree` to minimize collisions when the amount of key value pairs reaches `75%` of the size of the array then it is copied in a new larger array.\n\nOne last word, this copying incurs the re-hashing of all the keys present in a map which may be costly so be careful about that and try to create maps with the right size\n\u003c/details\u003e\n\n## 49. What does Synchronized mean?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt is a keyword that prevents more than one thread to execute a given block of code at the same time\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nSynchronization has to do with concurrent programming, this block of code can be a delimited block inside the method or it can be the wall method static or not. All synchronized blocks need an object that they use as a key, you can use the same key for more than one synchronized block. In the case of a synchronized method then the key is the object itself or the class if the method is static. There are limitations with synchronized block that you don't have with `ReentrantLock` so we can use these objects instead.\n\nOne last word, never expose your key or your locks. It will help you prevent `Deadlocks` a situation that you absolutely want to avoid\n\u003c/details\u003e\n\n## 50. What is the difference between a Collection and a Stream?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA collection contains an object, a stream is empty\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nA collection is meant to carry objects around with methods to handle them, most of the time your stream is an empty object that you can connect to a source of objects to process them. This source can be a collection, an array and many other things. You can even connect a stream to your own source of data if you need it. It will then process your elements one by one lazily. Some methods like `findAny()` or `allMatch()` can interrupt the processing of these objects.\n\nOne last word, there are actually two methods that need to remember the processed object; `distinct()` and `sorted()` so if you're using them then your stream will not be empty anymore\n\u003c/details\u003e\n\n## 51. What is the difference between a File and a Path?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA File is a class and the Path is an interface\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe File class is from Java 1.0 but is from `java.nio` released with Java 7. An instance of file is the same no matter what file system you're using because Path is an interface, the instance you build depends on the file system. You can get attributes that are specific to these file systems like security attributes. As of now, you should favor the use of path objects over file objects.\n\nOne last word, creating an instance of file all path does not create the corresponding file or directory on your disk, you need to call `createNewFile()` on the File class or the `Files.createFile()` Factory method that takes a path as an argument to do that\n\u003c/details\u003e\n\n## 52. What is the difference between a Checked and an Unchecked Exception?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou need to write special code to handle the checked exception, not for unchecked exceptions\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nAll your exceptions extend the `Exception.class` if an exception actually extends `Runtime` exception then it is an unchecked exception if it does not then it is checked exceptions. You need to handle your checked exceptions either by catching them or by declaring them in the `throws` clause of your methods and constructors. You do not need to do that for unchecked exceptions.\n\nOne last word, all these classes extend themselves the `Throwable.class` also extended by the `Error.class`. Errors are also unchecked exceptions but reserved for serious problems like Out Of Memory `OOM` error or Stack Overflow error\n\u003c/details\u003e\n\n## 53. What is a Stream?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn object that implements the `map`, `filter`, `reduce` pattern\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe stream consumes elements from a source and can do several operations, these operations are organized in a pipeline where each element is passed from one step of the pipeline to the next one. Mapping an element consists in transforming it, filtering consists in deciding if this element should be transmitted or not based on a predicate and reducing may consist in many things; summing the elements, extracting a min or a max or adding them to a list or a map.\n\nOne last word, the stream API allows you to conduct these computations in parallel, still you need to be careful with that as always when it comes to optimizations measure, don't guess\n\u003c/details\u003e\n\n## 54. What is the hash code of an object?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA mapping of an object to an integer\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe idea behind the hash code is to represent any object within it so that you can quickly tell if two objects are different by just comparing their hash code. Indeed, the specification says that two objects that are equal must have the same hash code but it turns out that two different objects may also have the same hash code so if two objects have different hash code then they cannot be equal but if they have the same hash code then you need to compare them to see if they are equal.\n\nOne last word, there are many ways of computing hash codes some are better than others, if you're not sure on what you need relying on your IDE to generate the hash code method is probably your safest choice.\n\u003c/details\u003e\n\n## 55. What is an ExecutorService?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn object to which you can submit tasks to be executed in another thread\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nExecutorService is an interface part of the `java.util.concurrent` API added to the `JDK 5` in 2004. It's the preferred way to run tasks in another thread. In fact, you shouldn't be creating threads by calling `new Thread()` anymore. A task can be either a `Runnable` or `Callable` that you can implement with a lambda expression, submitting a task gives you a Future object that you can use to get a result and exception if something goes wrong. All that you can use to interrupt the running of this task.\n\nOne last word, an ExecutorService is sometimes called the `Pool of Threads` and most of the time it is but it can also create threads on demand which is what it is doing for Virtual Threads for instance.\n\u003c/details\u003e\n\n## 56. What is an Iterator?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn object used to iterate over the elements of a Collection\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIterator is an interface with three method; `hasNext()` that tells you if there are more objects to iterate over we should call this method first then if it returns true, you can call `next()` to get the next object and move the iterator one step. It also has a `remove()` method that can throw an `UnsupportedOperationException` you need that if your collection is immutable. Most of the time you use iterators for collections but iterators can actually be created without them. For instance, you can create a `RangeIterator` that can iterate over a range of integers.\n\n```java\nimport java.util.Iterator;\n\npublic class RangeIterator implements Iterator\u003cInteger\u003e {\n    private int index = 0;\n    \n    public boolean hasNext() {\n        return index \u003c end;\n    }\n    public Integer next() {\n        return index++;\n    }\n}\n```\n\nOne last word, the iterator pattern is actually a pattern from the `Gang of Four` (GoF) book. Did I already mention that this book is a must-read?\n\u003c/details\u003e\n\n## 57. What are the 4 Java I/O based classes?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`Reader`, `Writer`, `InputStream` and `OutputStream`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThese are the 4 abstract classes that define the basic operations for reading and writing characters and binary data. They have been designed in the mid 90s and you should not use them directly anymore. The preferred patterns that you should use are the factory methods from the `Files.class`, these are a `new BufferedReader()` and `new BufferedWriter()` for the reading and writing of characters and `new InputStream()` and `new OutputStream()` for the reading and writing of binary data. These factory methods give you instances built on top of `java.nio`\n\nOne last word, you can still decorate the instances you get following the general pattern of the `java.io` API\n\u003c/details\u003e\n\n## 58. How many objects can you put in a collection?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt depends on the implementation you have\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`Arraylist` is backed by an Array so the limit would be `Integer.MAX_VALUE`, you may be thinking that LinkedList would allow you to store more objects but in fact many things will fail for a LinkedList with more objects than `Integer.MAX_VALUE`. LinkedList counts its element with a field called `size` that is an int and bad things will happen if size reaches `Integer.MAX_VALUE`. The `toArray()` method from LinkedList will not work super well neither since Arrays are also indexed by int.\n\nOne last word, the same limit also exists from `Maps` but don't worry there is little chance that you can reach that limit without reaching other limitations in your application.\n\u003c/details\u003e\n\n## 59. What is the maximum length of a String in Java?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt cannot be longer than `Integer.MAX_VALUE` because it is backed by an Array\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nFirst, that would be a very long string indeed and second the number of characters in a string may be different than the length of this array. The reason being there are many characters that are actually encoded on more than one byte.\n\nOne last word, the `String.class` changed in 2017 with Java9. The internal array used to be an array of chars 16 bits, it is now an array of bytes 8 bits. This optimization is called `Compact Strings` and can tremendously reduce the memory footprint of your application. One more reason to upgrade to the latest versions of the JDK.\n\u003c/details\u003e\n\n## 60. How does a Set know that it already contains an element?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt uses the `hashCode()` of the object, if it finds something then it calls the `equals()` method\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nA HashSet stalls its objects in the cells of an Array. The index of the cell for a given object is computed from the `hashCode()` of this object. This process is very fast because it does not depend on the amount of elements you have in your Set. Of course there is a mechanism to handle collisions that is if two different objects happen to have the same hash code.\n\nOne last word, because of that HashSet will not work if you override `equals()` for your object without overriding `hashCode()` and one very last word, do not mutate an object once it has been added to a set because you will not be able to find it again\n\n```java\nimport java.util.HashSet;\nimport java.util.Objects;\nimport java.util.Set;\n\nclass Person {\n    private String name;\n    private int age;\n\n    public Person(String name, int age) {\n        this.name = name;\n        this.age = age;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public void setAge(int age) {\n        this.age = age;\n    }\n\n    @Override\n    public int hashCode() {\n        return Objects.hash(name, age);\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) return true;\n        if (obj == null || getClass() != obj.getClass()) return false;\n        Person person = (Person) obj;\n        return age == person.age \u0026\u0026 Objects.equals(name, person.name);\n    }\n\n    @Override\n    public String toString() {\n        return name + \" (\" + age + \")\";\n    }\n}\nclass Scratch {\n    public static void main(String[] args) {\n        Set\u003cPerson\u003e set = new HashSet\u003c\u003e();\n\n        Person person = new Person(\"John\", 30);\n        set.add(person);\n\n        System.out.println(\"Set contains: \" + set.contains(person)); // true\n\n        // Mutate the object after adding it to the Set\n        person.setName(\"Jane\");\n        person.setAge(25);\n\n        // Try to find the object in the Set again\n        System.out.println(\"Set contains: \" + set.contains(person)); // false\n\n        // The object is still in the Set, but we can't find it because its hash code has changed\n        System.out.println(\"Set elements: \" + set);\n    }\n}\n/*\nSet contains: true\nSet contains: false\nSet elements: [Jane (25)]\n */\n```\n\u003c/details\u003e\n\n## 60a. Ad Episode\n\u003cdetails\u003e\n  \u003csummary\u003eAnswer\u003c/summary\u003e\n\nQuestion number wait I actually did 60 questions that's one hour and one hour is probably longer than most Java coding interviews at least for the technical parts so that's great. Don't worry, there are so many possible questions to be asked that yes there is still plenty of content to cover.\n\nI just would like to take a small break to let you know that I absolutely value your feedback and read all the comments you make so please keep them coming questions, suggestions, anything. Some questions in the comments actually became episodes so that's great thank you for that.\n\nOne last word, I created a playlist with all the episodes you can find a link in the descriptions and one very last word, next question 61 will be a real question so stay tuned for more\n\u003c/details\u003e\n\n## 61. How is `Arrays.asList()` working?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`Arrays.asList()` wraps an array and exposes it as a List\n\n- It does not copy it\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nFirst, you can call `Arrays.asList()` with a vararg but you can also pass an Array. Avoid passing an array of primitive types because what you will get is a list with a single element being the array itself. If you modify the array you pass then it will modify the list itself because as I said there is no defensive copy of this array. You can modify the elements of this list but you cannot `add` or `remove` elements from it because you know it's actually an Array.\n\nOne last word, so what you get with the `Arrays.asList()` is not an Unmodifiable List because you can still change its elements, if what you need is an Unmodifiable List you may consider using `List.of()`\n\u003c/details\u003e\n\n## 62. Can you cite some methods from the Stream API?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThe 3 basic methods are `map()`, `filter()` and `reduce()`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThose are that you will not use reduce match because you have many specialized method to reduce the elements of your stream like `toList()`, `forEach()`, `findFirst()` or `findAny()`. Other intermediate methods you can cite `flatMap()` of course `distinct()`, `sorted()` . 2 things you absolutely need to avoid. Avoid using `pick()` unless you need to debug your stream. `pick()` is useless in production, second don't do any side effect in any method of the stream API. It will put you in trouble.\n\nOne last word, you can also reduce your stream with the collector API, there are a bunch of available characters in the `Collectors` factory class and you can even create your own.\n\u003c/details\u003e\n\n## 63. What is the `var` keyword in Java?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA keyword you can use in methods to avoid having to specify the type of a local variable\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`var` is for local variables only, you cannot use it for fields for instance. You may use it for `Anonymous Classes` and in that case you will have access to the method you add in your Anonymous class that are not defined in the original type. The type of an Anonymous class is called the Non-Denotable type, you can add fields and method to it and access them if you declare your variable with the `var` keyword.\n\n```java\nvar v = new Object() {\n  private int i = 0;\n  public int index() {\n      return i;\n  }\n};\nprintln(\"i = \" + v.index());\n```\n\nOne last word, you can use your IDE to see the type in further by the compiler and sometimes the result is unexpected\n\u003c/details\u003e\n\n## 64. How can you create an Unmodifiable List?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nWith the factory method `List.of()`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are actually several ways to do that but `List.of()` is the preferred one, be careful with the behavior of `Collections.unmodifiableList()` what it gives you is an unmodifiable view of a list but the list you give as an argument is not defensive copied so if you modify it then this modification will be seen through the view, on the other hand you can pass an array to `List.of()` that will be copied so no funny behavior there.\n\nOne last word, be careful because `List.of()` does not accept null values. Why would you put null values in a list? You will get an exception at runtime if you pass an array with a null value in it\n\u003c/details\u003e\n\n## 65. How can you start a thread?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a `start()` method on a `Thread.class`\n\n`Call start(), not run()`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nTwo things a thread is either built on a Runnable or is a Runnable itself, in both cases a common mistake is to call the run method instead of start. `run()` will execute your Runnable but in the current thread not in a new thread. Second, calling `start()` is okay for testing, learning and exploring how threads are working. In a production environment, you should not launch your threads by hand. You should use instead the `ExecutorService` Pattern.\n\nOne last word, JDK 21 adds new factory methods on the Thread class to create both `Platform` threads and `Virtual` threads, but that would be for another time\n\u003c/details\u003e\n\n## 66. How can you create a file on the disk with Java I/O?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nUse the `createFile()` factory method from the `Files.class`\n\n```java\nFiles.createFile(...)\n```\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere is also a `createNewFile()` on the File class that is the legacy way of creating files. Creating a writer on output stream on a File can also create this file for you, once again the preferred pattern are in the Files factory class, you can check the `new BufferWriter()` or `new OutputStream()` factory methods they both take an open option arguments standard open options include read(), write(), append(), create() or createNew() among others.\n\nOne last word, depending on your file system, you can also pass 5 attributes to a file creation to handle security for instance\n\u003c/details\u003e\n\n## 67. What is the class named Class?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThe class that models classes\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe JVM creates an instance of this class for each class it loads. The simplest ways to get a reference on the class objects is to call `getClass()` on any object but you can also use the class itself directly like `String.class` or call the `Class.forName(\"...\")` method passing the name of the class as a string. In any case you always get the same reference to a given class there is only one instance of the Class.class that models the String class for instance.\n\n```java\nvar c1 = \"hello\".getClass();\nvar c2 = String.class;\nvar c3 = Class.forName(\"java.lang.String\");\n```\n\nOne last word, the Class class is the entry point of the reflection API which gives you a way to manipulate objects reflectively, a technique that is used by many frameworks\n\u003c/details\u003e\n\n## 68. How can you find duplicates in a List?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt really depends on what you need\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nYou can check if your list has duplicates by putting this List in a Set and comparing the size of the set with the size of the list. You could also use a stream calling `distinct()` and count()` method on it which also builds the Set internally. If you need to find the duplicate elements themselves then you need to build an histogram of these elements, create a stream on the list and group the elements by themselves counting them with the counting character.\n\n```java\nList\u003cT\u003e list = ...;\n\nMap\u003cT, Long\u003e histo = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))\n```\n\nOne last word, these techniques are all using Maps, a Set is in fact a map. With maps you can solve this problem in one pass over your data but you consume more memory. As usual there is a trade-off between computing time and memory conception.\n\u003c/details\u003e\n\n## 69. What is a Sealed type?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA type that knows all of its extensions\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIt can be any type interface, class or abstract class. You need to declare it with the `sealed` keyword and then declare the permitted types with the `permits` closer. Now there are constraints on these permitted types; first, they need to be declared in the same package or in the same module. Second they need to be either `final`, `sealed` or declared `non-sealed enum and records are actually final types so you cannot create an open hierarchy by accident, the non-sealed declaration is there for that.\n\n```java\nsealed interface Shape permits Circle, Square, RandomShape {}\nfinal class Circle implements Shape {}\nrecord Square implements Shape {}\nnon-sealed class RandomShape implements Shape {}\n```\n\nOne last word, seal types are enforced both at `compile time` and at `runtime`\n\u003c/details\u003e\n\n## 70. How is `List.of()` working?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt takes an Array or a vararg and makes a defensive copy to create an Unmodifiable List.\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nYou can use it with a vararg to create a pre-filled list but you can also pass an array, in that case remember that if it is an array of primitive types what you get is a list with one element which is your array probably not what you want. This List implementation does not accept null values, sometimes your IDE can warn you about that but in certain cases it cannot and you will get an exception at runtime.\n\n```java\npublic static void main(String[] args) {\n    int[] intArray = {1, 2, 3};\n    List\u003cint[]\u003e intsList = List.of(intArray);\n    System.out.println(intsList.size()); // \u003e 1\n}\n// or\npublic static void main(String[] args) {\n    Integer[] intArray = {1, 2, 3};\n    List\u003cInteger\u003e intsList = List.of(intArray);\n    System.out.println(intsList.size()); // \u003e 3\n}\n```\n\nOne last word, you can also create sets with `Set.of()` that works in the same way as `List.of()` and modifiable defensive copy and null values not allowed.\n\u003c/details\u003e\n\n## 71. What is the difference between Runnable and Thread?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\n`Runnable` is an interface and `Thread` is a class\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe Runnable is a model for a task you can implement it with Lambda that does not take anything and returns nothing. You can execute this lambda by calling its `run()` method. You can then create a thread object passing your runnable as an argument and then execute this runnable in this thread by calling the `start()` method of that thread object. Be careful not to use the `thread.run()` method, it will execute your runnable but in the current thread.\n\n```java\nRunnable task = () -\u003e System.out.println(Thread.currentThread().getName());\n\n// or\nThread t = new Thread(task);\nt.start();\nt.run() // NO !!\n\n// or\nExecutorService service = ...;\nservice.submit(task);\n```\n\nOne last word, this pattern is okay for playing with threads and understanding how they work. In a real application, you should use the `ExecutorService` pattern instead of this one\n\u003c/details\u003e\n\n## 72. What is the difference between `map()` and `flatMap()`?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThese are 2 methods from the stream API to map objects of a given type to objects of another type\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n`map()` is super simple, it takes a function like `String::length` that maps strings of characters to their name.\n\n```java\nvar lengthOfStrings = Stream.of(\"one\", \"two\", \"three\")\n        .map(String::length)\n        .toList();\n```\n`flatMap()` works differently, it maps one-to-many relationships. The mapping function should itself return a stream of something and these streams are flattened by the flatMap() method, for instance given a stream of countries you can flatmap this stream to a stream of cities.\n\n```java\nrecord Country(List\u003cCity\u003e cities) { }\n\nList\u003cCountry\u003e countries = ...;\nList\u003cCity\u003e cities = countries.stream()\n        .flatMap(country -\u003e country.cities().stream())\n        .toList();\n```\nOne last word, a mapping does not change the number of objects your stream processors, where a flatmap does. It can even produce zero elements\n\u003c/details\u003e\n\n## 73. How is synchronization working?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt works with the key held by the object you synchronize your block of code with\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis key is called the `monitor`, when a thread reaches a synchronized block or a method, it asks this object for its key. If the key is available, it takes it and run the code, if not it will have to wait until the key comes back. You absolutely want to avoid situations where the key never comes back usually because of `Deadlocks` but not only. In the case of an instance method, the object that holds the key is simply `this` and in the case of a static method, the object is the `class`.\n\nOne last word, try avoid synchronizing on objects that are public. That's a good rule to prevent Deadlocks, a situation you absolutely want to avoid\n\u003c/details\u003e\n\n## 74. What is a generic type?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA type that is parameterized over times\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nOnce defined along with the class, you can use this parameter in the class itself to define instance fields or instance methods. A single type can be parameterized over several types. Generics are massively used in athe JDK, all the collection framework, the stream API are using generics so you can check these classes to see how you can use them and how they were created.\n\n```java\nclass Box\u003cT\u003e {\n    void process() {\n        Class c = T.class;  // NO !!\n        T t = new T();      // NO !!\n        T[] ts = new T[10]; // NO !!\n    }\n}\n```\n\nOne last word, the type `T` is actually erased, it is replaced by object at runtime so there is a number of things you cannot do in your code. You cannot try to get the class of T because it will just return object, you cannot call `new T()` or `new Array\u003cT\u003e` neither\n\u003c/details\u003e\n\n## 75. How can you stop a thread?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou can't and you should not\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are two methods on the thread class; `stop()` and `suspend()` that have been deprecated in Java 2 1998 that is more than 25 years ago. Now throw an `UnsupportedOperationException` so don't even think about using them. Why? the answer is actually not that simple. In short, they have been deprecated mainly for security reasons. Being able to stop a thread could put your application in an unpredictable state something you absolutely want to avoid.\n\nOne last word, you are not supposed to start no stop your threads by end anyway. The pattern you should be using is the `ExecutorService` pattern that takes care of your thread life cycle for you\n\u003c/details\u003e\n\n## 76. How can you remove elements from a Stream?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nUse the `filter()` method\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nBe careful though because the stream does not contain any object, it consumes objects from a source so saying removing objects from a stream is actually not correct what you're really doing is telling your stream do not process certain elements. Filtering uses a predicate that tests certain properties of the object and decide if it should be further processed or not. On this example, you only want to process the non-empty strings.\n\n```java\nPredicate\u003cString\u003e isEmpty = String::isEmpty;\nPredicate\u003cString\u003e isNonEmpty = isEmpty.negate();\nList\u003cString\u003e strings = ...;\nList\u003cString\u003e nonEmptyStrings = strings.stream()\n        .filter(isNonEmpty)\n        .toList();\n```\n\nOne last word, there are actually 2 other patterns that you can use to do that. `flatMap()` and `mapMulti()`. They are not really meant for that but in certain cases they can work better than filter\n\u003c/details\u003e\n\n## 77. How is `Set.of()` working?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt builds a set of its arguments if there are no duplicates among them\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe arguments are added one by one to an array of the right size using the `hashCode()` to detect any duplicates, if a duplicate is detected an `IllegalArgumentException` is immediately thrown. This method only requires one pass over your data because duplicates are not allowed in your arguments, it can create an array of the right size upfront making the memory conception minimal so all this is pretty optimal.\n\n```java\npublic static void main(String[] args) {\n    int[] ints = {1, 2, 3};\n    Set\u003cint[]\u003e set = Set.of(ints);\n    System.out.println(set.size()); // \u003e 1\n}\n// or\npublic static void main(String[] args) {\n    Integer[] ints = {1, 2, 3};\n    Set\u003cInteger\u003e set = Set.of(ints);\n    System.out.println(set.size()); // \u003e 3\n}\n```\n\nOne last word, as usual be careful if you pass an array of primitive types because you will get a Set with a single element to your array which is usually not what you want.\n\u003c/details\u003e\n\n## 78. How can you join Strings with a separator?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou have a `join()` a factory method for that on the String class directly.\n\n```java\nList\u003cString\u003e strings = List.of();\nvar stringWithSeperator = String.join(\",\", strings);\n```\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThere are 2 overloads of this method, they both take a `delimiter` as a first argument and then you can pass a varargs or an array that's the first overloader or an iterable typically a collection and that's the second overload. If you need to add a prefix or a postfix to your string of character and then you can check the `StringJoiner.class` you can also reuse this StringJoiner if you have many strings to process.\n\n```java\n\nList\u003cString\u003e strings = List.of();\nvar joiner = new StringJoiner(\",\", \"{\", \"}\");\nstrings.forEach(joiner::add);\nvar stringWithSepPrefxSuffx = joiner.toString();\n```\n\nOne last word, you can also check the collect `Collectors.joining()` pattern which does the same for the stream API. That's useful if you need to create this stream lazily without you having to buffer everything in a collection\n\n```java\nList\u003cString\u003e strings = List.of();\nvar stringWithSepPrefxSuffx = strings.stream()\n        .collect(Collectors.joining(\",\", \"{\", \"}\"));\n```\n\u003c/details\u003e\n\n## 79. How can you modify your field using the Reflection API?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou can use the `set()` method of the field class to do that\n\n`Field.set(obj, value)`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis method takes the instance you want to operate on and the value you want to fix, if you do not have access to this field because it is private for instance, you can still change it by calling its `Field.setAccessible(true)` passing true as an argument. It does not make the field public but suppresses the access controls made by the language.\n\nOne last word, you can actually mutate final fields in regular classes which this pattern which is really annoying but records are `protected` against that you cannot mutate them, one more reason to use records wherever you can\n\u003c/details\u003e\n\n## 80. How can you declare a generic type on a Static Method?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou need to define the type parameter along with the method declaration\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe type parameters you define on a class are only seen by the instance, fields and methods not by the static members. Suppose you have a Box\u003cT\u003e class and you want to define the static method copy(). To define the type parameter for this method you need to add it after the static keyword not also that if you have several static methods, each one needs to declare its own type parameter.\n\n```java\nclass Box\u003cT\u003e {\n    private T t;\n    Box(T t) {\n        this.t = t;\n    }\n    static \u003cT\u003e Box\u003cT\u003e copy(Box\u003cT\u003e box) {\n        return new Box\u003c\u003e(box.t);\n    }\n}\n```\n\nOne last word, you have many examples of that in the jdk, in the collections class for instance. They also use this word syntax question marks Super T `? super T` and question marks extensity `? extends` but that will be for another time\n\u003c/details\u003e\n\n## 81. What does passing by value mean?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt means that what you pass to a method is the value not a reference to this value\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe consequence is that if your method modify the argument it gets, the calling code does not see this modification, if what you pass is a primitive type changing it in your method does not change the value in a calling code. If what you pass is a reference changing the reference itself does not change it in a calling coder but if you change the content of the object reference then this change is seen in a calling code.\n\n```java\nclass Scratch {\n    public static void main(String[] arg) {\n        Dog aDog = new Dog(\"Max\");\n        Dog oldDog = aDog;\n\n        // we pass the object to foo\n        foo(aDog);\n\n        // aDog variable is still pointing to the \"Max\" dog when foo(...) returns\n        System.out.println(\"3\" + aDog.getName().equals(\"Max\"));// true\n        System.out.println(\"4\" + aDog.getName().equals(\"Fifi\"));// false\n        System.out.println(\"5\" + (aDog == oldDog)); // true\n    }\n    public static void foo(Dog d) {\n        System.out.println(\"1\" + d.getName().equals(\"Max\")); // true\n        // change d inside of foo() to point to a new Dog instance construct red with name member variable set to \"Fifi\"\n        d = new Dog(\"Fifi\");\n        System.out.println(\"2\" + d.getName().equals(\"Fifi\")); // true\n    }\n}\nclass Dog {\n    private String name;\n\n    public Dog(String name) {\n        this.name = name;\n    }\n\n    public String getName() {\n        return name;\n    }\n\n    public void setName(String name) {\n        this.name = name;\n    }\n}\n/*\n1true\n2true\n3true\n4false\n5true\n*/\n```\n\nOne last word, Java passes by value always no exception\n\u003c/details\u003e\n\n## 82. What is the difference between an intermediate and a terminal operation?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn intermediate operation returns a stream, the terminal operation returns something else including void\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe stream processes the data from the source only when it executes its terminal operation. If you do not call the terminal operation no data is processed, you can only call one intermediate or terminal operation on a given stream object. It makes the storing of a stream in a local variable useless.\n\nOne last word, some terminal operations do not need to call the intermediate operations of your stream. The reason why you should not do any side effect in an intermediate operations, there are situations where they will not be executed\n\u003c/details\u003e\n\n## 83. What list can you pass to a method that takes a List of Number `List\u003cNumber\u003e`?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nList\u003cNumber\u003e is certainly not List\u003cInteger\u003e even though Integer extends Number\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nEven if a Type U extends a type T, a `List\u003cU\u003e` does not extend the List\u003cT\u003e. The reason is that within the method that takes a list of numbers, you could add a float to that list but then if you pass a list of integers at runtime, you actually end up trying adding a float to a list of integers that would cause an exception.\n```java\nvoid process(List\u003cNumber\u003e list) {\n    list.add(3.14f); // Legal\n}\nList\u003cInteger\u003e ints = ...;\nprocess(ints); // COMPILE ERROR\n```\nOne last word, you could change your method and declare that it takes a list of question marks extends number(`List\u003c? extends Number\u003e`) and in that case you will be able to pass the list of Integer, Double and alike\n```java\nvoid process(List\u003c? extends Number\u003e list) {\n  ...\n}\nList\u003cInteger\u003e ints = ...;\nprocess(ints); // ok\n```\n\u003c/details\u003e\n\n## 84. What is a DeadLock?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA situation where a first thread holds the lock and needs the second one to carry on its task and the second thread is holding that second lock and is waiting for the first one to carry on with its task\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis situation is really very bad, most of the time your solution would be to reboot your application, so you absolutely want to avoid it. It can also occur with the second lock that is outside of your application like in your database for instance.\n\nOne last word, one word of sound to avoid that never expose your locks as a public elements. Always use private fields to store your locks, it will help you most of the time but not always unfortunately.\n\u003c/details\u003e\n\n## 85. How can you create an object instance of a given class using the Reflection API?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a pattern for that called `getDeclaredConstructor()` that gives you a reference on the empty constructor of this class and called `newInstance()` on it.\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe pattern that consists including `newInstance()` directly on the class itself has been deprecated in Java 9 mostly because it does not handle exceptions properly. If your class does not have an empty constructor then this pattern throws a `NoSuchMethodException` exception.\n\n```java\nclass Box {\n    Box(String s) {\n        // ...\n    }\n}\n\npublic static void main(String[] args) {\n  var c = Box.class;\n  var ctor = c.getDeclaredConstructor(String.class);\n  Box box = ctor.newInstance(\"Hello\");\n  c.newInstance(); // @Deprecated(since=\"9\")\n}\n```\n\nOne last word, you can also get a reference on the other constructors of your class by passing the parameters they take as classes to `getDeclaredConstructor()` method\n\u003c/details\u003e\n\n## 86. What is the difference between a Collection and a List?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA List is ordered, a Collection is not\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nOrdered means that the order in which you iterate over the elements is stable from one iteration to the other and corresponds to the order in which you added the elements to your list. It is the case for all Lists because that's the specification but it's not the case for `HashSet` for instance and because the HashSet is a collection not all collections have this behavior. Adding elements to a HashSet may change the iteration order all the other elements so it's not even stable from one iteration to the other.\n\nOne last word, the consequence is that you can access the elements of your list using an index that wouldn't make sense for our Sets.\n\u003c/details\u003e\n\n## 87. What is the difference between the `toList()` and collect `Collectors.toList()`?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nBoth are terminal operations of the stream API. `Collectors.toList()` producers an Arraylist and `toList()` produces a Non-modifiable List.\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe fact that `Collectors.toList()` producers on ArrayList is actually not specified but it's the case. There are cases where `toList()` is actually more efficient, in a case where you know how many elements your stream is going to process, `toList()` can create an array of the right size up front, where `Collectors.toList()` relies on the automatic growing of your ArrayList.\n\nOne last word, the streamed `toList()` method produces a non-modifiable list that accepts null values, not all non-modifiable lists accept them `List.of()` doesn't for instance.\n\u003c/details\u003e\n\n## 88. Can you compare Integers and Doubles with a Comparator of Numbers?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYes\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis is fine because what you are defining is a method that takes two parameters of type Number and it's fine to call it with any extension of number, actually you could use such a comparator to define the comparison between integers and floating point numbers for instance. Such a comparator is also okay to sort any list of integers of floating point numbers because all these types extended Number.\n\nOne last word, don't make your comparator a `Comparator\u003c? extends Number\u003e` because in that case you will not be able to call it with any other wrapper types. There is a good reason for that but that will be for another time\n\u003c/details\u003e\n\n## 89. How can you model the Concurrent tasks in Java?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nYou have two interfaces for that `Runnable` and `Callable`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nBoth have functional interfaces so you can implement them with lambdas, neither of them take any parameter.\n\n```java\nRunnable runnable = () -\u003e {doSomething();};\nCallable\u003cInteger\u003e callable = () -\u003e {return anInt();};\n```\n\nA Runnable does not return anything and does not throw any exception. A Callable on the other hand can return a value and throw an exception.\n\nRunnable is the only task you can pass to the constructor all the builder of a thread. Callable and Runnable can be passed through an `ExecutorService` or `StructuredTaskScope`.\n\n```java\nvar thread = Thread.ofVirtual().start(runnable);\nExecutorService service = ...;\nservice.submit(runnable);\nservice.submit(callable);\n```\n\nOne last word, when you submit a task to an ExecutiveService, you get a Future object in return something we will talk more about in the future precisely\n\u003c/details\u003e\n\n## 90. What is an Annotation?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn interface with methods on which you can define default values\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\n```java\n@Retention(RetentionPolicy.RUNTIME) // when\n@Target({\n  ElementType.FIELD,\n  ElementType.METHOD,\n  ElementType.CONSTRUCTOR\n}) // where\n@interface Range {\n  int begin() default 0;\n  int end();\n}\n```\n\nYou can define your own annotations easily with methods that may return default values, along with your annotation you need to define two things where you can add this annotation in your code and when you want to access it. There are currently 12 places where you can add an annotation for instance Fields, Classes, Methods or Parameters are among them then you can declare that you will need to use your annotation at runtime or only when your class is loaded or at compile time.\n\nOne last word, at Runtime you need to use the reflection API to get the annotations added to an element of your code, a technique used by many frameworks; Hibernate or SpringBoot just to name a few\n\u003c/details\u003e\n\n## 91. What is a `? extends T`?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nIt is a type called the wild card that has been created to extend a parameter's type by itself with an extension of its parameter\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nSuppose you have two types `T` and `U` and `U extends T`, a class parameterized on U does not extend the same class parameterized on T. `Box\u003cU\u003e does not extend Box\u003cT\u003e`\n\n```java\nimport java.util.List;\n\nstatic List\u003cLong\u003e convert(List\u003cNumber\u003e numbers) {\n    return numbers.stream()\n            .map(Number::longValue)\n            .toList();\n}\n\npublic static void main(String[] args) {\n  List\u003cDouble\u003e doubles = List.of();\n  \n  // DOES NOT COMPILE !!!\n  var longs = convert(doubles);\n  // Required type: List\u003cNumber\u003e\n  // Provided: List\u003cDouble\u003e\n}\n```\n\nLook at this convert method, it could accept a list of double. We can fix that with a list of question mark extends number `? extends Number` because list of double extends a list of question mark extend number.\n\n```java\nimport java.util.List;\n\nstatic List\u003cLong\u003e convert(List\u003c? extends Number\u003e numbers) {\n    return numbers.stream()\n            .map(Number::longValue)\n            .toList();\n}\n\npublic static void main(String[] args) {\n  List\u003cDouble\u003e doubles = List.of();\n  \n  // OK\n  var longs = convert(doubles);\n}\n```\n\nOne last word, this technique is extensively used in a collection framework and in along the world, comparators, consumers, predicates functions their old use wild cards.\n\n```java\npublic static \u003cT\u003e void sort(List\u003cT\u003e list, Comparator\u003c? super T\u003e c) {}\ndefault Consumer\u003cT\u003e andThen(Consumer\u003c? super T\u003e after) {}\ndefault Predicate\u003cT\u003e and(Predicate\u003c? super T\u003e other) {}\ndefault \u003cV\u003e Function\u003cV, R\u003e compose(Function\u003c? super V, ? extends T\u003e before) {}\n```\n\u003c/details\u003e\n\n## 92. What is a Constructor?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn element of a class that is called when an instance of this class is built\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nBe careful, because the `Constructor` is not a method. It does not have a written type and is not compiled in the same way. You can have several overloads of a constructor in a class, all they need is declare different parameters. Constructors can throw exceptions so if you want to do some validation to prevent corrected objects to be built, you can do that in your Constructor.\n\nOne last word, you can write compact constructors in Records which is a very nice and very simple syntax to write constructors that only do some validation, one more reason to use Records wherever you want\n\u003c/details\u003e\n\n## 93. What is a short-circuit method?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nSeveral methods from the Stream API are called short-circuit methods\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThese method may interrupt the conceptions of the elements of your source. There are 2 intermediate operations `limit()` and `takeWhile()` and 5 terminal operations of `allMatch()`, `anyMatch()` and `noneMatch()` plus `findFirst()` and `findAny()` because elements are processed lazily and one by one by the stream API, short-circuit operations can prevent some elements to be read from your source which may be really bad if you are doing some side effects in your intermediate operations.\n\nOne last word, doing side effects in a stream intermediate or terminal operations is always a bad idea. Don't do it\n\u003c/details\u003e\n\n## 94. What is an Atomic variable?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA wrapper on a primitive type or a reference with methods to mutate it in a thread safe and efficient way\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThe atomic variables are actually mappings of CPU operations also called `CASing` operations. CASing means `C`ompare `A`nd `S`wap. For instance, on atomic integer you can call `increment()` and `get()` that will increment the internal value and return it atomically. This operation is thread safe, it does not rely on synchronization which prevents thread contention.\n\nOne last word, atomic references are used to implement two thread safe structures from the collection framework; `ConcurrentSkipListMap` which is a Map and `ConcurrentSkipListSet` which is a Set, all these without any synchronization\n\u003c/details\u003e\n\n## 95. What is a Record?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nSomething you should use all the time\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nIt is a class that carries some immutable state declared along with its declaration. This state is called the Components of your record. A record cannot extend anything and cannot be extended but it can implement any interface. It cannot declare an instance field, static fields are okay and it can declare any method. The compiler gives you a constructor accesses that you can rewrite yourself and `toString()`, `equals()` and `hashCode()` for free. You can do some validation and deserialization, calls this constructor so no corrupt record in your application.\n\n```java\nrecord Range(int begin, int end) implements Serializable {\n    Range {\n        if (begin \u003e end) {\n            throw new IllegalArgumentException(\"...\");\n        }\n    }\n    int size() {\n        return end - begin;\n    }\n}\n```\n\nOne last word, use records wherever and whenever you can\n\u003c/details\u003e\n\n## 96. How can you invoke a method using the Reflection API?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is an `invoke()` method in the `Method.class`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nWe can get a specific method of a class with the `getMethod()` or `getDeclaredMethod()` of the class named Class. You need to pass the name of the method you want along with the types of its parameters. When you have a method object all you need to do is call the invoke() method passing first the object on which you want to invoke this method and then the arguments needed by this method. We can invoke a private method from outside the class by first calling the `setAccessible(true)` which removes the visibility checks.\n\n```java\nimport java.lang.reflect.Method;\n\npublic static void main(String[] args) {\n    var c = String.class;\n    Method indexOf = c.getMethod(\"indexOf\", String.class);\n    var message = \"Hello world\";\n    var index = indexOf.invoke(message, \"world\");\n    // output: 6\n}\n```\n\nOne last word, you also have another pattern to do that that uses the method and all class but that would be for another time oh\n\u003c/details\u003e\n\n## 97. What is a ConcurrentModificationException?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn exception raised when you modify your collection while iterating over it\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nBe careful because despite the name, it has nothing to do with concurrent programming. Removing elements from a collection while iterating over it is generally not a great idea. There is a `remove()` method on iterator that you can use just make sure that it is supported by your implementation if what you need is to remove elements using your predicate for instance, you can use the `removeIf()` method that does exactly that.\n\n```java\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic static void main(String[] args) {\n    var list = List.\u003cString\u003eof(\"1\", \"2\");\n    list = new ArrayList\u003c\u003e(list);\n    var iterator = list.iterator();\n    while (iterator.hasNext()) {\n        var s = iterator.next();\n        list.remove(s); // Exception in thread \"main\" java.util.ConcurrentModificationException\n        list.removeIf(String::isEmpty);\n        if (s.isEmpty()) {\n            iterator.remove();\n        }\n    }\n}\n```\n\nOne last word, some implementations of collection can be okay with removing elements while iterating over them, especially the concurrent ones like `ArrayBlockingQueue` or `ConcurrentLinkedQueue` so be sure to check the javadoc on this one\n\u003c/details\u003e\n\n## 98. What is a Collector?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nAn object provided by the Stream API that you can use to reduce streams using the `collect()` method\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nA collector is an implementation of the `Collector` interface, you can implement this interface yourself. You also have a collector's factory class with plenty of pre-built collectors that should cover most of your needs. You can do many things with collectors; you can create any sort of collections or maps, you can group your stream elements using keys and gather them in maps or you can join them in strings of characters. You even have collectors that can map, filter or flatMap the elements of your stream.\n\nOne last word, sometimes the stream API uses DownStream Collectors, this is a way to compose collectors but that will be for another time\n\u003c/details\u003e\n\n## 99. What is a Daemon Thread?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA Thread\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nWhen you create a thread, you can decide to set its daemon property to true, the JVM will start its shutdown sequence if it does not have any more non-daemon thread running. The thread main for instance that runs your main method is a non-demand thread so when you exit your main method the JVM shuts down. Non-Daeman thread keep your JVM alive that can be created in ExecutorServices for instance so don't forget to shut them down or your JVM will never shut down. 2 examples of the Daemon thread; the ones that are running your Garbage Collector or your Just In Time(`JIT`) compiler.\n\nOne last word, you can set the daemon property of a platform thread but a virtual thread is always a daemon thread\n\u003c/details\u003e\n\n## 100. What is a Race Condition?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nA race condition occurs when two threads are writing and reading the same variable at the same time\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis is a situation you need to take care of because it can put your application in an inconsistent state. Suppose that you are incrementing a simple counter, you first read its value increment it and write it back if two threads are doing that in two different calls of your CPU. They may be reading the same value and what you will see is one incrementation instead of two. To prevent race conditions, you need to guard your variables with synchronization or use atomic variables.\n\nOne last word, in Java, race conditions can only happen on the fields of your classes not on local variables. It can be different in other languages\n\u003c/details\u003e\n\n## 101. How can you check if a class is an extension of another?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThere is a method for that in a `Class.class`\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis method is called `isAssignableFrom()` you call it on a class instance which could represent an interface by the way and pass another class instance as an argument. `isAssignableFrom()` checked if an instance of the argument class you pass can be assigned to a variable of the type you are calling this method on, for instance you can check if you can assign a string object to a variable of type comparable with the following code.\n\n```java\npublic static void main(String[] args) {\n    var v = Comparable.class;\n    var checked = String.class;\n    boolean b = v.isAssignableFrom(checked);\n    // the compiler knows b is true!\n    // use it for types unknown\n    // at compile time\n}\n```\n\nOne last word, this is a method that you should use with types that you don't know at compile time, if you do then you probably don't need it\n\u003c/details\u003e\n\n## 102. What is the type `? super T`?\n\u003cdetails\u003e\n  \u003csummary\u003eShort Answer\u003c/summary\u003e\n\nThis type represents all the types that are super types of T\n\u003c/details\u003e\n\u003cdetails\u003e\n  \u003csummary\u003eLess Short Answer\u003c/summary\u003e\n\nThis is the kind of type you need when you need to define the type of an object that you consume. Suppose that you have a list of polygon objects, you know that all the objects of this list can be cast to the polygon type. Processing them with a consumer of shape will then be okay thus the forEach() method take","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsenocak%2Fcracking-the-java-coding-interview","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsenocak%2Fcracking-the-java-coding-interview","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsenocak%2Fcracking-the-java-coding-interview/lists"}