{"id":13401543,"url":"https://github.com/learning-zone/java-basics","last_synced_at":"2025-10-24T14:39:13.579Z","repository":{"id":38464078,"uuid":"174074983","full_name":"learning-zone/java-basics","owner":"learning-zone","description":"Java Basics ( Java-8 )","archived":false,"fork":false,"pushed_at":"2024-09-29T17:11:07.000Z","size":123208,"stargazers_count":1725,"open_issues_count":1,"forks_count":828,"subscribers_count":56,"default_branch":"master","last_synced_at":"2025-04-11T14:17:18.822Z","etag":null,"topics":["collections","design-pattern","hibernate","java","java-programs","java8","jdbc","jsp","multithreading","servlet"],"latest_commit_sha":null,"homepage":"https://learning-zone.github.io/java-basics/","language":"Java","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/learning-zone.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":"2019-03-06T05:03:23.000Z","updated_at":"2025-04-11T11:23:07.000Z","dependencies_parsed_at":"2023-12-31T06:36:53.647Z","dependency_job_id":"33f92069-023b-4569-ba29-0cbd933e5c9b","html_url":"https://github.com/learning-zone/java-basics","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fjava-basics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fjava-basics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fjava-basics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/learning-zone%2Fjava-basics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/learning-zone","download_url":"https://codeload.github.com/learning-zone/java-basics/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254264765,"owners_count":22041793,"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":["collections","design-pattern","hibernate","java","java-programs","java8","jdbc","jsp","multithreading","servlet"],"created_at":"2024-07-30T19:01:03.923Z","updated_at":"2025-10-24T14:39:13.485Z","avatar_url":"https://github.com/learning-zone.png","language":"Java","readme":"# Java Basics\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily ♡ welcome.*\n\n\u003cbr/\u003e\n\n## Related Topics\n\n* *[Multithreading](multithreading-questions.md)*\n* *[Collections](collections-questions.md)*\n* *[Java Database Connectivity (JDBC)](JDBC-questions.md)*\n* *[Java Programs](java-programs.md)*\n* *[Java String Methods](java-string-methods.md)*\n* *[Jakarta Server Pages (JSP)](jsp-questions.md)*\n* *[Servlets](servlets-questions.md)*\n* *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)*\n* *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)*\n* *[Hibernate](https://github.com/learning-zone/hibernate-basics)*\n* *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)*\n\n\u003cbr/\u003e\n\n## Table of Contents\n\n* [Introduction](#-1-introduction)\n* [Java Architecture](#-2-java-architecture)\n* [Java Data Types](#-3-java-data-types)\n* [Java Methods](#-4-java-methods)\n* [Java Functional programming](#-5-java-functional-programming)\n* [Java Lambda expressions](#-6-java-lambda-expressions)\n* [Java Classes](#-7-java-classes)\n* [Java Constructors](#-8-java-constructors)\n* [Java Array](#-9-java-array)\n* [Java Strings](#-10-java-strings)\n* [Java Reflection](#-11-java-reflection)\n* [Java Streams](#-12-java-streams)\n* [Java Regular Expressions](#-13-java-regular-expressions)\n* [Java File Handling](#-14-java-file-handling)\n* [Java Exceptions](#-15-java-exceptions)\n* [Java Inheritance](#-16-java-inheritance)\n* [Java Method Overriding](#-17-java-method-overriding)\n* [Java Polymorphism](#-18-java-polymorphism)\n* [Java Abstraction](#-19-java-abstraction)\n* [Java Interfaces](#-20-java-interfaces)\n* [Java Encapsulation](#-21-java-encapsulation)\n* [Java Generics](#-22-java-generics)\n* [Miscellaneous](#-23-miscellaneous)\n\n\u003cbr/\u003e\n\n## # 1. INTRODUCTION\n\n\u003cbr/\u003e\n\n## Q. What are the important features of Java 8 release?\n\n* Interface methods by default;\n* Lambda expressions;\n* Functional interfaces;\n* References to methods and constructors;\n* Repeatable annotations\n* Annotations on data types;\n* Reflection for method parameters;\n* Stream API for working with collections;\n* Parallel sorting of arrays;\n* New API for working with dates and times;\n* New JavaScript Nashorn Engine ;\n* Added several new classes for thread safe operation;\n* Added a new API for `Calendar`and `Locale`;\n* Added support for Unicode 6.2.0 ;\n* Added a standard class for working with Base64 ;\n* Added support for unsigned arithmetic;\n* Improved constructor `java.lang.String(byte[], *)` and method performance `java.lang.String.getBytes()`;\n* A new implementation `AccessController.doPrivileged` that allows you to set a subset of privileges without having to check all * other access levels;\n* Password-based algorithms have become more robust;\n* Added support for SSL / TLS Server Name Indication (NSI) in JSSE Server ;\n* Improved keystore (KeyStore);\n* Added SHA-224 algorithm;\n* Removed JDBC Bridge - ODBC;\n* PermGen is removed , the method for storing meta-data of classes is changed;\n* Ability to create profiles for the Java SE platform, which include not the entire platform, but some part of it;\n* Tools\n    * Added utility `jjs` for using JavaScript Nashorn;\n    * The command `java` can run JavaFX applications;\n    * Added utility `jdeps` for analyzing .class files.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Nashorn?\n\n**Nashorn** is a JavaScript engine developed in Java by Oracle. Designed to provide the ability to embed JavaScript code in Java applications. Compared to Rhino , which is supported by the Mozilla Foundation, Nashorn provides 2 to 10 times better performance, as it compiles code and transfers bytecode to the Java virtual machine directly in memory. Nashorn can compile JavaScript code and generate Java classes that are loaded with a special loader. It is also possible to call Java code directly from JavaScript.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is jjs?\n\n`jjs` - This is a command line utility that allows you to execute JavaScript programs directly in the console.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. In Java, How many ways you can take input from the console?\n\nIn Java, there are three different ways for reading input from the user in the command line environment ( console ).\n\n**1. Using Buffered Reader Class:**\n\nThis method is used by wrapping the System.in ( standard input stream ) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.\n\n```java\n/**\n * Buffered Reader Class\n */\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class Test {\n    public static void main(String[] args) throws IOException {\n        // Enter data using BufferReader\n        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n\n        // Reading data using readLine\n        String name = reader.readLine();\n\n        // Printing the read line\n        System.out.println(name);\n    }\n}\n```\n\n**2. Using Scanner Class:**\n\nThe main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line.\n\n```java\n/**\n * Scanner Class\n */\nimport java.util.Scanner;\n\nclass GetInputFromUser {\n    public static void main(String args[]) {\n        // Using Scanner for Getting Input from User\n        Scanner in = new Scanner(System.in);\n\n        String s = in.nextLine();\n        System.out.println(\"You entered string \" + s);\n\n        int a = in.nextInt();\n        System.out.println(\"You entered integer \" + a);\n\n        float b = in.nextFloat();\n        System.out.println(\"You entered float \" + b);\n    }\n}\n```  \n\n**3. Using Console Class:**\n\nIt has been becoming a preferred way for reading user\\'s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used ( like System.out.printf() ).\n\n```java\n/**\n * Console Class\n */\npublic class Sample {\n    public static void main(String[] args) {\n        // Using Console to input data from user\n        String name = System.console().readLine();\n        System.out.println(name);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of using javap?\n\nThe **javap** command displays information about the fields, constructors and methods present in a class file. The javap command ( also known as the Java Disassembler ) disassembles one or more class files.\n\n ```java\n /**\n  * Java Disassembler\n  */\nclass Simple {\n    public static void main(String args[]) {\n        System.out.println(\"Hello World\");\n    }\n}\n```\n\n```cmd\ncmd\u003e javap Simple.class  \n```\n\nOutput\n\n```java\nCompiled from \".java\"  \nclass Simple {  \n  Simple();  \n  public static void main(java.lang.String[]);  \n}  \n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain the expression `System.out::println`?\n\nThe specified expression illustrates passing a reference to a static method of a `println()`class `System.out`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Tell us about parallel processing in Java 8?\n\nStreams can be sequential and parallel. Operations on sequential streams are performed in one processor thread, on parallel streams - using several processor threads. Parallel streams use the shared stream `ForkJoinPool`through the static `ForkJoinPool.commonPool()`method. In this case, if the environment is not multi-core, then the stream will be executed as sequential. In fact, the use of parallel streams is reduced to the fact that the data in the streams will be divided into parts, each part is processed on a separate processor core, and in the end these parts are connected, and final operations are performed on them.\n\nYou can also use the `parallelStream()`interface method to create a parallel stream from the collection `Collection`.\n\nTo make a regular sequential stream parallel, you must call the `Stream`method on the object `parallel()`. The method `isParallel()`allows you to find out if the stream is parallel.\n\nUsing, methods `parallel()`and `sequential()`it is possible to determine which operations can be parallel, and which only sequential. You can also make a parallel stream from any sequential stream and vice versa:\n\n```java\ncollection\n  .stream ()\n  .peek ( ... ) // operation is sequential\n  .parallel ()\n  .map ( ... ) // the operation can be performed in parallel,\n  .sequential ()\n  .reduce ( ... ) // operation is sequential again\n```\n\nAs a rule, elements are transferred to the stream in the same order in which they are defined in the data source. When working with parallel streams, the system preserves the sequence of elements. An exception is a method `forEach()`that can output elements in random order. And in order to maintain the order, it is necessary to apply the method `forEachOrdered()`.\n\n* Criteria that may affect performance in parallel streams:\n* Data size - the more data, the more difficult it is to separate the data first, and then combine them.\n* The number of processor cores. Theoretically, the more cores in a computer, the faster the program will work. If the machine has one core, it makes no sense to use parallel threads.\n* The simpler the data structure the stream works with, the faster operations will occur. For example, data from is `ArrayList`easy to use, since the structure of this collection assumes a sequence of unrelated data. But a type collection  `LinkedList`is not the best option, since in a sequential list all the elements are connected with previous / next. And such  data is difficult to parallelize.\n* Operations with primitive types will be faster than with class objects.\n* It is highly recommended that you do not use parallel streams for any long operations (for example, network connections),  since all parallel streams work with one `ForkJoinPool`, such long operations can stop all parallel streams in the JVM due to  the lack of available threads in the pool, etc. e. parallel streams should be used only for short operations where the count  goes for milliseconds, but not for those where the count can go for seconds and minutes;\n* Saving order in parallel streams increases execution costs, and if order is not important, it is possible to disable its  saving and thereby increase productivity by using an intermediate operation `unordered()`:\n\n```java\ncollection.parallelStream ()\n    .sorted ()\n    .unordered ()\n    .collect ( Collectors . toList ());\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 2. JAVA ARCHITECTURE\n\n\u003cbr/\u003e\n\n## Q. What is JVM and is it platform independent?\n\nJava Virtual Machine (JVM) is a specification that provides runtime environment in which java bytecode(.class files) can be executed. The JVM is the platform. The JVM acts as a \"virtual\" machine or processor. Java\\'s platform independence consists mostly of its Java Virtual Machine (JVM). JVM makes this possible because it is aware of the specific instruction lengths and other particularities of the platform (Operating System).\n\nThe JVM is not platform independent. Java Virtual Machine (JVM) provides the environment to execute the java file(. Class file). So at the end it's depends on kernel and kernel is differ from OS (Operating System) to OS. The JVM is used to both translate the bytecode into the machine language for a particular computer and actually execute the corresponding machine-language instructions as well.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is JIT compiler in Java?\n\nThe Just-In-Time (JIT) compiler is a component of the runtime environment that improves the performance of Java applications by compiling bytecodes to native machine code at run time.\n\nJava programs consists of classes, which contain platform-neutral bytecodes that can be interpreted by a JVM on many different computer architectures. At run time, the JVM loads the class files, determines the semantics of each individual bytecode, and performs the appropriate computation. The additional processor and memory usage during interpretation means that a Java application performs more slowly than a native application. The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time. The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Classloader in Java?\n\nThe **Java ClassLoader** is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source.\n\n**Types of ClassLoader:**\n\n**1. Bootstrap Class Loader**:\n\nIt loads standard JDK class files from rt.jar and other core classes. It loads class files from jre/lib/rt.jar. For example, java.lang package class.\n\n**2. Extensions Class Loader**:\n\nIt loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` directory or any other directory as java.ext.dirs.\n\n**3. System Class Loader**:\n\nIt loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Java Compiler is stored in JDK, JRE or JVM?\n\n**1. JDK**:\n\nJava Development Kit is the core component of Java Environment and provides all the tools, executables and binaries required to compile, debug and execute a Java Program.\n\n**2. JVM**:\n\nJVM is responsible for converting Byte code to the machine specific code. JVM is also platform dependent and provides core java functions like memory management, garbage collection, security etc. JVM is customizable and we can use java options to customize it, for example allocating minimum and maximum memory to JVM. JVM is called virtual because it provides an interface that does not depend on the underlying operating system and machine hardware.\n\n**2. JRE**:\n\nJava Runtime Environment provides a platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/jdk.jpg\" alt=\"Java Compiler\" width=\"500px\"  /\u003e\n\u003c/p\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between Heap and Stack Memory in java?\n\n**1. Java Heap Space:**  \n\nJava Heap space is used by java runtime to allocate memory to **Objects** and **JRE classes**. Whenever we create any object, it\\'s always created in the Heap space.\n\nGarbage Collection runs on the heap memory to free the memory used by objects that doesn\\'t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.\n\n**2. Java Stack Memory:**\n\nStack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack.\n\nStack memory is always referenced in LIFO ( Last-In-First-Out ) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method.\n\nAs soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory.\n\n**Difference:**  \n\n|Parameter\t       |Stack Memory\t               |Heap Space                       |\n|------------------|-----------------------------|-----------------------------------|\n|Application\t   |Stack is used in parts, one at a time during execution of a thread|\tThe entire application uses Heap space during runtime|\n|Size\t           |Stack has size limits depending upon OS and is usually smaller then Heap|There is no size limit on Heap|\n|Storage\t       |Stores only primitive variables and references to objects that are created in Heap Space|All the newly created objects are stored here|\n|Order\t           |It is accessed using Last-in First-out (LIFO) memory allocation system|\tThis memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.|\n|Life\t           |Stack memory only exists as long as the current method is running|Heap space exists as long as the application runs|\n|Efficiency\t       |Comparatively much faster to allocate when compared to heap| Slower to allocate when compared to stack|\n|Allocation/Deallocation| This Memory is automatically allocated and deallocated when a method is called and returned respectively|Heap space is allocated when new objects are created and deallocated by Gargabe Collector when they are no longer referenced |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How many types of memory areas are allocated by JVM?\n\nJVM is a program which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM perform some particular types of operations:\n\n* Loading of code\n* Verification of code\n* Executing the code\n* It provide run-time environment to the users\n\n**Types of Memory areas allocated by the JVM:**  \n\n**1. Classloader**: Classloader is a subsystem of JVM that is used to load class files.\n\n**2. Class(Method) Area**: Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.\n\n**3. Heap**: It is the runtime data area in which objects are allocated.  \n\n**4. Stack**: Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread.\n\n**5. Program Counter Register**: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.  \n\n**6. Native Method Stack**: It contains all the native methods used in the application.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 3. JAVA DATA TYPES\n\n\u003cbr/\u003e\n\n## Q. What are autoboxing and unboxing?\n\nThe automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing.\n\n**Example:** Autoboxing\n\n```java\n/**\n * Autoboxing\n */\nclass BoxingExample {\n    public static void main(String args[]) {\n        int a = 50;\n        Integer a2 = new Integer(a); // Boxing\n        Integer a3 = 5; // Boxing\n\n        System.out.println(a2 + \" \" + a3);\n    }\n} \n```\n\n**Example:** Unboxing\n\n```java\n/**\n * Unboxing\n */\nclass UnboxingExample {\n    public static void main(String args[]) {\n        Integer i = new Integer(50);\n        int a = i;\n\n        System.out.println(a);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between transient and volatile variable in Java?\n\n**1. Transient:**\n\nThe transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type.\n\n**Example:**\n\n```java\n/**\n * Transient\n */\npublic transient int limit = 55;   // will not persist\npublic int b;   // will persist\n```\n\n**2. Volatile:**\n\nThe volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization.\n\n**Example:**\n\n```java\n/**\n * Volatile\n */\npublic class MyRunnable implements Runnable {\n   private volatile boolean active;\n   public void run() {\n      active = true;\n      while (active) {    \n      }\n   }\n   public void stop() {\n      active = false;  \n   }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are assertions in Java?\n\nAn assertion allows testing the correctness of any assumptions that have been made in the program. Assertion is achieved using the assert statement in Java.\n\nWhile executing assertion, it is believed to be true. If it fails, JVM throws an error named `AssertionError`. It is mainly used for testing purposes during development.\n\nThe assert statement is used with a Boolean expression and can be written in two different ways.\n\n```java\n// First way \nassert expression;\n\n// Second way\nassert expression1 : expression2;\n```\n\n**Example:**\n\n```java\n/**\n * Assertions\n */\npublic class Example {\n    public static void main(String[] args) {\n        int age = 14;\n        assert age \u003c= 18 : \"Cannot Vote\";\n        System.out.println(\"The voter's age is \" + age);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the final variable, final class, and final blank variable?\n\n**1. Final Variable:**\n\nFinal variables are nothing but constants. We cannot change the value of a final variable once it is initialized.\n\n**Example:**\n\n```java\n/**\n * Final Variable\n */\nclass Demo {\n\n    final int MAX_VALUE = 99;\n\n    void myMethod() {\n        MAX_VALUE = 101;\n    }\n\n    public static void main(String args[]) {\n        Demo obj = new Demo();\n        obj.myMethod();\n    }\n}\n```\n\nOutput\n\n```java\nException in thread \"main\" java.lang.Error: Unresolved compilation problem: \n\tThe final field Demo.MAX_VALUE cannot be assigned\n\n\tat beginnersbook.com.Demo.myMethod(Details.java:6)\n\tat beginnersbook.com.Demo.main(Details.java:10)\n```\n\n**2. Blank final variable:**\n\nA final variable that is not initialized at the time of declaration is known as blank final variable. We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error ( Error: `variable MAX_VALUE might not have been initialized` ).\n\n**Example:**\n\n```java\n/**\n * Blank final variable\n */\nclass Demo {\n    // Blank final variable\n    final int MAX_VALUE;\n\n    Demo() {\n        // It must be initialized in constructor\n        MAX_VALUE = 100;\n    }\n\n    void myMethod() {\n        System.out.println(MAX_VALUE);\n    }\n\n    public static void main(String args[]) {\n        Demo obj = new Demo();\n        obj.myMethod();\n    }\n}\n```\n\nOutput\n\n```java\n100\n```\n\n**3. Final Method:**\n\nA final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it.\n\n**Example:**\n\n```java\n/**\n * Final Method\n */\nclass XYZ {\n    final void demo() {\n        System.out.println(\"XYZ Class Method\");\n    }\n}\n\nclass ABC extends XYZ {\n    void demo() {\n        System.out.println(\"ABC Class Method\");\n    }\n\n    public static void main(String args[]) {\n        ABC obj = new ABC();\n        obj.demo();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a compile time constant in Java?\n\nIf a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant.\n\n**Compile time constant must be:**  \n\n* Declared final\n* Primitive or String\n* Initialized within declaration\n* Initialized with constant expression\n\nThey are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time.\n\n```java\nprivate final int x = 10;\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the different access specifiers available in java?\n\n* access specifiers/modifiers helps to restrict the scope of a class, constructor, variable, method, or data member.\n* There are four types of access modifiers available in java:\n    1. `default` – No keyword required, when a class, constructor,variable, method, or data member declared without any access specifier then it is having default access scope i.e. accessible only within the same package.\n    2. `private` - when declared as a private , access scope is limited within the enclosing class.\n    3. `protected` - when declared as protocted, access scope is limited to enclosing classes, subclasses from same package as well as other packages.\n    4. `public` - when declared as public, accessible everywhere in the program.\n\n```java\n    ... /* data member variables */\n    String firstName=\"Pradeep\";     /* default scope */\n    protected isValid=true;         /* protected scope */\n    private String otp=\"AB0392\";    /* private scope */\n    public int id = 12334;          /* public scope */\n    ...\n    ... /* data member functions */\n    String getFirstName(){ return this.firstName; } /* default scope */\n    protected boolean getStatus(){this.isValid;}    /* protected scope */\n    private void generateOtp(){                     /* private scope */\n        this.otp = this.hashCode() \u003c\u003c 16;\n    };    \n    public int getId(){ return this.id; }           /* public scope */\n    ...\n    .../* inner classes */\n    class A{}            /* default scope */\n    protected class B{}  /* protected scope */\n    private class C{}    /* private scope */\n    public class D{}     /* public scope */\n    ...\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 4. JAVA METHODS\n\n\u003cbr/\u003e\n\n## Q. Can you have virtual functions in Java?\n\nIn Java, all non-static methods are by default **virtual functions**. Only methods marked with the keyword `final`, which cannot be overridden, along with `private methods`, which are not inherited, are non-virtual.\n\n**Example:** Virtual function with Interface\n\n```java\n/**\n * The function applyBrakes() is virtual because\n * functions in interfaces are designed to be overridden.\n **/\ninterface Bicycle {\n    void applyBrakes();\n}\n\nclass ACMEBicycle implements Bicycle {\n    public void applyBrakes() { // Here we implement applyBrakes()\n        System.out.println(\"Brakes applied\"); // function\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a native method?\n\nA native method is a Java method (either an instance method or a class method) whose implementation is also written in another programming language such as C/C++. Moreover, a method marked as native cannot have a body and should end with a semicolon:\n\n**Main.java:**\n\n```java\npublic class Main {\n    public native int intMethod(int i);\n\n    public static void main(String[] args) {\n        System.loadLibrary(\"Main\");\n        System.out.println(new Main().intMethod(2));\n    }\n}\n```\n\n**Main.c:**\n\n```c\n#include \u003cjni.h\u003e\n#include \"Main.h\"\n\nJNIEXPORT jint JNICALL Java_Main_intMethod(\n    JNIEnv *env, jobject obj, jint i) {\n  return i * i;\n}\n```\n\n**Compile and Run:**  \n\n```java\njavac Main.java\njavah -jni Main\ngcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \\\n  -I${JAVA_HOME}/include/linux Main.c\njava -Djava.library.path=. Main\n```\n\nOutput\n\n```java\n4\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the restrictions that are applied to the Java static methods?\n\nIf a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class.\n\nThere are a few restrictions imposed on a static method\n\n* The static method cannot use non-static data member or invoke non-static method directly.\n* The `this` and `super` cannot be used in static context.\n* The static method can access only static type data ( static type instance variable ).\n* There is no need to create an object of the class to invoke the static method.\n* A static method cannot be overridden in a subclass\n\n**Example:**\n\n```java\n/**\n * Static Methods\n */\nclass Parent {\n    static void display() {\n        System.out.println(\"Super class\");\n    }\n}\n\npublic class Example extends Parent {\n    void display()  // trying to override display() {\n       System.out.println(\"Sub class\");  \n    }\n\n    public static void main(String[] args) {\n        Parent obj = new Example();\n        obj.display();\n    }\n}\n```\n\nThis generates a compile time error. The output is as follows −\n\n```java\nExample.java:10: error: display() in Example cannot override display() in Parent\nvoid display()  // trying to override display()\n     ^\noverridden method is static\n\n1 error\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a lambda?\n\n What is the structure and features of using a lambda expression?\nA lambda is a set of instructions that can be separated into a separate variable and then repeatedly called in various places of the program.\n\nThe basis of the lambda expression is the _lambda operator_ , which represents the arrow `-\u003e`. This operator divides the lambda expression into two parts: the left side contains a list of expression parameters, and the right actually represents the body of the lambda expression, where all actions are performed.\n\nThe lambda expression is not executed by itself, but forms the implementation of the method defined in the functional interface. It is important that the functional interface should contain only one single method without implementation.\n\n```java\ninterface  Operationable {\n     int  calculate ( int  x , int  y );\n}\n\npublic  static  void main ( String [] args) {\n    Operationable operation = (x, y) - \u003e x + y;     \n    int result = operation.calculate ( 10 , 20 );\n    System.out.println (result); // 30 \n}\n```\n\nIn fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java.\n\n* _Deferred execution lambda expressions_ - it is defined once in one place of the program, it is called if necessary, any number of times and in any place of the program.\n\n* _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method:\n\n```javascript\noperation = ( int x, int y) - \u003e x + y;\n// When writing the lambda expression itself, the parameter type is allowed not to be specified: \n(x, y) - \u003e x + y;\n// If the method does not accept any parameters, then empty brackets are written, for example: \n() - \u003e  30  +  20 ;\n// If the method accepts only one parameter, then the brackets can be omitted: \nn - \u003e n * n;\n```\n\n* Trailing lambda expressions are not required to return any value.\n\n```java\ninterface  Printable {\n     void  print( String  s );\n}\n \npublic  static  void main ( String [] args) {\n    Printable printer = s - \u003e  System.out.println(s);\n    printer.print(\"Hello, world\");\n}\n\n// _ Block lambda - expressions_ are surrounded by curly braces . The modular lambda - expressions can be used inside nested blocks, loops, `design the if ` ` switch statement ', create variables, and so on . d . If you block a lambda - expression must return a value, it explicitly applies `statement return statement ' :\n\n\nOperationable operation = ( int x, int y) - \u003e {       \n    if (y ==  0 ) {\n        return  0 ;\n    }\n    else {\n        return x / y;\n    }\n};\n```\n\n* Passing a lambda expression as a method parameter\n\n```java\ninterface  Condition {\n     boolean  isAppropriate ( int  n );\n}\n\nprivate  static  int sum ( int [] numbers, Condition condition) {\n     int result =  0 ;\n    for ( int i : numbers) {\n         if (condition.isAppropriate(i)) {\n            result + = i;\n        }\n    }\n    return result;\n}\n\npublic  static  void main ( String [] args) {\n     System.out.println(sum ( new  int [] { 0 , 1 , 0 , 3 , 0 , 5 , 0 , 7 , 0 , 9 }, (n) - \u003e n ! =  0 ));\n} \n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What variables do lambda expressions have access to?\n\nAccess to external scope variables from a lambda expression is very similar to access from anonymous objects.\n\n* immutable ( effectively final - not necessarily marked as final) local variables;\n* class fields\n* static variables.\n\nThe default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a method reference?\n\nIf the method existing in the class already does everything that is necessary, then you can use the method reference mechanism (method reference) to directly pass this method. The result will be exactly the same as in the case of defining a lambda expression that calls this method.\n\n**Example:**\n\n```java\nprivate interface Measurable {\n   public int length(String string);\n}\n\npublic  static  void main ( String [] args) {\n   Measurable a =  String::length;\n   System.out.println(a.length(\"abc\"));\n}\n```\n\nMethod references are potentially more efficient than using lambda expressions. In addition, they provide the compiler with better information about the type, and if you can choose between using a reference to an existing method and using a lambda expression, you should always use a method reference.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What types of method references do you know?\n\n* on the static method;\n* per instance method;\n* to the constructor.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 5. JAVA FUNCTIONAL PROGRAMMING\n\n\u003cbr/\u003e\n\n## # 6. JAVA LAMBDA EXPRESSIONS\n\n\u003cbr/\u003e\n\n## # 7. JAVA CLASSES\n\n\u003cbr/\u003e\n\n## Q. What is difference between the Inner Class and Sub Class?\n\nNested Inner class can access any private instance variable of outer class. Like any other instance variable, we can have access modifier private, protected, public and default modifier.\n\n**Example:**\n\n```java\n/**\n * Inner Class\n */\nclass Outer { \n   class Inner { \n      public void show() { \n           System.out.println(\"In a nested class method\"); \n      } \n   } \n} \nclass Main { \n   public static void main(String[] args) { \n       Outer.Inner in = new Outer().new Inner(); \n       in.show(); \n   } \n} \n```\n\nA subclass is class which inherits a method or methods from a superclass.\n\n**Example:**\n\n```java\n/**\n * Sub Class \n */\nclass Car {\n    //...\n}\n \nclass HybridCar extends Car {\n    //...\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Distinguish between static loading and dynamic class loading?\n\n**1. Static Class Loading:**\n\nCreating objects and instance using `new` keyword is known as static class loading. The retrieval of class definition and instantiation of the object is done at compile time.\n\n**Example:**\n\n```java\n/**\n * Static Class Loading \n */\nclass TestClass {\n  public static void main(String args[]) {\n      TestClass tc = new TestClass();\n  }\n}\n```\n\n**2. Dynamic Class Loading:**\n\nLoading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time.\n\n**Example:**\n\n```java\n/**\n * Dynamic Class Loading \n */\nClass.forName (String className);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of the Runtime class and System class?\n\n**1. Runtime Class:**\n\nThe **java.lang.Runtime** class is a subclass of Object class, provide access to the Java runtime system. The runtime information like memory availability, invoking the garbage collector, etc.\n\n**Example:**\n\n```java\n/**\n * Runtime Class\n */\npublic class RuntimeTest \n{\n    static class Message extends Thread {\n        public void run() {\n            System.out.println(\" Exit\");\n        }\n    }\n\n    public static void main(String[] args) {\n        try {\n            Runtime.getRuntime().addShutdownHook(new Message());\n            System.out.println(\" Program Started...\");\n            System.out.println(\" Wait for 5 seconds...\");\n            Thread.sleep(5000);\n            System.out.println(\" Program Ended...\");\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\n**2. System Class:**\n\nThe purpose of the System class is to provide access to system resources. It contains accessibility to standard input, standart output, error output streams, current time in millis, terminating the application, etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the ways to instantiate the Class class?\n\n**1. Using new keyword:**\n\n```java\nMyObject object = new MyObject();\n```\n\n**2. Using Class.forName():**\n\n```java\nMyObject object = (MyObject) Class.forName(\"subin.rnd.MyObject\").newInstance();\n```\n\n**3. Using clone():**\n\n```java\nMyObject anotherObject = new MyObject();\nMyObject object = (MyObject) anotherObject.clone();\n```\n\n**4. Using object deserialization:**\n\n```java\nObjectInputStream inStream = new ObjectInputStream(anInputStream );\nMyObject object = (MyObject) inStream.readObject();\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is immutable object?\n\nImmutable objects are objects that don\\'t change. A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field.\n\n**Creating an Immutable Object:**  \n\n* Do not add any setter method\n* Declare all fields final and private\n* If a field is a mutable object create defensive copies of it for getter methods\n* If a mutable object passed to the constructor must be assigned to a field create a defensive copy of it\n* Don\\'t allow subclasses to override methods.\n\n```java\n/**\n * Immutable Object\n */\npublic class DateContainer {\n    private final Date date;\n\n    public DateContainer() {\n        this.date = new Date();\n    }\n\n    public Date getDate() {\n        return new Date(date.getTime());\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can we create an immutable class in Java?\n\nImmutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable.\n\n**Rules to create immutable classes:**  \n\n* The class must be declared as final\n* Data members in the class must be declared as final\n* A parameterized constructor\n* Getter method for all the variables in it\n* No setters\n\n```java\n/**\n * Immutable Class\n */\npublic final class Employee {\n\n    final String pancardNumber;\n\n    public Employee(String pancardNumber) {\n        this.pancardNumber = pancardNumber;\n    }\n\n    public String getPancardNumber() {\n        return pancardNumber;\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How bootstrap class loader works in java?\n\nBootstrap ClassLoader is repsonsible for loading standard JDK classs files from **rt.jar** and it is parent of all class loaders in java. There are three types of built-in ClassLoader in Java:\n\n**1. Bootstrap Class Loader:** It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes  \n\n**2. Extensions Class Loader:** It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.  \n\n**3. System Class Loader:** It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.\n\n```java\n/**\n * ClassLoader\n */\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\npublic class ClassLoaderTest {\n\n    public static void main(String args[]) {\n        try {\n            // printing ClassLoader of this class\n            System.out.println(\"ClassLoader : \" + ClassLoaderTest.class.getClassLoader());\n\n            // trying to explicitly load this class again using Extension class loader\n            Class.forName(\"Explicitly load class\", true, ClassLoaderTest.class.getClassLoader().getParent());\n        } catch (ClassNotFoundException ex) {\n            Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can we create a object of a class without using new operator?\n\nDifferent ways to create an object in Java\n\n* **Using new Keyword:**\n\n```java\nclass ObjectCreationExample{\n\tString Owner;\n}\npublic class MainClass {\n\tpublic static void main(String[] args) {\n\t\t// Here we are creating Object of JBT using new keyword\n\t\tObjectCreationExample obj = new ObjectCreationExample();\n\t}\n}\n```\n\n* **Using New Instance (Reflection)**\n\n```java\nclass CreateObjectClass {\n\tstatic int j = 10;\n\tCreateObjectClass() {\n\t\ti = j++;\n\t}\n\tint i;\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Value of i :\" + i;\n\t}\n}\n\nclass MainClass {\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tClass cls = Class.forName(\"CreateObjectClass\");\n\t\t\tCreateObjectClass obj = (CreateObjectClass) cls.newInstance();\n\t\t\tCreateObjectClass obj1 = (CreateObjectClass) cls.newInstance();\n\t\t\tSystem.out.println(obj);\n\t\t\tSystem.out.println(obj1);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (InstantiationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n```\n\n* **Using Clone:**\n\n```java\n class CreateObjectWithClone implements Cloneable {\n\t@Override\n\tprotected Object clone() throws CloneNotSupportedException {\n\t\treturn super.clone();\n\t}\n\tint i;\n\tstatic int j = 10;\n\tCreateObjectWithClone() {\n\t\ti = j++;\n\t}\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Value of i :\" + i;\n\t}\n}\n\nclass MainClass {\n\tpublic static void main(String[] args) {\n\t\tCreateObjectWithClone obj1 = new CreateObjectWithClone();\n\t\tSystem.out.println(obj1);\n\t\ttry {\n\t\t\tCreateObjectWithClone obj2 = (CreateObjectWithClone) obj1.clone();\n\t\t\tSystem.out.println(obj2);\n\t\t} catch (CloneNotSupportedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}\n```\n\n* **Using ClassLoader**\n\n```java\nclass CreateObjectWithClassLoader {\n\tstatic int j = 10;\n\tCreateObjectWithClassLoader() {\n\t\ti = j++;\n\t}\n\tint i;\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Value of i :\" + i;\n\t}\n}\n\npublic class MainClass {\n\tpublic static void main(String[] args) {\n\t\tCreateObjectWithClassLoader obj = null;\n\t\ttry {\n\t\t\tobj = (CreateObjectWithClassLoader) new MainClass().getClass()\n\t\t\t\t\t.getClassLoader().loadClass(\"CreateObjectWithClassLoader\").newInstance();\n        // Fully qualified classname should be used.\n\t\t} catch (InstantiationException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (ClassNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tSystem.out.println(obj);\n\t}\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are methods of Object Class?\n\nThe Object class is the parent class of all the classes in java by default.\n\n\u003ctable class=\"alt\"\u003e\n\u003ctbody\u003e\u003ctr\u003e\u003cth\u003eMethod\u003c/th\u003e\u003cth\u003eDescription\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final Class getClass()\u003c/td\u003e\u003ctd\u003ereturns the Class class object of this object. The Class class can further be used to get the metadata of this class.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic int hashCode()\u003c/td\u003e\u003ctd\u003e returns the hashcode number for this object.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic boolean equals(Object obj)\u003c/td\u003e\u003ctd\u003e compares the given object to this object.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eprotected Object clone() throws CloneNotSupportedException\u003c/td\u003e\u003ctd\u003e creates and returns the exact copy (clone) of this object.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic String toString()\u003c/td\u003e\u003ctd\u003e returns the string representation of this object.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final void notify()\u003c/td\u003e\u003ctd\u003e wakes up single thread, waiting on this object\\'s monitor.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final void notifyAll()\u003c/td\u003e\u003ctd\u003e wakes up all the threads, waiting on this object\\'s monitor.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final void wait(long timeout)throws InterruptedException\u003c/td\u003e\u003ctd\u003e causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final void wait(long timeout,int nanos)throws InterruptedException\u003c/td\u003e\u003ctd\u003ecauses the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003epublic final void wait()throws InterruptedException\u003c/td\u003e\u003ctd\u003e causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eprotected void finalize()throws Throwable\u003c/td\u003e\u003ctd\u003e is invoked by the garbage collector before object is being garbage collected.\u003c/td\u003e\u003c/tr\u003e\n\u003c/tbody\u003e\u003c/table\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Optional\n\nAn optional value `Optional`is a container for an object that may or may not contain a value `null`. Such a wrapper is a convenient means of prevention `NullPointerException`, as has some higher-order functions, eliminating the need for repeating `if null/notNullchecks`:\n\n```java\nOptional \u003c String \u003e optional =  Optional.of( \" hello \" );\n\noptional.isPresent(); // true \noptional.ifPresent(s -\u003e  System.out.println(s.length())); // 5 \noptional.get(); // \"hello\" \noptional.orElse( \" ops ... \" ); // \"hello\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 8. JAVA CONSTRUCTORS\n\n\u003cbr/\u003e\n\n## Q. How many types of constructors are used in Java?\n\nIn Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.\n\n**Types of Java Constructors:**  \n\n* Default Constructor (or) no-arg Constructor\n* Parameterized Constructor\n\n**Example:** Default Constructor (or) no-arg constructor\n\n```java\n/**\n * Default Constructor\n */\npublic class Car {\n    Car() {\n        System.out.println(\"Default Constructor of Car class called\");\n    }\n\n    public static void main(String args[]) {\n        // Calling the default constructor\n        Car c = new Car();\n    }\n}\n```\n\nOutput\n\n```java\nDefault Constructor of Car class called\n```\n\n**Example:** Parameterized Constructor\n\n```java\n/**\n * Parameterized Constructor\n */\npublic class Car {\n    String carColor;\n\n    Car(String carColor) {\n        this.carColor = carColor;\n    }\n\n    public void display() {\n        System.out.println(\"Color of the Car is : \" + carColor);\n    }\n\n    public static void main(String args[]) {\n        // Calling the parameterized constructor\n        Car c = new Car(\"Blue\");\n        c.display();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can constructor chaining be done using this keyword?\n\nJava constructor chaining is a method of calling one constructor with the help of another while considering the present object. It can be done in 2 ways –\n\n* **Within same class**: It can be done using `this()` keyword for constructors in the same class.\n* **From base class**: By using `super()` keyword to call a constructor from the base class.\n\n```java\n/**\n * Constructor Chaining \n * within same class Using this() keyword \n */\nclass Temp \n{ \n    // default constructor 1 \n    // default constructor will call another constructor \n    // using this keyword from same class \n    Temp() { \n        // calls constructor 2 \n        this(5); \n        System.out.println(\"The Default constructor\"); \n    } \n  \n    // parameterized constructor 2 \n    Temp(int x) { \n        // calls constructor 3 \n        this(10, 20); \n        System.out.println(x); \n    } \n  \n    // parameterized constructor 3 \n    Temp(int x, int y) { \n        System.out.println(10 + 20); \n    } \n  \n    public static void main(String args[]) { \n        // invokes default constructor first \n        new Temp(); \n    } \n} \n```\n\nOuput:\n\n```java\n30\n10\nThe Default constructor\n```\n\n```java\n/**\n * Constructor Chaining to \n * other class using super() keyword \n */\nclass Base \n{ \n    String name; \n  \n    // constructor 1 \n    Base() { \n        this(\"\"); \n        System.out.println(\"No-argument constructor of base class\"); \n    } \n  \n    // constructor 2 \n    Base(String name) { \n        this.name = name; \n        System.out.println(\"Calling parameterized constructor of base\"); \n    } \n} \n  \nclass Derived extends Base \n{ \n    // constructor 3 \n    Derived() { \n        System.out.println(\"No-argument constructor of derived\"); \n    } \n  \n    // parameterized constructor 4 \n    Derived(String name) { \n        // invokes base class constructor 2 \n        super(name); \n        System.out.println(\"Calling parameterized constructor of derived\"); \n    } \n  \n    public static void main(String args[]) { \n        // calls parameterized constructor 4 \n        Derived obj = new Derived(\"test\"); \n  \n        // Calls No-argument constructor \n        // Derived obj = new Derived(); \n    } \n} \n```\n\nOutput:\n\n```java\nCalling parameterized constructor of base\nCalling parameterized constructor of derived\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a private constructor?\n\n* A constructor with private access specifier/modifier is private constructor. \n* It is only accessible inside the class by its data members(instance fields,methods,inner classes) and in static block.\n* Private Constructor be used in **Internal Constructor chaining and Singleton class design pattern**\n\n```java\npublic class MyClass {\n    \n    static{\n        System.out.println(\"outer static block..\");\n        new MyClass();\n    }\n    \n    private MyInner in;\n    \n    {\n        System.out.println(\"outer instance block..\");\n        //new MyClass(); //private constructor accessbile but bad practive will cause infinite loop \n    }\n    \n    private MyClass(){\n        System.out.println(\"outer private constructor..\");\n    }\n    \n    public void getInner(){\n        System.out.println(\"outer data member function..\");\n        \n        new MyInner();\n    }\n\n    private static class MyInner{\n        {\n            System.out.println(\"inner instance block..\");\n            new MyClass();\n        }\n        \n        MyInner(){\n            System.out.println(\"inner constructor..\");\n        }\n    }\n    \n    \n    public static void main(String args[]) {\n        System.out.println(\"static main method..\");\n        MyClass m=new MyClass();\n        m.getInner();\n    }\n}\n\nclass Visitor{\n    {\n        new MyClass();//gives compilation error as MyClass() has private access in MyClass\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 9. JAVA ARRAY\n\n\u003cbr/\u003e\n\n## Q. What is copyonwritearraylist in java?\n\n* `CopyOnWriteArrayList` class implements `List` and `RandomAccess` interfaces and thus provide all functionalities available in `ArrayList` class.\n* Using `CopyOnWriteArrayList` is costly for update operations, because each mutation creates a cloned copy of underlying array and add/update element to it.\n* It is `thread-safe` version of ArrayList. Each thread accessing the list sees its own version of snapshot of backing array created while initializing the iterator for this list.\n* Because it gets `snapshot` of underlying array while creating iterator, it does not throw `ConcurrentModificationException`.\n* Mutation operations on iterators (remove, set, and add) are not supported. These methods throw `UnsupportedOperationException`.\n* CopyOnWriteArrayList is a concurrent `replacement for a synchronized List` and offers better concurrency when iterations outnumber mutations.\n* It `allows duplicate elements and heterogeneous Objects` (use generics to get compile time errors).\n* Because it creates a new copy of array everytime iterator is created, `performance is slower than ArrayList`.\n* We can prefer to use CopyOnWriteArrayList over normal ArrayList in following cases:\n\n    - When list is to be used in concurrent environemnt.\n    - Iterations outnumber the mutation operations.\n    - Iterators must have snapshot version of list at the time when they were created.\n    - We don\\'t want to synchronize the thread access programatically.\n\n```java\n        import java.util.concurrent.CopyOnWriteArrayList;\n        CopyOnWriteArrayList\u003cString\u003e copyOnWriteArrayList = new CopyOnWriteArrayList\u003cString\u003e();\n        copyOnWriteArrayList.add(\"captain america\");\n        Iterator it = copyOnWriteArrayList.iterator();  //iterator creates separate snapshot\n        copyOnWriteArrayList.add(\"iron man\");           //doesn't throw ConcurrentModificationException\n        while(it.hasNext())\n            System.out.println(it.next());              // prints captain america only , since add operation is after returning iterator\n\n        it = copyOnWriteArrayList.iterator();           //fresh snapshot\n        while(it.hasNext())\n            System.out.println(it.next());              // prints captain america and iron man, \n        \n        it = copyOnWriteArrayList.iterator();           //fresh snapshot\n        while(it.hasNext()){\n            System.out.println(it.next());\n            it.remove();                                //mutable operation 'remove' not allowed ,throws UnsupportedOperationException                            \n        }\n\n        ArrayList\u003cString\u003e list = new ArrayList\u003cString\u003e();\n        list.add(\"A\");\n        Iterator ait = list.iterator();\n        list.add(\"B\");                                      // immediately throws  ConcurrentModificationException\n        while(ait.hasNext())\n            System.out.println(ait.next()); \n        \n        ait = list.iterator();\n        while(ait.hasNext()){\n            System.out.println(ait.next());\n            ait.remove();                                //mutable operation 'remove' allowed without any exception                            \n        }\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 10. JAVA STRINGS\n\n\u003cbr/\u003e\n\n## Q. What is the difference between creating String as new() and literal?\n\nWhen you create String object using `new()` operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. \"Java\", it may return an existing object from String pool ( a cache of String object in Perm gen space, which is now moved to heap space in recent Java release ), if it\\'s already exists. Otherwise it will create a new string object and put in string pool for future re-use.\n\n**Example:**\n\n```java\n/**\n * String literal\n */\nString a = \"abc\"; \nString b = \"abc\";\nSystem.out.println(a == b);  // true\n\n/**\n * Using new()\n */\nString c = new String(\"abc\");\nString d = new String(\"abc\");\nSystem.out.println(c == d);  // false\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between String, StringBuffer and StringBuilder?\n\n**1. Mutability Difference:**\n\n`String` is **immutable**, if you try to alter their values, another object gets created, whereas `StringBuffer` and `StringBuilder` are **mutable** so they can change their values.\n\n**2. Thread-Safety Difference:**\n\nThe difference between `StringBuffer` and `StringBuilder` is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.\n\n**Example:**  \n\n```java\n/**\n * StringBuffer\n */\npublic class BufferTest {\n    public static void main(String[] args) {\n        StringBuffer buffer = new StringBuffer(\"Hello\");\n        buffer.append(\" World\");\n        System.out.println(buffer);\n    }\n}\n```\n\n**Example:**  \n\n```java\n/**\n * StringBuilder\n */\npublic class BuilderTest {\n    public static void main(String[] args) {\n        StringBuilder builder = new StringBuilder(\"Hello\");\n        builder.append(\" World\");\n        System.out.println(builder);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why string is immutable in java?\n\nThe string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client\\'s action would affect all another client.\n\nSince string is immutable it can safely share between many threads and avoid any synchronization issues in java.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is Java String Pool?\n\nString Pool in java is a pool of Strings stored in Java Heap Memory. String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String.\n\nWhen we use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. However using **new** operator, we force String class to create a new String object in heap space.\n\n```java\n/**\n * String Pool\n */\npublic class StringPool {\n\n    public static void main(String[] args) {\n        String s1 = \"Java\";\n        String s2 = \"Java\";\n        String s3 = new String(\"Java\");\n\n        System.out.println(\"s1 == s2 :\" + (s1 == s2)); // true\n        System.out.println(\"s1 == s3 :\" + (s1 == s3)); // false\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between String, StringBuilder and StringBuffer?\n\nString is `immutable`, if you try to alter their values, another object gets created, whereas `StringBuffer` and `StringBuilder` are mutable so they can change their values.  \n\nThe difference between `StringBuffer` and `StringBuilder` is that `StringBuffer` is thread-safe. So when the application needs to be run only in a single thread then it is better to use `StringBuilder`. `StringBuilder` is more efficient than StringBuffer.\n\n**Situations:**\n\n* If your string is not going to change use a String class because a `String` object is immutable.\n* If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a `StringBuilder` is good enough.\n* If your string can change, and will be accessed from multiple threads, use a `StringBuffer` because `StringBuffer` is synchronous so you have thread-safety.  \n\n**Example:**\n\n```java\nclass StringExample {\n\n    // Concatenates to String \n    public static void concat1(String s1) { \n        s1 = s1 + \"World\"; \n    } \n  \n    // Concatenates to StringBuilder \n    public static void concat2(StringBuilder s2) { \n        s2.append(\"World\"); \n    } \n  \n    // Concatenates to StringBuffer \n    public static void concat3(StringBuffer s3) { \n        s3.append(\"World\"); \n    } \n  \n    public static void main(String[] args) { \n        String s1 = \"Hello\"; \n        concat1(s1);  // s1 is not changed \n        System.out.println(\"String: \" + s1); \n  \n        StringBuilder s2 = new StringBuilder(\"Hello\"); \n        concat2(s2); // s2 is changed \n        System.out.println(\"StringBuilder: \" + s2); \n  \n        StringBuffer s3 = new StringBuffer(\"Hello\"); \n        concat3(s3); // s3 is changed \n        System.out.println(\"StringBuffer: \" + s3); \n    } \n} \n```\n\nOutput  \n\n```java\nString: Hello\nStringBuilder: World\nStringBuffer: World\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is StringJoiner?\n\nThe class is StringJoinerused to create a sequence of strings separated by a separator with the ability to append a prefix and suffix to the resulting string:\n\n```java\nStringJoiner joiner =  new  StringJoiner ( \" . \" , \" Prefix- \" , \" -suffix \" );\nfor ( String s :  \" Hello the brave world \" . split ( \"  \" )) {\n    , joiner, . add (s);\n}\nSystem.out.println(joiner); // prefix-Hello.the.brave.world-suffix\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 11. JAVA REFLECTION\n\n\u003cbr/\u003e\n\n## Q. What is Java Reflection API?\n\nReflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at **runtime**.\n\nThe **java.lang.Class** class provides many methods that can be used to get metadata, examine and change the run time behavior of a class. There are 3 ways to get the instance of Class class.\n\n* forName() method of Class class\n* getClass() method of Object class\n* the .class syntax\n\n**1. forName() method:**  \n\n* is used to load the class dynamically.\n* returns the instance of Class class.\n* It should be used if you know the fully qualified name of class.This cannot be used for primitive types.\n\n```java\n/**\n * forName()\n */\nclass Simple {\n}\n\nclass Test {\n    public static void main(String args[]) {\n        Class c = Class.forName(\"Simple\");\n        System.out.println(c.getName());\n    }\n}\n```\n\nOutput\n\n```java\nSimple\n```\n\n**2. getClass() method:**  \n\nIt returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.\n\n```java\n/**\n * getClass\n */\nclass Simple {\n}\n\nclass Test {\n    void printName(Object obj) {\n        Class c = obj.getClass();\n        System.out.println(c.getName());\n    }\n\n    public static void main(String args[]) {\n        Simple s = new Simple();\n        Test t = new Test();\n        t.printName(s);\n    }\n} \n```\n\nOutput\n\n```java\nSimple\n```\n\n**3. The .class syntax:**  \n\nIf a type is available but there is no instance then it is possible to obtain a Class by appending \".class\" to the name of the type. It can be used for primitive data type also.\n\n```java\n/**\n * .class Syntax\n */\nclass Test {  \n  public static void main(String args[]) {  \n   Class c = boolean.class;   \n   System.out.println(c.getName());  \n  \n   Class c2 = Test.class;   \n   System.out.println(c2.getName());  \n }  \n}  \n```\n\nOutput\n\n```java\nboolean\nTest\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 12. JAVA STREAMS\n\n\u003cbr/\u003e\n\n## Q. What is Stream?\n\nAn interface `java.util.Stream` is a sequence of elements on which various operations can be performed.\n\nOperations on streams can be either intermediate (intermediate) or final (terminal) . Final operations return a result of a certain type, and intermediate operations return the same stream. Thus, you can build chains of several operations on the same stream.\n\nA stream can have any number of calls to intermediate operations and the last call to the final operation. At the same time, all intermediate operations are performed lazily and until the final operation is called, no actions actually happen (similar to creating an object `Thread`or `Runnable`, without a call `start()`).\n\nStreams are created based on sources of some, for example, classes from `java.util.Collection`.\n\nAssociative arrays (maps), for example `HashMap`, are not supported.\n\nOperations on streams can be performed both sequentially and in parallel.\n\nStreams cannot be reused. As soon as some final operation has been called, the flow is closed.\n\nIn addition to the universal object, there are special types of streams to work with primitive data types `int`, `long`and `double`: `IntStream`, `LongStream`and `DoubleStream`. These primitive streams work just like regular object streams, but with the following differences:\n\n* use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`;\n* support additional end operations `sum()`, `average()`, `mapToObj()`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the ways to create a stream?\n\n* Using collection:\n\n```java\nStream \u003c String \u003e fromCollection =  Arrays.asList ( \" x \" , \" y \" , \" z \" ).stream ();\n```\n\n* Using  set of values:\n\n```java\nStream \u003c String \u003e fromValues =  Stream.of( \" x \" , \" y \" , \" z \" );\n```\n\n* Using Array\n\n```java\nStream \u003c String \u003e fromArray =  Arrays.stream( new  String [] { \" x \" , \" y \" , \" z \" });\n```\n\n* Using file (each line in the file will be a separate element in the stream):\n\n```java\nStream \u003c String \u003e fromFile =  Files.lines( Paths.get(\" input.txt \"));\n```\n\n* From the line:\n\n```java\nIntStream fromString =  \" 0123456789 \" . chars ();\n```\n\n* With the help of `Stream.builder()`:\n\n```java\nStream \u003c String \u003e fromBuilder =  Stream.builder().add (\" z \").add(\" y \").add(\" z \").build ();\n```\n\n* Using `Stream.iterate()(infinite)`:\n\n```java\nStream \u003c Integer \u003e fromIterate =  Stream.iterate ( 1 , n - \u003e n +  1 );\n```\n\n* Using `Stream.generate()(infinite)`:\n\n```java\nStream \u003c String \u003e fromGenerate =  Stream.generate(() -\u003e  \" 0 \" );\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between `Collection` and `Stream`?\n\nCollections allow you to work with elements separately, while streams do not allow this, but instead provides the ability to perform functions on data as one.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the method `collect()`for streams for?\n\nA method `collect()`is the final operation that is used to represent the result as a collection or some other data structure.\n\n`collect()`accepts an input that contains four stages:\n\n* **supplier** — initialization of the battery,\n* **accumulator** — processing of each element,\n* **combiner** — connection of two accumulators in parallel execution,\n* **[finisher]** —a non-mandatory method of the last processing of the accumulator. \n\nIn Java 8, the class `Collectors` implements several common collectors:  \n\n* `toList()`, `toCollection()`, `toSet()`- present stream in the form of a list, collection or set;\n* `toConcurrentMap()`, `toMap()`- allow you to convert the stream to `Map`;\n* `averagingInt()`, `averagingDouble()`, `averagingLong()`- return the average value;\n* `summingInt()`, `summingDouble()`, `summingLong()`- returns the sum;\n* `summarizingInt()`, `summarizingDouble()`, `summarizingLong()`- return SummaryStatisticswith different values of the aggregate;\n* `partitioningBy()`- divides the collection into two parts according to the condition and returns them as `Map\u003cBoolean, List\u003e`;\n* `groupingBy()`- divides the collection into several parts and returns `Map\u003cN, List\u003cT\u003e\u003e`;\n* `mapping()`- Additional value conversions for complex Collectors.\n\nThere is also the possibility of creating your own collector through `Collector.of()`:\n\n```java\nCollector \u003c String , a List \u003c String \u003e , a List \u003c String \u003e \u003e toList =  Collector.of (\n    ArrayList :: new ,\n    List :: add,\n    (l1, l2) -\u003e {l1 . addAll (l2); return l1; }\n);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Why do streams use `forEach()`and `forEachOrdered()` methods?\n\n* `forEach()` applies a function to each stream object; ordering in parallel execution is not guaranteed;\n* `forEachOrdered()` applies a function to each stream object while maintaining the order of the elements.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream?\n\nThe method `map()`is an intermediate operation, which transforms each element of the stream in a specified way.\n\n`mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`, returns the corresponding numerical stream (ie the stream of numerical primitives):\n```java\nStream \n    .of ( \" 12 \" , \" 22 \" , \" 4 \" , \" 444 \" , \" 123 \" )\n    .mapToInt ( Integer :: parseInt)\n    .toArray (); // [12, 22, 4, 444, 123]\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the purpose of `filter()` method in streams?\n\nThe method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the use of `limit()` method in streams?\n\nThe method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the use of `sorted()` method in streams?\n\nThe method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator.\n\nThe order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`?\n\nThe method `flatMap()` is similar to map, but can create several from one element. Thus, each object will be converted to zero, one or more other objects supported by the stream. The most obvious way to use this operation is to convert container elements using functions that return containers.\n\n```java\nStream \n    .of ( \" Hello \" , \" world! \" )\n    .flatMap ((p) -\u003e  Arrays.stream (p . split ( \" , \" )))\n    .toArray ( String [] :: new ); // [\"H\", \"e\", \"l\", \"l\", \"o\", \"w\", \"o\", \"r\", \"l\", \"d\", \"!\"]\n```\n\n`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the final methods of working with streams you know?\n\n* `findFirst()` returns the first element\n* `findAny()` returns any suitable item\n* `collect()` presentation of results in the form of collections and other data structures\n* `count()` returns the number of elements\n* `anyMatch()`returns trueif the condition is satisfied for at least one element\n* `noneMatch()`returns trueif the condition is not satisfied for any element\n* `allMatch()`returns trueif the condition is satisfied for all elements\n* `min()`returns the minimum element, using as a condition Comparator\n* `max()`returns the maximum element, using as a condition Comparator\n* `forEach()` applies a function to each object (order is not guaranteed in parallel execution)\n* `forEachOrdered()` applies a function to each object while preserving the order of elements\n* `toArray()` returns an array of values\n* `reduce()`allows you to perform aggregate functions and return a single result.\n* `sum()` returns the sum of all numbers\n* `average()` returns the arithmetic mean of all numbers.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What intermediate methods of working with streams do you know?\n\n* `filter()` filters records, returning only records matching the condition;\n* `skip()` allows you to skip a certain number of elements at the beginning;\n* `distinct()`returns a stream without duplicates (for a method `equals()`);\n* `map()` converts each element;\n* `peek()` returns the same stream, applying a function to each element;\n* `limit()` allows you to limit the selection to a certain number of first elements;\n* `sorted()`allows you to sort values ​​either in natural order or by setting `Comparator`;\n* `mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`return stream numeric primitives;\n* `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- similar to `map()`, but can create a single element more.\n\nFor numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n#### Q. Explain Difference between Collection API and Stream API?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 13. JAVA REGULAR EXPRESSIONS\n\n\u003cbr/\u003e\n\n## Q. Name some classes present in java.util.regex package?\n\nThe Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings.\n\n**Regular Expression Package:**  \n\n* MatchResult interface\n* Matcher class\n* Pattern class\n* PatternSyntaxException class\n\n**Example:**\n\n```java\n/**\n * Regular Expression\n */\nimport java.util.regex.*;\n\npublic class Index {\n    public static void main(String args[]) {\n\n        // Pattern, String\n        boolean b = Pattern.matches(\".s\", \"as\");\n\n        System.out.println(\"Match: \" + b);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 14. JAVA FILE HANDLING\n\n\u003cbr/\u003e\n\n## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?\n\n`BufferedInputStream` and `BufferedOutputStream` class is used for buffering an input and output stream while reading and writing, respectively. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.\n\n**Example:**\n\n```java\n/**\n * BufferedInputStream\n */\nimport java.io.BufferedInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\npublic class BufferedInputStreamExample {\n\n    public static void main(String[] args) {\n        File file = new File(\"file.txt\");\n        FileInputStream fileInputStream = null;\n        BufferedInputStream bufferedInputStream = null;\n\n        try {\n            fileInputStream = new FileInputStream(file);\n            bufferedInputStream = new BufferedInputStream(fileInputStream);\n            // Create buffer\n            byte[] buffer = new byte[1024];\n            int bytesRead = 0;\n            while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {\n                System.out.println(new String(buffer, 0, bytesRead));\n            }\n        } catch (IOException e) {\n            e.printStackTrace();\n        } finally {\n            try {\n                if (fileInputStream != null) {\n                    fileInputStream.close();\n                }\n                if (bufferedInputStream != null) {\n                    bufferedInputStream.close();\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}\n```\n\nOutput\n\n```java\nThis is an example of reading data from file\n```\n\n**Example:**  \n\n```java\n/**\n * BufferedOutputStream\n */\nimport java.io.BufferedOutputStream;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n\npublic class BufferedOutputStreamExample {\n\n    public static void main(String[] args) {\n        File file = new File(\"outfile.txt\");\n        FileOutputStream fileOutputStream = null;\n        BufferedOutputStream bufferedOutputStream = null;\n        try {\n            fileOutputStream = new FileOutputStream(file);\n            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);\n            bufferedOutputStream.write(\"This is an example of writing data to a file\".getBytes());\n            bufferedOutputStream.flush();\n\n        } catch (IOException e) {\n            e.printStackTrace();\n        } finally {\n            try {\n                if (fileOutputStream != null) {\n                    fileOutputStream.close();\n                }\n                if (bufferedOutputStream != null) {\n                    bufferedOutputStream.close();\n                }\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}\n```\n\nOutput\n\n```java\nThis is an example of writing data to a file\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to set the Permissions to a file in Java?\n\nJava 7 has introduced PosixFilePermission Enum and **java.nio.file.Files** includes a method setPosixFilePermissions( Path path, `Set\u003cPosixFilePermission\u003e perms` ) that can be used to set file permissions easily.\n\n**Example:**\n\n```java\n/**\n * FilePermissions \n */\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.nio.file.attribute.PosixFilePermission;\nimport java.util.HashSet;\nimport java.util.Set;\n\npublic class FilePermissions {\n\n    public static void main(String[] args) throws IOException {\n        File file = new File(\"/Users/file.txt\");\n\n        // change permission to 777 for all the users\n        // no option for group and others\n        file.setExecutable(true, false);\n        file.setReadable(true, false);\n        file.setWritable(true, false);\n\n        // using PosixFilePermission to set file permissions 777\n        Set\u003cPosixFilePermission\u003e perms = new HashSet\u003cPosixFilePermission\u003e();\n\n        // add owners permission\n        perms.add(PosixFilePermission.OWNER_READ);\n        perms.add(PosixFilePermission.OWNER_WRITE);\n        perms.add(PosixFilePermission.OWNER_EXECUTE);\n\n        // add group permissions\n        perms.add(PosixFilePermission.GROUP_READ);\n        perms.add(PosixFilePermission.GROUP_WRITE);\n        perms.add(PosixFilePermission.GROUP_EXECUTE);\n\n        // add others permissions\n        perms.add(PosixFilePermission.OTHERS_READ);\n        perms.add(PosixFilePermission.OTHERS_WRITE);\n        perms.add(PosixFilePermission.OTHERS_EXECUTE);\n\n        Files.setPosixFilePermissions(Paths.get(\"/Users/run.sh\"), perms);\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Give the hierarchy of InputStream and OutputStream classes?\n\nA stream can be defined as a sequence of data. There are two kinds of Streams −\n\n* **InPutStream** − The InputStream is used to read data from a source.\n* **OutPutStream** − The OutputStream is used for writing data to a destination.\n\n**1. Byte Streams:**\n\nJava byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream.\n\n**Example:**\n\n```java\n/**\n * Byte Streams\n */\nimport java.io.*;\n\npublic class CopyFile {\n\n    public static void main(String args[]) throws IOException {\n        FileInputStream in = null;\n        FileOutputStream out = null;\n\n        try {\n            in = new FileInputStream(\"input.txt\");\n            out = new FileOutputStream(\"output.txt\");\n\n            int c;\n            while ((c = in.read()) != -1) {\n                out.write(c);\n            }\n        } finally {\n            if (in != null) {\n                in.close();\n            }\n            if (out != null) {\n                out.close();\n            }\n        }\n    }\n}\n```\n\n**2. Character Streams:**\n\nJava Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter.\n\n**Example:**\n\n```java\n/**\n * Character Streams\n */\nimport java.io.*;\n\npublic class CopyFile {\n\n    public static void main(String args[]) throws IOException {\n        FileReader in = null;\n        FileWriter out = null;\n\n        try {\n            in = new FileReader(\"input.txt\");\n            out = new FileWriter(\"output.txt\");\n\n            int c;\n            while ((c = in.read()) != -1) {\n                out.write(c);\n            }\n        } finally {\n            if (in != null) {\n                in.close();\n            }\n            if (out != null) {\n                out.close();\n            }\n        }\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How serialization works in java?\n\nSerialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.\n\n**Example:**\n\n```java\n/**\n* Serialization and Deserialization\n*/\nimport java.io.*;\n\nclass Employee implements Serializable {\n    private static final long serialversionUID = 129348938L;\n    transient int a;\n    static int b;\n    String name;\n    int age;\n\n    // Default constructor\n    public Employee(String name, int age, int a, int b) {\n        this.name = name;\n        this.age = age;\n        this.a = a;\n        this.b = b;\n    }\n}\n\npublic class SerialExample {\n\n    public static void printdata(Employee object1) {\n        System.out.println(\"name = \" + object1.name);\n        System.out.println(\"age = \" + object1.age);\n        System.out.println(\"a = \" + object1.a);\n        System.out.println(\"b = \" + object1.b);\n    }\n\n    public static void main(String[] args) {\n        Employee object = new Employee(\"ab\", 20, 2, 1000);\n        String filename = \"file.txt\";\n\n        // Serialization\n        try {\n            // Saving of object in a file\n            FileOutputStream file = new FileOutputStream(filename);\n            ObjectOutputStream out = new ObjectOutputStream(file);\n\n            // Method for serialization of object\n            out.writeObject(object);\n\n            out.close();\n            file.close();\n\n            System.out.println(\"Object has been serialized\\n\"\n                    + \"Data before Deserialization.\");\n            printdata(object);\n            // value of static variable changed\n            object.b = 2000;\n        } catch (IOException ex) {\n            System.out.println(\"IOException is caught\");\n        }\n\n        object = null;\n\n        // Deserialization\n        try {\n            // Reading the object from a file\n            FileInputStream file = new FileInputStream(filename);\n            ObjectInputStream in = new ObjectInputStream(file);\n\n            // Method for deserialization of object\n            object = (Employee) in.readObject();\n\n            in.close();\n            file.close();\n            System.out.println(\"Object has been deserialized\\n\"\n                    + \"Data after Deserialization.\");\n            printdata(object);\n            System.out.println(\"z = \" + object1.z);\n        } catch (IOException ex) {\n            System.out.println(\"IOException is caught\");\n        } catch (ClassNotFoundException ex) {\n            System.out.println(\"ClassNotFoundException is caught\");\n        }\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 15. JAVA EXCEPTIONS\n\n\u003cbr/\u003e\n\n## Q. What are the types of Exceptions?\n\nException is an error event that can happen during the execution of a program and disrupts its normal flow.\n\n**1. Checked Exception**:\n\nThe classes which directly inherit **Throwable class** except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.  \n\n**2. Unchecked Exception**:\n\nThe classes which inherit **RuntimeException** are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.  \n\n**3. Error**:\n\nError is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain hierarchy of Java Exception classes?\n\nThe **java.lang.Throwable** class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/exception.png\" alt=\"Exception in Java\" width=\"500px\" /\u003e\n\u003c/p\u003e\n\n**Example:**\n\n```java\n/**\n * Exception classes\n */\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic class CustomExceptionExample {\n\n\tpublic static void main(String[] args) throws MyException {\n\t\ttry {\n\t\t\tprocessFile(\"file.txt\");\n\t\t} catch (MyException e) {\n\t\t\tprocessErrorCodes(e);\n\t\t}\n\t}\n\n\tprivate static void processErrorCodes(MyException e) throws MyException {\n\t\tswitch(e.getErrorCode()){\n\t\t  case \"BAD_FILE_TYPE\":\n\t\t\t System.out.println(\"Bad File Type, notify user\");\n\t\t\t throw e;\n\t\t  case \"FILE_NOT_FOUND_EXCEPTION\":\n\t\t\t System.out.println(\"File Not Found, notify user\");\n\t\t\t throw e;\n\t\t  case \"FILE_CLOSE_EXCEPTION\":\n\t\t\t System.out.println(\"File Close failed, just log it.\");\n\t\t\t break;\n\t\t  default:\n\t\t\t System.out.println(\"Unknown exception occured,\" +e.getMessage());\n\t\t\t e.printStackTrace();\n\t\t}\n\t}\n\n\tprivate static void processFile(String file) throws MyException {\t\t\n\t\tInputStream fis = null;\n\t\ttry {\n\t\t\tfis = new FileInputStream(file);\n\t\t} catch (FileNotFoundException e) {\n\t\t\tthrow new MyException(e.getMessage(),\"FILE_NOT_FOUND_EXCEPTION\");\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif(fis !=null) fis.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new MyException(e.getMessage(),\"FILE_CLOSE_EXCEPTION\");\n\t\t\t}\n\t\t}\n\t}\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between Error and Exception?\n\n|BASIS FOR COMPARISON\t|ERROR                                    |EXCEPTION                               |\n|-----------------------|-----------------------------------------|----------------------------------------|\n|Basic\t               |An error is caused due to lack of system resources.|An exception is caused because of the code.|\n|Recovery\t            |An error is irrecoverable.\t            |An exception is recoverable.|\n|Keywords\t            |There is no means to handle an error by the program code.|\tExceptions are handled using three keywords \"try\", \"catch\", and \"throw\".|\n|Consequences           |As the error is detected the program will terminated abnormally.|As an exception is detected, it is thrown and caught by the \"throw\" and \"catch\" keywords correspondingly.|\n|Types\t               |Errors are classified as unchecked type.|Exceptions are classified as checked or unchecked type.|\n|Package\t               |In Java, errors are defined \"java.lang.Error\" package.|In Java, an exceptions are defined in\"java.lang.Exception\".|\n|Example\t               |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Explain about Exception Propagation?\n\nAn exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.\n\n**Example:**\n\n```java\n/**\n * Exception Propagation\n */\nclass TestExceptionPropagation {\n\n    void method1() {\n        int data = 10 / 0; // generates an exception\n        System.out.println(data);\n    }\n\n    void method2() {\n        method1(); // doesn't catch the exception\n    }\n\n    void method3() { // method3 catches the exception\n        try {\n            method2();\n        } catch (Exception e) {\n            System.out.println(\"Exception is caught\");\n        }\n    }\n\n    public static void main(String args[]) {\n        TestExceptionPropagation obj = new TestExceptionPropagation();\n        obj.method3();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are different scenarios causing \"Exception in thread main\"?\n\nSome of the common main thread exception are as  follows:\n\n* **Exception in thread main java.lang.UnsupportedClassVersionError**: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.\n\n* **Exception in thread main java.lang.NoClassDefFoundError**: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.\n\n* **Exception in thread main java.lang.NoSuchMethodError: main**: This exception comes when you are trying to run a class that doesn\\'t have main method.\n\n* **Exception in thread \"main\" java.lang.ArithmeticException**: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the differences between throw and throws?\n\n**Throw** keyword is used in the method body to throw an exception, while **throws** is used in method signature to declare the exceptions that can occur in the statements present in the method.\n\n**Example:**\n\n```java\n/**\n * Throw in Java\n */\npublic class ThrowExample {\n    void checkAge(int age) {\n        if (age \u003c 18)\n            throw new ArithmeticException(\"Not Eligible for voting\");\n        else\n            System.out.println(\"Eligible for voting\");\n    }\n\n    public static void main(String args[]) {\n        ThrowExample obj = new ThrowExample();\n        obj.checkAge(13);\n        System.out.println(\"End Of Program\");\n    }\n}\n```\n\nOutput\n\n```java\nException in thread \"main\" java.lang.ArithmeticException: \nNot Eligible for voting\nat Example1.checkAge(Example1.java:4)\nat Example1.main(Example1.java:10)\n```\n\n**Example:**  \n\n```java\n/**\n * Throws in Java\n */\npublic class ThrowsExample {\n    int division(int a, int b) throws ArithmeticException {\n        int t = a / b;\n        return t;\n    }\n\n    public static void main(String args[]) {\n        ThrowsExample obj = new ThrowsExample();\n        try {\n            System.out.println(obj.division(15, 0));\n        } catch (ArithmeticException e) {\n            System.out.println(\"You shouldn't divide number by zero\");\n        }\n    }\n}\n```\n\nOutput\n\n```java\nYou shouldn\\'t divide number by zero\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. While overriding a method can you throw another exception or broader exception?\n\nIf a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. This is because of polymorphism.\n\n**Example:**\n\n```java\nclass A {\n   public void message() throws IOException {..}\n}\n\nclass B extends A {\n   @Override\n   public void message() throws SocketException {..} // allowed\n\n   @Override\n   public void message() throws SQLException {..} // NOT allowed\n\n   public static void main(String args[]) {\n        A a = new B();\n        try {\n            a.message();\n        } catch (IOException ex) {\n            // forced to catch this by the compiler\n        }\n   }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is checked, unchecked exception and errors?\n\n**1. Checked Exception**:\n\n* These are the classes that extend **Throwable** except **RuntimeException** and **Error**.\n* They are also known as compile time exceptions because they are checked at **compile time**, meaning the compiler forces us to either handle them with try/catch or indicate in the function signature that it **throws** them and forcing us to deal with them in the caller.\n* They are programmatically recoverable problems which are caused by unexpected conditions outside the control of the code (e.g. database down, file I/O error, wrong input, etc).\n\n**Example:** **IOException, SQLException** etc.\n\n```java\nimport java.io.*; \n  \nclass Main { \n    public static void main(String[] args) { \n        FileReader file = new FileReader(\"C:\\\\assets\\\\file.txt\"); \n        BufferedReader fileInput = new BufferedReader(file); \n          \n        for (int counter = 0; counter \u003c 3; counter++)  \n            System.out.println(fileInput.readLine()); \n          \n        fileInput.close(); \n    } \n} \n```\n\noutput:\n\n```java\nException in thread \"main\" java.lang.RuntimeException: Uncompilable source code - \nunreported exception java.io.FileNotFoundException; must be caught or declared to be \nthrown\n    at Main.main(Main.java:5)\n```\n\nAfter adding IOException\n\n```java\nimport java.io.*; \n  \nclass Main { \n    public static void main(String[] args) throws IOException { \n        FileReader file = new FileReader(\"C:\\\\assets\\\\file.txt\"); \n        BufferedReader fileInput = new BufferedReader(file); \n           \n        for (int counter = 0; counter \u003c 3; counter++)  \n            System.out.println(fileInput.readLine()); \n          \n        fileInput.close(); \n    } \n} \n```\n\noutput:\n\n```java\nOutput: First three lines of file “C:\\assets\\file.txt”\n```\n\n**2. Unchecked Exception**:\n\n* The classes that extend **RuntimeException** are known as unchecked exceptions.\n* Unchecked exceptions are not checked at compile-time, but rather at **runtime**, hence the name.\n* They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration.\n\n**Example:**  **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc.\n\n```java\nclass Main { \n   public static void main(String args[]) { \n      int x = 0; \n      int y = 10; \n      int z = y/x; \n  } \n} \n```\n\nOutput:\n\n```java\nException in thread \"main\" java.lang.ArithmeticException: / by zero\n    at Main.main(Main.java:5)\nJava Result: 1\n```\n\n**3. Error**:\n\n**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**.\nExample: **OutOfMemoryError, VirtualMachineError, AssertionError** etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between ClassNotFoundException and NoClassDefFoundError?\n\n`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios.\n\n`ClassNotFoundException` is an exception that occurs when you try to load a class at run time using `Class.forName()` or `loadClass()` methods and mentioned classes are not found in the classpath.\n\n`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 16. JAVA INHERITANCE\n\n\u003cbr/\u003e\n\n## Q. What is the difference between aggregation and composition?\n\n**1. Aggregation:**\n\nWe call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object.\n\n**Example:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes\n\n```java\n/**\n * Aggregation\n */\npublic class Organization {\n   private List employees;\n}\n\npublic class Person {\n   private String name;   \n}\n```\n\n**2. Composition:**\n\nWe use the term composition to refer to relationships whose objects **don\\'t have an independent lifecycle**, and if the parent object is deleted, all child objects will also be deleted.\n\n**Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes.\n\n```java\n/**\n * Composition\n */\npublic class Car {\n    //final will make sure engine is initialized\n    private final Engine engine;  \n       \n    public Car(){\n       engine  = new Engine();\n    }\n}\n\nclass Engine {\n    private String type;\n}\n```\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"assets/aggregation.png\" alt=\"Aggregation\" width=\"400px\" /\u003e\n\u003c/p\u003e\n\n\u003ctable class=\"alt\"\u003e\n\u003ctbody\u003e\u003ctr\u003e\u003cth\u003eAggregation\u003c/th\u003e\u003cth\u003eComposition\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAggregation is a weak Association.\u003c/td\u003e\u003ctd\u003eComposition is a strong Association.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eClass can exist independently without owner.\u003c/td\u003e\u003ctd\u003eClass can not meaningfully exist without owner.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eHave their own Life Time.\u003c/td\u003e\u003ctd\u003eLife Time depends on the Owner.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eA uses B.\u003c/td\u003e\u003ctd\u003eA owns B.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eChild is not owned by 1 owner.\u003c/td\u003e\u003ctd\u003eChild can have only 1 owner.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eHas-A relationship. A has B.\u003c/td\u003e\u003ctd\u003ePart-Of relationship. B is part of A.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eDenoted by a empty diamond in UML.\u003c/td\u003e\u003ctd\u003eDenoted by a filled diamond in UML.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eWe do not use \"final\" keyword for Aggregation.\u003c/td\u003e\u003ctd\u003e\"final\" keyword is used to represent Composition.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eExamples:\u003cbr\u003e- Car has a Driver.\u003cbr\u003e- A Human uses Clothes.\u003cbr\u003e- A Company is an aggregation of People.\u003cbr\u003e- A Text Editor uses a File.\u003cbr\u003e- Mobile has a SIM Card.\u003c/td\u003e\u003ctd\u003eExamples:\u003cbr\u003e- Engine is a part of Car.\u003cbr\u003e- A Human owns the Heart.\u003cbr\u003e- A Company is a composition of Accounts.\u003cbr\u003e- A Text Editor owns a Buffer.\u003cbr\u003e- IMEI Number is a part of a Mobile.\u003c/td\u003e\u003c/tr\u003e\n\u003c/tbody\u003e\u003c/table\u003e\n\n*Note: \"final\" keyword is used in Composition to make sure child variable is initialized.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. The difference between Inheritance and Composition?\n\nThough both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Inheritance is an **\"is-a\"** relationship. Composition is a **\"has-a\"**.\n\n**Example:** Inheritance\n\n```java\n/**\n * Inheritance\n */\nclass Fruit {\n    // ...\n}\n\nclass Apple extends Fruit {\n    // ...\n}\n```\n\n**Example:** Composition\n\n```java\n/**\n * Composition\n */\nclass Fruit {\n    // ...\n}\n\nclass Apple {\n    private Fruit fruit = new Fruit();\n    // ...\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Can you declare the main method as final?\n\nYes. We can declare main method as final. But, In inheritance concept we cannot declare main method as final in parent class. It give compile time error.\n\nThe main method has to be public because it has to be called by JVM which is outside the scope of the package and hence would need the access specifier-public.\n\n**Example:**\n\n```java\npublic class Test {\n\tpublic final static void main(String[] args) throws Exception {\n\t\tSystem.out.println(\"This is Test Class\");\n\t}\n}\n \nclass Child extends Test {\n\tpublic static void main(String[] args) throws Exception {\n\t\tSystem.out.println(\"This is Child Class\");\n\t}\n}\n```\n\nOutput\n\n```java\nCannot override the final method from Test.\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is covariant return type?\n\nIt is possible to have different return type for a overriding method in child class, but child\\'s return type should be sub-type of parent\\'s return type. Overriding method becomes variant with respect to return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.\n\n**Example:**\n\n```java\n/**\n * Covariant Return Type\n */\nclass SuperClass {\n    SuperClass get() {\n        System.out.println(\"SuperClass\");\n        return this;\n    }\n}\n\npublic class Tester extends SuperClass {\n    Tester get() {\n        System.out.println(\"SubClass\");\n        return this;\n    }\n\n    public static void main(String[] args) {\n        SuperClass tester = new Tester();\n        tester.get();\n    }\n}\n```\n\nOutput:\n\n```java\nSubclass\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Can you explain Liskov Substitution principle?\n\nLiskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.**\n\nGiven a class B is subclass of class A , we should be able to pass an object of class B to any method that expects(takes as an argument/parameter) an object of class A and the method should not give any weird output in that case.\n\n`ClientTestProgram` class has a method `playVideoInAllMediaPlayers()` which accepts list of all `MediaPlayer` objects and plays video for each , but method fails at `WinampMediaPlayer` ? Let's check whether it satisfies **LSP**.\n\n```java\npublic class MediaPlayer {\n\n    // Play audio implementation\n    public void playAudio() {\n        System.out.println(\"Playing audio...\");\n    }\n\n    // Play video implementation\n    public void playVideo() {\n        System.out.println(\"Playing video...\");\n    }\n}\n\npublic class VlcMediaPlayer extends MediaPlayer {}\n\npublic class WinampMediaPlayer extends MediaPlayer {\n\n    // Play video is not supported in Winamp player\n    public void playVideo() {\n        throw new VideoUnsupportedException();\n    }\n}\n\npublic class VideoUnsupportedException extends RuntimeException {\n\n    private static final long serialVersionUID = 1 L;\n\n}\n\npublic class ClientTestProgram {\n\n    public static void main(String[] args) {\n\n        // Created list of players\n        List \u003c MediaPlayer \u003e allPlayers = new ArrayList \u003c MediaPlayer \u003e ();\n        allPlayers.add(new VlcMediaPlayer());\n        allPlayers.add(new DivMediaPlayer());\n\n        // Play video in all players\n        playVideoInAllMediaPlayers(allPlayers);\n\n        // Well - all works as of now...... :-)\n        System.out.println(\"---------------------------\");\n\n        // Now adding new Winamp player\n        allPlayers.add(new WinampMediaPlayer());\n\n        // Again play video in all players \u0026 Oops it broke the program... :-(\n        // Why we got unexpected behavior in client? --- Because LSP is violated in WinampMediaPlayer.java, \n        // as it changed the original behavior of super class MediaPlayer.java\n        playVideoInAllMediaPlayers(allPlayers);\n    }\n\n    /**\n     * This method is playing video in all players\n     * \n     * @param allPlayers\n     */\n    public static void playVideoInAllMediaPlayers(List \u003c MediaPlayer \u003e allPlayers) {\n\n        for (MediaPlayer player: allPlayers) {\n            player.playVideo();\n        }\n    }\n}\n```\n\nLet\\'s refactor the code to make \"good\" design using **LSP**?\n- `MediaPlayer` is super class having play audio ability.\n- `VideoMediaPlayer` extends `MediaPlayer` and adds play video ability.\n- `DivMediaPlayer` and `VlcMediaPlayer` both extends `VideoMediaPlayer` for playing audio and video ability.\n- `WinampMediaPlayer` which extends `MediaPlayer` for playing audio ability only.\n- so client program can substitute `DivMediaPlayer` or `VlcMediaPlayer` for their super class `VideoMediaPlayer`\n\nlets reimplement the refactored code\n\n```java\npublic class MediaPlayer {\n\n    // Play audio implementation\n    public void playAudio() {\n        System.out.println(\"Playing audio...\");\n    }\n}\n\n//separated video playing ability from base class \npublic class VideoMediaPlayer extends MediaPlayer {\n\n    // Play video implementation\n    public void playVideo() {\n        System.out.println(\"Playing video...\");\n    }\n}\n\npublic class DivMediaPlayer extends VideoMediaPlayer {}\n\npublic class VlcMediaPlayer extends VideoMediaPlayer {}\n\n//as Winamp expects only audio playing ability, so it must only extend relative base class behaviour, no need to inherit unnecessary behaviour\npublic class WinampMediaPlayer extends MediaPlayer {}\n\n    /**\n     * This method is playing video in all players\n     * \n     * @param allPlayers\n     */\n    public static void playVideoInAllMediaPlayers(List \u003cVideoMediaPlayer\u003e allPlayers) {\n\n        for (VideoMediaPlayer player: allPlayers) {\n            player.playVideo();\n        }\n    }\n```\n\nNow, in `ClientTestProgram` , instead of creating list of type `MediaPlayer`, we will create list of `VideoMediaPlayer` type that should give us compile time error at statement `allPlayers.add(new WinampMediaPlayer()); ` as `WinampMediaPlayer` isnt subclass of `VideoMediaPlayer`.But in case of  `DivMediaPlayer` and `VlcMediaPlayer` they are substitutable for their parent class as seen in `playVideoInAllMediaPlayers()` method\nthat satisefies *Liskov's substitution principle*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 17. JAVA METHOD OVERRIDING\n\n\u003cbr/\u003e\n\n## # 18. JAVA POLYMORPHISM\n\n\u003cbr/\u003e\n\n## Q. What is the difference between compile-time polymorphism and runtime polymorphism?\n\nThere are two types of polymorphism in java:\n\n1. Static Polymorphism also known as Compile time polymorphism\n2. Runtime polymorphism also known as Dynamic Polymorphism  \n\n**1. Static Polymorphism:**  \n\nMethod overloading is one of the way java supports static polymorphism. Here we have two definitions of the same method add() which add method would be called is determined by the parameter list at the compile time. That is the reason this is also known as compile time polymorphism.\n\n**Example:**\n\n```java\n/**\n * Static Polymorphism\n */\nclass SimpleCalculator {\n    int add(int a, int b) {\n        return a + b;\n    }\n\n    int add(int a, int b, int c) {\n        return a + b + c;\n    }\n}\n\npublic class Demo {\n    public static void main(String args[]) {\n        SimpleCalculator obj = new SimpleCalculator();\n        System.out.println(obj.add(10, 20));\n        System.out.println(obj.add(10, 20, 30));\n    }\n}\n```\n\nOutput\n\n```java\n30\n60\n```\n\n**2. Runtime Polymorphism:**  \n\nIt is also known as **Dynamic Method Dispatch**. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, thats why it is called runtime polymorphism.\n\n**Example:**\n\n```java\n/**\n * Runtime Polymorphism\n */\nclass ABC {\n\n    public void myMethod() {\n        System.out.println(\"Overridden Method\");\n    }\n}\n\npublic class XYZ extends ABC {\n\n    public void myMethod() {\n        System.out.println(\"Overriding Method\");\n    }\n\n    public static void main(String args[]) {\n        ABC obj = new XYZ();\n        obj.myMethod();\n    }\n}\n```\n\nOutput:\n\n```java\nOverriding Method\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do you mean Run time Polymorphism?\n\n`Polymorphism` in Java is a concept by which we can perform a single action in different ways.\nThere are two types of polymorphism in java:  \n\n* **Static Polymorphism** also known as compile time polymorphism\n* **Dynamic Polymorphism** also known as runtime polymorphism\n\n**Example:** Static Polymorphism\n\n```java\nclass SimpleCalculator {\n\n    int add(int a, int b) {\n        return a + b;\n    }\n    int  add(int a, int b, int c) {\n        return a + b + c;\n    }\n}\npublic class MainClass\n{\n   public static void main(String args[]) {\n\t   SimpleCalculator obj = new SimpleCalculator();\n       System.out.println(obj.add(10, 20));\n       System.out.println(obj.add(10, 20, 30));\n   }\n}\n```\n\nOutput\n\n```java\n30\n60\n```\n\n**Example:** Runtime polymorphism\n\n```java\nclass ABC {\n   public void myMethod() {\n\t  System.out.println(\"Overridden Method\");\n   }\n}\npublic class XYZ extends ABC {\n\n   public void myMethod() {\n\t  System.out.println(\"Overriding Method\");\n   }\n   public static void main(String args[]) {\n      ABC obj = new XYZ();\n\t  obj.myMethod();\n   }\n}\n```\n\nOutput\n\n```java\nOverriding Method\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is runtime polymorphism in java?\n\n**Runtime polymorphism** or **Dynamic Method Dispatch** is a process in which a call to an overridden method is resolved at runtime rather than compile-time.\n\nAn overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred.\n\n```java\nclass Bank{  \n    public float roi=0.0f;\nfloat getRateOfInterest(){return this.roi;}  \n}  \nclass SBI extends Bank{ \n    float roi=8.4f; \nfloat getRateOfInterest(){return this.roi;}  \n}  \nclass ICICI extends Bank{ \n    float roi=7.3f; \nfloat getRateOfInterest(){return this.roi;}  \n}  \nclass AXIS extends Bank{  \n    float roi=9.7f;\nfloat getRateOfInterest(){return this.roi;}  \n}  \n\nBank b;  \nb=new SBI();  \nSystem.out.println(\"SBI Rate of Interest: \"+b.getRateOfInterest());\n\nb=new ICICI();  \nSystem.out.println(\"ICICI Rate of Interest: \"+b.getRateOfInterest());\n\nb=new AXIS();  \nSystem.out.println(\"AXIS Rate of Interest: \"+b.getRateOfInterest()); \n\nSystem.out.println(\"Bank Rate of Interest: \"+b.roi); \n\n/**output:\nSBI Rate of Interest: 8.4\nICICI Rate of Interest: 7.3\nAXIS Rate of Interest: 9.7\nBank Rate of Interest: 0.0 \n\n//you might think it should be 9.7 , as recent object being refered to is of AXIS but method is overridden, not the data members, so runtime polymorphism can't be achieved by data members/instance variables.\n**/\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 19. JAVA ABSTRACTION\n\n\u003cbr/\u003e\n\n## Q. What is the difference between abstract class and interface?\n\nAbstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can\\'t be instantiated.\n\n|Abstract Class               |Interface                        |\n|-----------------------------|---------------------------------|\n|Abstract class can have abstract and non-abstract methods.|Interface can have only abstract methods. Since Java 8, it can have default and static methods also.|\n|Abstract class doesn\\'t support multiple inheritance.|Interface supports multiple inheritance.|\n|Abstract class can have final, non-final, static and non-static variables.|Interface has only static and final variables.|\n|Abstract class can provide the implementation of interface.|Interface can\\'t provide the implementation of abstract class.|\n|An abstract class can extend another Java class and implement multiple Java interfaces.|An interface can extend another Java interface only.|\n|An abstract class can be extended using keyword \"extends\".|An interface can be implemented using keyword \"implements\".|\n|A Java abstract class can have class members like private, protected, etc.|Members of a Java interface are public by default.|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are Wrapper classes?\n\nThe wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.\n\n**Use of Wrapper classes in Java:**  \n\n* **Change the value in Method**: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.\n\n* **Serialization**: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.\n\n* **Synchronization**: Java synchronization works with objects in Multithreading.\n\n* **java.util package**: The java.util package provides the utility classes to deal with objects.\n\n* **Collection Framework**: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.\n\n| Sl.No|Primitive Type  |\tWrapper class       |\n|------|----------------|----------------------|\n| 01.  |boolean\t      |Boolean|\n| 02.  |char\t         |Character|\n| 03.  |byte\t         |Byte|\n| 04.  |short\t         |Short|\n| 05.  |int\t            |Integer|\n| 06.  |long\t         |Long|\n| 07.  |float\t         |Float|\n| 08.  |double\t         |Double|\n\n**Example:** Primitive to Wrapper\n\n```java\n/**\n * Java program to convert primitive into objects\n * Autoboxing example of int to Integer\n */\nclass WrapperExample {\n    public static void main(String args[]) {\n        int a = 20;\n        Integer i = Integer.valueOf(a); // converting int into Integer explicitly\n        Integer j = a; // autoboxing, now compiler will write Integer.valueOf(a) internally\n\n        System.out.println(a + \" \" + i + \" \" + j);\n    }\n}\n```\n\nOutput\n\n```java\n20 20 20\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between abstraction and encapsulation?\n\nIn Java, Abstraction is supported using `interface` and `abstract class` while Encapsulation is supported using access modifiers e.g. public, private and protected. Abstraction solves the problem at design level while Encapsulation solves it implementation level.\n\nAbstraction is about hiding unwanted details while giving out most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect inner working of an object from outside world.\n\n**Difference:**\n\n\u003ctable class=\"alt\"\u003e\n\u003ctbody\u003e\u003ctr\u003e\u003cth\u003eAbstraction\u003c/th\u003e\u003cth\u003eEncapsulation\u003c/th\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAbstraction is a process of hiding the implementation details and showing only functionality to the user.\u003c/td\u003e\n\u003ctd\u003e Encapsulation is a process of wrapping code and data together into a single unit\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAbstraction lets you focus on what the object does instead of how it does it.\u003c/td\u003e\n\u003ctd\u003eEncapsulation provides you the control over the data and keeping it safe from outside misuse.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAbstraction solves the problem in the Design Level.\u003c/td\u003e\n\u003ctd\u003eEncapsulation solves the problem in the Implementation Level.\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAbstraction is implemented by using Interfaces and Abstract Classes.\u003c/td\u003e\n\u003ctd\u003eEncapsulation is implemented by using Access Modifiers (private, default, protected, public)\u003c/td\u003e\u003c/tr\u003e\n\u003ctr\u003e\u003ctd\u003eAbstraction means hiding implementation complexities by using interfaces and abstract class.\u003c/td\u003e\n\u003ctd\u003eEncapsulation means hiding data by using setters and getters.\u003c/td\u003e\u003c/tr\u003e\n\u003c/tbody\u003e\u003c/table\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 20. JAVA INTERFACES\n\n\u003cbr/\u003e\n\n## Q. Can we use private or protected member variables in an interface?\n\nThe java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically\n\n```java\npublic interface Test {\n   public string name1;\n   private String email;\n   protected pass;\n}\n```\n\nas you have declare variable in test interface with private and protected it will give error. if you do not specify the modifier the compiler will add public static final automatically.\n\n```java\npublic interface Test {\n   public static final string name1;\n   public static final  String email;\n   public static final pass;\n}\n```\n\n* Interfaces cannot be instantiated that is why the variable are **static**\n* Interface are used to achieve the 100% abstraction there for the variable are **final**\n* An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them. that is why variable are **public**\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. When can an object reference be cast to a Java interface reference?\n\nAn interface reference can point to any object of a class that implements this interface\n\n```java\n/**\n * Interface\n */\ninterface MyInterface {\n    void display();\n}\n\npublic class TestInterface implements MyInterface {\n\n    void display() {\n        System.out.println(\"Hello World\");\n    }\n\n    public static void main(String[] args) {\n        MyInterface myInterface = new TestInterface();\n        MyInterface.display();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface?\n\nIf superClass has implemented Serializable that means subclass is also Serializable ( as subclass always inherits all features from its parent class ), for avoiding Serialization in sub-class we can define **writeObject()** method and throw **NotSerializableException()** from there as done below.\n\n```java\n/**\n * Serialization\n */\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.NotSerializableException;\nimport java.io.ObjectOutput;\nimport java.io.ObjectOutputStream;\nimport java.io.OutputStream;\nimport java.io.Serializable;\n\nclass Super implements Serializable {\n    private static final long serialVersionUID = 1L;\n}\n\nclass Sub extends Super {\n\n    private static final long serialVersionUID = 1L;\n    private Integer id;\n\n    public Sub(Integer id) {\n        this.id = id;\n    }\n\n    @Override\n    public String toString() {\n        return \"Employee [id=\" + id + \"]\";\n    }\n\n    /*\n     * define how Serialization process will write objects.\n     */\n    private void writeObject(ObjectOutputStream os) throws NotSerializableException {\n        throw new NotSerializableException(\"This class cannot be Serialized\");\n    }\n}\n\npublic class SerializeDeserialize {\n\n    public static void main(String[] args) {\n\n        Sub object1 = new Sub(8);\n        try {\n            OutputStream fout = new FileOutputStream(\"ser.txt\");\n            ObjectOutput oout = new ObjectOutputStream(fout);\n            System.out.println(\"Serialization process has started, serializing objects...\");\n            oout.writeObject(object1);\n            fout.close();\n            oout.close();\n            System.out.println(\"Object Serialization completed.\");\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n}\n```\n\nOutput\n\n```java\nSerialization process has started, serializing objects...\njava.io.NotSerializableException: This class cannot be Serialized\n    at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35)\n    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)\n    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)\n    at java.lang.reflect.Method.invoke(Unknown Source)\n    at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)\n    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)\n    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)\n    at java.io.ObjectOutputStream.writeObject0(Unknown Source)\n    at java.io.ObjectOutputStream.writeObject(Unknown Source)\n    at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51)\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between Serializable and Externalizable interface?\n\n|SERIALIZABLE    |EXTERNALIZABLE        |\n|----------------|-----------------------|\n|Serializable is a marker interface i.e. does not contain any method.|\tExternalizable interface contains two methods writeExternal() and readExternal() which implementing classes MUST override.|\n|Serializable interface pass the responsibility of serialization to JVM and it\\'s default algorithm.|\tExternalizable provides control of serialization logic to programmer – to write custom logic.|\n|Mostly, default serialization is easy to implement, but has higher performance cost.|Serialization done using Externalizable, add more responsibility to programmer but often result in better performance.|\n|It\\'s hard to analyze and modify class structure because any change may break the serialization.|\tIt\\'s more easy to analyze and modify class structure because of complete control over serialization logic.|\n|Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create marker interface?\n\nAn interface with no methods is known as marker or tagged interface. It provides some useful information to JVM/compiler so that JVM/compiler performs some special operations on it. It is used for better readability of code. For example Serializable, Clonnable etc.\n\n**Syntax:**\n\n```java\npublic interface Interface_Name {\n\n}\n```\n\n**Example:**\n\n```java\n/**\n * Maker Interface\n */\ninterface Marker {\n}\n\nclass MakerExample implements Marker {\n    // do some task\n}\n\nclass Main {\n    public static void main(String[] args) {\n        MakerExample obj = new MakerExample();\n        if (obj instanceOf Marker) {\n            // do some task\n        }\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Can you declare an interface method static?\n\nJava 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a Functional Interface?\n\nA **functional interface** is an interface that defines only one abstract method.\n\nTo accurately determine the interface as functional, an annotation has been added `@FunctionalInterface` that works on the principle of `@Override`. It will designate a plan and will not allow to define the second abstract method in the interface.\n\nAn interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are `default` interface methods?\n\nJava 8 allows you to add non-abstract method implementations to an interface using the keyword default:\n\n```java\ninterface  Example {\n    int  process ( int  a );\n    default void  show () {\n        System.out.println(\"default show ()\");\n    }\n}\n```\n\n* If a class implements an interface, it can, but does not have to, implement the default methods already implemented in the * interface. The class inherits the default implementation.\n* If a class implements several interfaces that have the same default method, then the class must implement the method with the same signature on its own. The situation is similar if one interface has a default method, and in the other the same method is abstract - no class default implementation is inherited.\n* The default method cannot override the class method `java.lang.Object`.\n* They help implement interfaces without fear of disrupting other classes.\n* Avoid creating utility classes, since all the necessary methods can be represented in the interfaces themselves.\n* They give classes the freedom to choose the method to be redefined.\n* One of the main reasons for introducing default methods is the ability of collections in Java 8 to use lambda expressions.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to call `default` interface method in a class that implements this interface?\n\nUsing the keyword superalong with the interface name:\n\n```java\ninterface  Paper {\n    default void  show () {\n        System.out.println(\" default show ()\");\n    }\n}\n\nclass  License  implements  Paper {\n     public  void  show () {\n        Paper.super.show();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is `static` interface method?\n\nStatic interface methods are similar to default methods, except that there is no way to override them in classes that implement the interface.\n\n* Static methods in the interface are part of the interface without the ability to use them for objects of the implementation class\n* Class methods `java.lang.Object`cannot be overridden as static\n* Static methods in the interface are used to provide helper methods, for example, checking for null, sorting collections, etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to call `static` interface method?\n\nUsing the interface name:\n\n```java\ninterface  Paper {\n     static  void  show () {\n         System.out.println( \" static show () \" );\n    }\n}\n\nclass  License {\n     public  void  showPaper () {\n         Paper.show ();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `Function\u003cT,R\u003e`, `DoubleFunction\u003cR\u003e`, `IntFunction\u003cR\u003e` and `LongFunction\u003cR\u003e`?\n\n`Function\u003cT, R\u003e`- the interface with which a function is implemented that receives an instance of the class `T` and returns an instance of the class at the output `R`.\n\nDefault methods can be used to build call chains ( `compose`, `andThen`).\n\n```java\nFunction \u003c String , Integer \u003e toInteger =  Integer :: valueOf;\nFunction \u003c String , String \u003e backToString = toInteger.andThen ( String :: valueOf);\nbackToString.apply(\"123\");     // \"123\"\n```\n\n* `DoubleFunction\u003cR\u003e`- a function that receives input `Double` and returns an instance of the class at the output `R`;\n* `IntFunction\u003cR\u003e`- a function that receives input `Integer`and returns an instance of the class at the output `R`;\n* `LongFunction\u003cR\u003e`- a function that receives input `Long`and returns an instance of the class at the output `R`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `UnaryOperator\u003cT\u003e`, `DoubleUnaryOperator`, `IntUnaryOperator`and `LongUnaryOperator`?\n\n`UnaryOperator\u003cT\u003e`(**unary operator**) takes an object of type as a parameter `T`, performs operations on them and returns the result of operations in the form of an object of type `T`:\n\n```java\nUnaryOperator \u003c Integer \u003e operator = x - \u003e x * x;\nSystem.out.println(operator.apply ( 5 )); // 25\n```\n\n* `DoubleUnaryOperator`- unary operator receiving input `Double`;\n* `IntUnaryOperator`- unary operator receiving input `Integer`;\n* `LongUnaryOperator`- unary operator receiving input `Long`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `BinaryOperator\u003cT\u003e`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`?\n\n`BinaryOperator\u003cT\u003e`(**binary operator**) - an interface through which a function is implemented that receives two instances of the class `T`and returns an instance of the class at the output `T`.\n\n```java\nBinaryOperator \u003c Integer \u003e operator = (a, b) -\u003e a + b;\nSystem.out.println(operator.apply ( 1 , 2 )); // 3\n```\n\n* `DoubleBinaryOperator`- binary operator receiving input Double;\n* `IntBinaryOperator`- binary operator receiving input Integer;\n* `LongBinaryOperator`- binary operator receiving input Long.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `Predicate\u003cT\u003e`, `DoublePredicate`, `IntPredicateand` `LongPredicate`?\n\n`Predicate\u003cT\u003e`(**predicate**) - the interface with which a function is implemented that receives an instance of the class as input `T`and returns the type value at the output `boolean`.\n\nThe interface contains a variety of methods by default, allow to build complex conditions ( `and`, `or`, `negate`).\n\n```java\nPredicate \u003c String \u003e predicate = (s) -\u003e s.length () \u003e  0 ;\npredicate.test(\"foo\"); // true \npredicate.negate().test(\"foo\"); // false\n```\n\n* `DoublePredicate`- predicate receiving input `Double`;\n* `IntPredicate`- predicate receiving input `Integer`;\n* `LongPredicate`- predicate receiving input `Long`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `Consumer\u003cT\u003e`, `DoubleConsumer`, `IntConsumer`and `LongConsumer`?\n\n`Consumer\u003cT\u003e`(**consumer**) - the interface through which a function is implemented that receives an instance of the class as an input `T`, performs some action with it, and returns nothing.\n\n```java\nConsumer\u003cString\u003e hello = (name) -\u003e  System.out.println( \" Hello, \"  + name);\nhello.accept( \" world \" );\n```\n\n* `DoubleConsumer`- the consumer receiving the input `Double`;\n* `IntConsumer`- the consumer receiving the input `Integer`;\n* `LongConsumer`- the consumer receiving the input `Long`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the functional interfaces `Supplier\u003cT\u003e`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier`and `LongSupplier`?\n\n`Supplier\u003cT\u003e`(**provider**) - the interface through which a function is implemented that takes nothing to the input, but returns the result of the class to the output `T`;\n\n```java\nSupplier \u003c LocalDateTime \u003e now =  LocalDateTime::now;\nnow.get();\n```\n\n* `DoubleSupplier`- the supplier is returning `Double`;\n* `IntSupplier`- the supplier is returning `Integer`;\n* `LongSupplier`- the supplier is returning `Long`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n#### Q. What is Spliterator in Java SE 8?\n#### Q. What is Type Inference in Java 8?\n#### Q. What is difference between External Iteration and Internal Iteration?\n\n*ToDo*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 21. JAVA ENCAPSULATION\n\n\u003cbr/\u003e\n\n## Q. How Encapsulation concept implemented in JAVA?\n\nEncapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as `data hiding`.\n\nTo achieve encapsulation in Java −\n\n* Declare the variables of a class as private.\n* Provide public setter and getter methods to modify and view the variables values.\n\n**Example:**\n\n```java\npublic class EncapClass {\n   private String name;\n\n   public String getName() {\n      return name;\n   }\n   public void setName(String newName) {\n      name = newName;\n   }\n}\n\npublic class MainClass {\n\n   public static void main(String args[]) {\n      EncapClass obj = new EncapClass();\n      obj.setName(\"Pradeep Kumar\");\n      System.out.print(\"Name : \" + obj.getName());\n   }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 22. JAVA GENERICS\n\n\u003cbr/\u003e\n\n## Q. Do you know Generics? How did you used in your coding?\n\n`Generics` allows type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well.\n\n**Advantages:**\n\n* **Type-safety**: We can hold only a single type of objects in generics. It doesn\\'t allow to store other objects.\n* **Type Casting**: There is no need to typecast the object.\n* **Compile-Time Checking**: It is checked at compile time so problem will not occur at runtime.\n\n**Example:**\n\n```java\n/** \n* A Simple Java program to show multiple \n* type parameters in Java Generics \n*\n* We use \u003c \u003e to specify Parameter type\n*\n**/ \nclass GenericClass\u003cT, U\u003e { \n    T obj1;  // An object of type T \n    U obj2;  // An object of type U \n  \n    // constructor \n    GenericClass(T obj1, U obj2) { \n        this.obj1 = obj1; \n        this.obj2 = obj2; \n    } \n  \n    // To print objects of T and U \n    public void print() { \n        System.out.println(obj1); \n        System.out.println(obj2); \n    } \n} \n  \n// Driver class to test above \nclass MainClass { \n    public static void main (String[] args) { \n        GenericClass \u003cString, Integer\u003e obj = \n            new GenericClass\u003cString, Integer\u003e(\"Generic Class Example !\", 100); \n  \n        obj.print(); \n    } \n}\n```\n\nOutput:\n\n```java\nGeneric Class Example !\n100\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## # 23. MISCELLANEOUS\n\n\u003cbr/\u003e\n\n## Q. How will you invoke any external process in Java?\n\nIn java, external process can be invoked using **exec()** method of **Runtime Class**.\n\n**Example:**\n\n```java\n/**\n * exec()\n */\nimport java.io.IOException;\n\nclass ExternalProcessExample {\n    public static void main(String[] args) { \n        try { \n            // Command to create an external process \n             String command = \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"; \n  \n            // Running the above command \n            Runtime run  = Runtime.getRuntime(); \n            Process proc = run.exec(command); \n        } catch (IOException e) { \n            e.printStackTrace(); \n        } \n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the static import?\n\nThe static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name.\n\n```java\n/**\n * Static Import\n */\nimport static java.lang.System.*;\n\nclass StaticImportExample {\n\n    public static void main(String args[]) {\n        out.println(\"Hello\");// Now no need of System.out\n        out.println(\"Java\");\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is the difference between factory and abstract factory pattern?\n\nThe Factory Method is usually categorised by a switch statement where each case returns a different class, using the same root interface so that the calling code never needs to make decisions about the implementation.\n\n**Example:** credit card validator factory which returns a different validator for each card type.\n\n```java\n/**\n * Abstract Factory Pattern\n */\npublic ICardValidator GetCardValidator (string cardType)\n{\n    switch (cardType.ToLower())\n    {\n        case \"visa\":\n            return new VisaCardValidator();\n        case \"mastercard\":\n        case \"ecmc\":\n            return new MastercardValidator();\n        default:\n            throw new CreditCardTypeException(\"Do not recognise this type\");\n    }\n}\n```\n\nAbstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.\n\nIn Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the methods used to implement for key Object in HashMap?\n\n**1. equals()** and **2. hashcode()**\n\nClass inherits methods from the following classes in terms of HashMap\n\n* java.util.AbstractMap\n* java.util.Object\n* java.util.Map\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is a Memory Leak?\n\nThe standard definition of a memory leak is a scenario that occurs when **objects are no longer being used by the application, but the Garbage Collector is unable to remove them from working memory** – because they\\'re still being referenced. As a result, the application consumes more and more resources – which eventually leads to a fatal OutOfMemoryError.\n\nSome tools that do memory management to identifies useless objects or memeory leaks like:\n\n* \u003ca href=\"https://support.hpe.com/hpsc/doc/public/display?docId=emr_na-c00990822\u0026docLocale=en_US\"\u003eHP OpenView\u003c/a\u003e\n* \u003ca href=\"https://h20392.www2.hpe.com/portal/swdepot/displayProductInfo.do?productNumber=HPJMETER\"\u003eHP JMETER\u003c/a\u003e\n* \u003ca href=\"http://www.javaperformancetuning.com/tools/jprobe/index.shtml\"\u003eJProbe\u003c/a\u003e\n* \u003ca href=\"https://www.ibm.com/support/knowledgecenter/en/SSTFXA_6.3.0/com.ibm.itm.doc_6.3/install/itm_over.htm\"\u003eIBM Tivoli\u003c/a\u003e\n\n**Example:**\n\n```java\n/**\n * Memory Leaks \n */\nimport java.util.Vector;\n\npublic class MemoryLeaksExample {\n    public static void main(String[] args) {\n        Vector v = new Vector(214444);\n        Vector v1 = new Vector(214744444);\n        Vector v2 = new Vector(214444);\n        System.out.println(\"Memory Leaks Example\");\n    }\n}\n```\n\nOutput\n\n```java\nException in thread \"main\" java.lang.OutOfMemoryError: Java heap space exceed\n```\n\n**Types of Memory Leaks in Java:**  \n\n* Memory Leak through static Fields\n* Unclosed Resources/connections\n* Adding Objects With no `hashCode()` and `equals()` Into a HashSet\n* Inner Classes that Reference Outer Classes\n* Through `finalize()` Methods\n* Calling `String.intern()` on Long String\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. The difference between Serial and Parallel Garbage Collector?\n\n**1. Serial Garbage Collector:**  \n\nSerial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs.\n\nTurn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector.\n\n**2. Parallel Garbage Collector:**  \n\nParallel garbage collector is also called as throughput collector. It is the default garbage collector of the JVM. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is difference between WeakReference and SoftReference in Java?\n\n**1. Weak References:**\n\nWeak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them.\n\n```java\n/**\n * Weak Reference\n */\nimport java.lang.ref.WeakReference;\n\nclass MainClass {\n    public void message() {\n        System.out.println(\"Weak References Example\");\n    }\n}\n\npublic class Example {\n    public static void main(String[] args) {\n        // Strong Reference\n        MainClass g = new MainClass();\n        g.message();\n\n        // Creating Weak Reference to MainClass-type object to which 'g'\n        // is also pointing.\n        WeakReference\u003cMainClass\u003e weakref = new WeakReference\u003cMainClass\u003e(g);\n        g = null;\n        g = weakref.get();\n        g.message();\n    }\n}\n```\n\n**2. Soft References:**\n\nIn Soft reference, even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory.To create such references java.lang.ref.SoftReference class is used.\n\n```java\n/**\n * Soft Reference\n */\nimport java.lang.ref.SoftReference;\n\nclass MainClass {\n    public void message() {\n        System.out.println(\"Soft References Example\");\n    }\n}\n\npublic class Example {\n    public static void main(String[] args) {\n        // Strong Reference\n        MainClass g = new MainClass();\n        g.message();\n\n        // Creating Soft Reference to MainClass-type object to which 'g'\n        // is also pointing.\n        SoftReference\u003cMainClass\u003e softref = new SoftReference\u003cMainClass\u003e(g);\n        g = null;\n        g = softref.get();\n        g.message();\n    }\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How Garbage collector algorithm works?\n\nGarbage collection works on **Mark** and **Sweep** algorithm. In Mark phase it detects all the unreachable objects and Sweep phase it reclaim the heap space used by the garbage objects and make the space available again to the program.\n\nThere are methods like `System.gc()` and `Runtime.gc()` which is used to send request of Garbage collection to JVM but it\\'s not guaranteed that garbage collection will happen. If there is no memory space for creating a new object in Heap Java Virtual Machine throws `OutOfMemoryError` or `java.lang.OutOfMemoryError` heap space\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. Java Program to Implement Singly Linked List?\n\nThe singly linked list is a linear data structure in which each element of the list contains a pointer which points to the next element in the list. Each element in the singly linked list is called a node. Each node has two components: data and a pointer next which points to the next node in the list.\n\n**Example:**\n\n```java\npublic class SinglyLinkedList {    \n    // Represent a node of the singly linked list    \n    class Node{    \n        int data;    \n        Node next;    \n            \n        public Node(int data) {    \n            this.data = data;    \n            this.next = null;    \n        }    \n    }    \n     \n    // Represent the head and tail of the singly linked list    \n    public Node head = null;    \n    public Node tail = null;    \n        \n    // addNode() will add a new node to the list    \n    public void addNode(int data) {    \n        // Create a new node    \n        Node newNode = new Node(data);    \n            \n        // Checks if the list is empty    \n        if(head == null) {    \n            // If list is empty, both head and tail will point to new node    \n            head = newNode;    \n            tail = newNode;    \n        }    \n        else {    \n            // newNode will be added after tail such that tail's next will point to newNode    \n            tail.next = newNode;    \n            // newNode will become new tail of the list    \n            tail = newNode;    \n        }    \n    }    \n        \n    // display() will display all the nodes present in the list    \n    public void display() {    \n        // Node current will point to head    \n        Node current = head;    \n            \n        if(head == null) {    \n            System.out.println(\"List is empty\");    \n            return;    \n        }    \n        System.out.println(\"Nodes of singly linked list: \");    \n        while(current != null) {    \n            // Prints each node by incrementing pointer    \n            System.out.print(current.data + \" \");    \n            current = current.next;    \n        }    \n        System.out.println();    \n    }    \n        \n    public static void main(String[] args) {    \n            \n        SinglyLinkedList sList = new SinglyLinkedList();    \n            \n        // Add nodes to the list    \n        sList.addNode(10);    \n        sList.addNode(20);    \n        sList.addNode(30);    \n        sList.addNode(40);    \n            \n        // Displays the nodes present in the list    \n        sList.display();    \n    }    \n}  \n```\n\n**Output:**\n\n```java\nNodes of singly linked list: \n10 20 30 40\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What do we mean by weak reference?\n\nA weakly referenced object is cleared by the Garbage Collector when it\\'s weakly reachable.\nWeak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference. To create such references `java.lang.ref.WeakReference` class is used.\n\n```java\n/**\n* Weak reference\n*/ \nimport java.lang.ref.WeakReference; \n\nclass WeakReferenceExample { \n    \n    public void message() { \n        System.out.println(\"Weak Reference Example!\"); \n    } \n} \n\npublic class MainClass {\n\n    public static void main(String[] args) { \n        // Strong Reference \n        WeakReferenceExample obj = new WeakReferenceExample();    \n        obj.message(); \n          \n        // Creating Weak Reference to WeakReferenceExample-type object to which 'obj'  \n        // is also pointing. \n        WeakReference\u003cWeakReferenceExample\u003e weakref = new WeakReference\u003cWeakReferenceExample\u003e(obj); \n\n        obj = null;  // is available for garbage collection.\n        obj = weakref.get();  \n        obj.message(); \n    } \n} \n```\n\nOutput\n\n```java\nWeak Reference Example!\nWeak Reference Example!\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What are the different types of JDBC Driver?\n\nJDBC Driver is a software component that enables java application to interact with the database.\nThere are 4 types of JDBC drivers:\n\n1. **JDBC-ODBC bridge driver**: The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.\n1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.\n1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.\n1. **Thin driver**: The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What additional methods for working with associative arrays (maps) appeared in Java 8?\n\n* `putIfAbsent()` adds a key-value pair only if the key was missing:\n\n```java\nmap.putIfAbsent(\"a\", \"Aa\");\n```\n\n* `forEach()` accepts a function that performs an operation on each element:\n\n```java\nmap.forEach((k, v) -\u003e System.out.println(v));\n```\n\n* `compute()` creates or updates the current value to the result of the calculation (it is possible to use the key and the current value):\n\n```java\nmap.compute(\"a\", (k, v) -\u003e String.valueOf(k).concat(v)); //[\"a\", \"aAa\"]\n```\n\n* `computeIfPresent()` if the key exists, updates the current value to the result of the calculation (it is possible to use the key and the current value):\n\n```java\nmap.computeIfPresent(\"a\", (k, v) -\u003e k.concat(v));\n```\n\n* `computeIfAbsent()` if the key is missing, creates it with the value that is calculated (it is possible to use the key):\n\n```java\nmap.computeIfAbsent(\"a\", k -\u003e \"A\".concat(k)); //[\"a\",\"Aa\"]\n```\n\n* `getOrDefault()` if there is no key, returns the passed value by default:\n\n```java\nmap.getOrDefault(\"a\", \"not found\");\n```\n\n* `merge()` accepts a key, a value, and a function that combines the transmitted and current values. If there is no value under the specified key, then it writes the transmitted value there.\n\n```java\nmap.merge(\"a\", \"z\", (value, newValue) -\u003e value.concat(newValue)); //[\"a\",\"Aaz\"]\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is LocalDateTime?\n\n`LocalDateTime`combines together `LocaleDate`and `LocalTime`contains the date and time in the calendar system ISO-8601 without reference to the time zone. Time is stored accurate to the nanosecond. It contains many convenient methods such as plusMinutes, plusHours, isAfter, toSecondOfDay, etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What is ZonedDateTime?\n\n`java.time.ZonedDateTime`- an analogue `java.util.Calendar`, a class with the most complete amount of information about the temporary context in the calendar system ISO-8601. It includes a time zone, therefore, this class carries out all operations with time shifts taking into account it.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to determine repeatable annotation?\n\nTo define a repeatable annotation, you must create a container annotation for the list of repeatable annotations and designate a repeatable meta annotation `@Repeatable`:\n\n```java\n@interface  Schedulers {\n    Scheduler [] value ();\n}\n\n@Repeatable ( Schedulers . Class)\n @interface  Scheduler {\n    String  birthday () default \"Jan 8 2000\";\n }\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. What class appeared in Java 8 for encoding / decoding data?\n\n`Base64`- a thread-safe class that implements a data encoder and decoder using a base64 encoding scheme according to RFC 4648 and RFC 2045 .\n\nBase64 contains 6 basic methods:\n\n`getEncoder() / getDecoder()`- returns a base64 encoder / decoder conforming to the RFC 4648 standard ; getUrlEncoder()/ `getUrlDecoder()`- returns URL-safe base64 encoder / decoder conforming to RFC 4648 standard ;\n`getMimeEncoder() / getMimeDecoder()`- returns a MIME encoder / decoder conforming to RFC 2045 .\n\n\u003cdiv align=\"right\"\u003e\n  \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. How to create a Base64 encoder and decoder?\n\n```java\n// Encode \nString b64 =  Base64.getEncoder().encodeToString ( \" input \" . getBytes ( \" utf-8 \" )); // aW5wdXQ == \n// Decode \nnew  String ( Base64.getDecoder().decode ( \" aW5wdXQ == \" ), \" utf-8 \" ); // input\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n#### Q. Give me an example of design pattern which is based upon open closed principle?\n#### Q. How do you test static method?\n#### Q. How to do you test a method for an exception using JUnit?\n#### Q. Which unit testing libraries you have used for testing Java programs?\n#### Q. What is the difference between @Before and @BeforeClass annotation?\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#related-topics\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n","funding_links":[],"categories":["Java"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fjava-basics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flearning-zone%2Fjava-basics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flearning-zone%2Fjava-basics/lists"}