diff --git a/README.md b/README.md index 2d05a5c..380fef3 100644 --- a/README.md +++ b/README.md @@ -1,348 +1,371 @@ -## Java, J2EE, JSP, Servlet, Hibernate Interview Questions +# Java Basics -*Click if you like the project. Pull Request are highly appreciated.* +> *Click ★ if you like the project. Your contributions are heartily ♡ welcome.* +
-### Table of Contents +## Related Topics -* *[Java 8 Interview Questions](java8-questions.md)* -* *[Multithreading Interview Questions](multithreading-questions.md)* -* *[Collections Interview Questions](collections-questions.md)* -* *[Hibernate Interview Questions](hibernate-questions.md)* -* *[JDBC Interview Questions](JDBC-questions.md)* +* *[Multithreading](multithreading-questions.md)* +* *[Collections](collections-questions.md)* +* *[Java Database Connectivity (JDBC)](JDBC-questions.md)* * *[Java Programs](java-programs.md)* * *[Java String Methods](java-string-methods.md)* -* *[JSP Interview Questions](jsp-questions.md)* -* *[Servlets Interview Questions](servlets-questions.md)* -* *[Java Design Pattern Questions](java-design-pattern-questions.md)* +* *[Jakarta Server Pages (JSP)](jsp-questions.md)* +* *[Servlets](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* +* *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)* +* *[Hibernate](https://github.com/learning-zone/hibernate-basics)* +* *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)*
-## Q. ***What are the types of Exceptions? Explain the hierarchy of Java Exception classes?*** -Exception is an error event that can happen during the execution of a program and disrupts its normal flow. +## Table of Contents + +* [Introduction](#-1-introduction) +* [Java Architecture](#-2-java-architecture) +* [Java Data Types](#-3-java-data-types) +* [Java Methods](#-4-java-methods) +* [Java Functional programming](#-5-java-functional-programming) +* [Java Lambda expressions](#-6-java-lambda-expressions) +* [Java Classes](#-7-java-classes) +* [Java Constructors](#-8-java-constructors) +* [Java Array](#-9-java-array) +* [Java Strings](#-10-java-strings) +* [Java Reflection](#-11-java-reflection) +* [Java Streams](#-12-java-streams) +* [Java Regular Expressions](#-13-java-regular-expressions) +* [Java File Handling](#-14-java-file-handling) +* [Java Exceptions](#-15-java-exceptions) +* [Java Inheritance](#-16-java-inheritance) +* [Java Method Overriding](#-17-java-method-overriding) +* [Java Polymorphism](#-18-java-polymorphism) +* [Java Abstraction](#-19-java-abstraction) +* [Java Interfaces](#-20-java-interfaces) +* [Java Encapsulation](#-21-java-encapsulation) +* [Java Generics](#-22-java-generics) +* [Miscellaneous](#-23-miscellaneous) -**Types of Java Exceptions** +
-**1. Checked Exception**: The 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. -**2. Unchecked Exception**: The 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. -**3. Error**: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. +## # 1. INTRODUCTION -**Hierarchy of Java Exception classes** -The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. +
-Java Exception +## Q. What are the important features of Java 8 release? + +* Interface methods by default; +* Lambda expressions; +* Functional interfaces; +* References to methods and constructors; +* Repeatable annotations +* Annotations on data types; +* Reflection for method parameters; +* Stream API for working with collections; +* Parallel sorting of arrays; +* New API for working with dates and times; +* New JavaScript Nashorn Engine ; +* Added several new classes for thread safe operation; +* Added a new API for `Calendar`and `Locale`; +* Added support for Unicode 6.2.0 ; +* Added a standard class for working with Base64 ; +* Added support for unsigned arithmetic; +* Improved constructor `java.lang.String(byte[], *)` and method performance `java.lang.String.getBytes()`; +* A new implementation `AccessController.doPrivileged` that allows you to set a subset of privileges without having to check all * other access levels; +* Password-based algorithms have become more robust; +* Added support for SSL / TLS Server Name Indication (NSI) in JSSE Server ; +* Improved keystore (KeyStore); +* Added SHA-224 algorithm; +* Removed JDBC Bridge - ODBC; +* PermGen is removed , the method for storing meta-data of classes is changed; +* Ability to create profiles for the Java SE platform, which include not the entire platform, but some part of it; +* Tools + * Added utility `jjs` for using JavaScript Nashorn; + * The command `java` can run JavaFX applications; + * Added utility `jdeps` for analyzing .class files. +
+ ↥ back to top +
-Example: -```java -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +## Q. What is Nashorn? -public class CustomExceptionExample { +**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. - public static void main(String[] args) throws MyException { - try { - processFile("file.txt"); - } catch (MyException e) { - processErrorCodes(e); - } - } +
+ ↥ back to top +
- private static void processErrorCodes(MyException e) throws MyException { - switch(e.getErrorCode()){ - case "BAD_FILE_TYPE": - System.out.println("Bad File Type, notify user"); - throw e; - case "FILE_NOT_FOUND_EXCEPTION": - System.out.println("File Not Found, notify user"); - throw e; - case "FILE_CLOSE_EXCEPTION": - System.out.println("File Close failed, just log it."); - break; - default: - System.out.println("Unknown exception occured," +e.getMessage()); - e.printStackTrace(); - } - } +## Q. What is jjs? + +`jjs` - This is a command line utility that allows you to execute JavaScript programs directly in the console. - private static void processFile(String file) throws MyException { - InputStream fis = null; - try { - fis = new FileInputStream(file); - } catch (FileNotFoundException e) { - throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION"); - } finally { - try { - if(fis !=null) fis.close(); - } catch (IOException e) { - throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION"); - } - } - } -} -```
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between aggregation and composition?*** +## Q. In Java, How many ways you can take input from the console? -Aggregation +In Java, there are three different ways for reading input from the user in the command line environment ( console ). +**1. Using Buffered Reader Class:** -**Aggregation**: We call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object. +This 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. -Example: Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes ```java -public class Organization { - private List employees; -} +/** + * Buffered Reader Class + */ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; -public class Person { - private String name; +public class Test { + public static void main(String[] args) throws IOException { + // Enter data using BufferReader + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); + + // Reading data using readLine + String name = reader.readLine(); + + // Printing the read line + System.out.println(name); + } } ``` -**Composition**: We 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. +**2. Using Scanner Class:** + +The 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. -Example: Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. ```java -public class Car { - //final will make sure engine is initialized - private final Engine engine; - - public Car(){ - engine = new Engine(); +/** + * Scanner Class + */ +import java.util.Scanner; + +class GetInputFromUser { + public static void main(String args[]) { + // Using Scanner for Getting Input from User + Scanner in = new Scanner(System.in); + + String s = in.nextLine(); + System.out.println("You entered string " + s); + + int a = in.nextInt(); + System.out.println("You entered integer " + a); + + float b = in.nextFloat(); + System.out.println("You entered float " + b); } } +``` -class Engine { - private String type; +**3. Using Console Class:** + +It 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() ). + +```java +/** + * Console Class + */ +public class Sample { + public static void main(String[] args) { + // Using Console to input data from user + String name = System.console().readLine(); + System.out.println(name); + } } ``` - - - - - - - - - - - -
AggregationComposition
Aggregation is a weak Association.Composition is a strong Association.
Class can exist independently without owner.Class can not meaningfully exist without owner.
Have their own Life Time.Life Time depends on the Owner.
A uses B.A owns B.
Child is not owned by 1 owner.Child can have only 1 owner.
Has-A relationship. A has B.Part-Of relationship. B is part of A.
Denoted by a empty diamond in UML.Denoted by a filled diamond in UML.
We do not use "final" keyword for Aggregation."final" keyword is used to represent Composition.
Examples:
- Car has a Driver.
- A Human uses Clothes.
- A Company is an aggregation of People.
- A Text Editor uses a File.
- Mobile has a SIM Card.
Examples:
- Engine is a part of Car.
- A Human owns the Heart.
- A Company is a composition of Accounts.
- A Text Editor owns a Buffer.
- IMEI Number is a part of a Mobile.
+
+ ↥ back to top +
-*Note: "final" keyword is used in Composition to make sure child variable is initialized.* +## Q. What is the purpose of using javap? + +The **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. + + ```java + /** + * Java Disassembler + */ +class Simple { + public static void main(String args[]) { + System.out.println("Hello World"); + } +} +``` + +```cmd +cmd> javap Simple.class +``` + +Output + +```java +Compiled from ".java" +class Simple { + Simple(); + public static void main(java.lang.String[]); +} +```
- ↥ back to top + ↥ back to top
-## Q. ***What is difference between Heap and Stack Memory in java?*** -**Java Heap Space** +## Q. Explain the expression `System.out::println`? + +The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. -Java 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. +
+ ↥ back to top +
-Garbage 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. +## Q. Tell us about parallel processing in Java 8? -**Java Stack Memory** +Streams 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. -Stack in java is a section of memory which contains methods, local variables and reference variables. Local variables are created in the stack. +You can also use the `parallelStream()`interface method to create a parallel stream from the collection `Collection`. -Stack 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. +To 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. -As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. +Using, 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: + +```java +collection + .stream () + .peek ( ... ) // operation is sequential + .parallel () + .map ( ... ) // the operation can be performed in parallel, + .sequential () + .reduce ( ... ) // operation is sequential again +``` -**Difference** +As 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()`. +* Criteria that may affect performance in parallel streams: +* Data size - the more data, the more difficult it is to separate the data first, and then combine them. +* 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. +* 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. +* Operations with primitive types will be faster than with class objects. +* 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; +* 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()`: -|Parameter |Stack Memory |Heap Space | -|------------------|-----------------------------|-----------------------------------| -|Application |Stack is used in parts, one at a time during execution of a thread| The entire application uses Heap space during runtime| -|Size |Stack has size limits depending upon OS and is usually smaller then Heap|There is no size limit on Heap| -|Storage |Stores only primitive variables and references to objects that are created in Heap Space|All the newly created objects are stored here| -|Order |It is accessed using Last-in First-out (LIFO) memory allocation system| This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.| -|Life |Stack memory only exists as long as the current method is running|Heap space exists as long as the application runs| -|Efficiency |Comparatively much faster to allocate when compared to heap| Slower to allocate when compared to stack| -|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 | +```java +collection.parallelStream () + .sorted () + .unordered () + .collect ( Collectors . toList ()); +```
- ↥ back to top + ↥ back to top
-## Q. ***What is JVM and is it platform independent?*** -Java 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). +## # 2. JAVA ARCHITECTURE + +
+ +## Q. What is JVM and is it platform independent? + +Java 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). The 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.
- ↥ back to top + ↥ back to top
-## Q. ***What is JIT compiler in Java?*** +## Q. What is JIT compiler in Java? + The 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. -Java 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. +Java 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.
- ↥ back to top + ↥ back to top
-## Q. ***What is Classloader in Java? What are different types of classloaders?*** -The **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. +## Q. What is Classloader in Java? + +The **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. + +**Types of ClassLoader:** -**Types of ClassLoader** +**1. Bootstrap Class Loader**: -**a) Bootstrap Class Loader**: It 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. +It 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. -**b) Extensions Class Loader**: It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` directory or any other directory as java.ext.dirs. +**2. Extensions Class Loader**: -**c) System Class Loader**: It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options. +It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` directory or any other directory as java.ext.dirs. + +**3. System Class Loader**: + +It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options.
- ↥ back to top + ↥ back to top
-## Q. ***Java Compiler is stored in JDK, JRE or JVM?*** -**JDK**: Java 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. +## Q. Java Compiler is stored in JDK, JRE or JVM? -**JVM**: JVM 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. +**1. JDK**: -**JRE**: Java Runtime Environment provides a platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. +Java 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. +**2. JVM**: -Java Compiler - -
- ↥ back to top -
+JVM 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. -## Q. ***What is the difference between factory and abstract factory pattern?*** -The 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. +**2. JRE**: -For example credit card validator factory which returns a different validator for each card type. -```java -public ICardValidator GetCardValidator (string cardType) -{ - switch (cardType.ToLower()) - { - case "visa": - return new VisaCardValidator(); - case "mastercard": - case "ecmc": - return new MastercardValidator(); - default: - throw new CreditCardTypeException("Do not recognise this type"); - } -} -``` -Abstract 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. +Java Runtime Environment provides a platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. -In 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. +

+ Java Compiler +

- ↥ back to top + ↥ back to top
-## Q. ***What are the methods used to implement for key Object in HashMap?*** -**1. equals()** and **2. hashcode()** -Class inherits methods from the following classes in terms of HashMap +## Q. What is difference between Heap and Stack Memory in java? -* java.util.AbstractMap -* java.util.Object -* java.util.Map +**1. Java Heap Space:** -
- ↥ back to top -
+Java 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. -## Q. ***What is difference between the Inner Class and Sub Class?*** -Nested 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. -```java -class Outer { - class Inner { - public void show() { - System.out.println("In a nested class method"); - } - } -} -class Main { - public static void main(String[] args) { - Outer.Inner in = new Outer().new Inner(); - in.show(); - } -} -``` -A subclass is class which inherits a method or methods from a superclass. -```java -class Car { - //... -} - -class HybridCar extends Car { - //... -} -``` -
- ↥ back to top -
+Garbage 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. -## Q. ***Can we import same package/class two times? Will the JVM load the package twice at runtime?*** -We can import the same package or same class multiple times. The JVM will internally load the class only once no matter how many times import the same class. +**2. Java Stack Memory:** -
- ↥ back to top -
+Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. -## Q. ***Distinguish between static loading and dynamic class loading?*** -**Static Class Loading**: Creating 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. -```java -class TestClass { - public static void main(String args[]) { - TestClass tc = new TestClass(); - } -} -``` +Stack 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. -**Dynamic Class Loading**: Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. -```java -Class.forName (String className); -``` -
- ↥ back to top -
+As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. -## Q. ***What is the difference between transient and volatile variable in Java?*** -**Transient**: The 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. -```java -public transient int limit = 55; // will not persist -public int b; // will persist -``` -**Volatile**: The 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. -```java -public class MyRunnable implements Runnable { - private volatile boolean active; - public void run() { - active = true; - while (active) { - } - } - public void stop() { - active = false; - } -} -``` +**Difference:** + +|Parameter |Stack Memory |Heap Space | +|------------------|-----------------------------|-----------------------------------| +|Application |Stack is used in parts, one at a time during execution of a thread| The entire application uses Heap space during runtime| +|Size |Stack has size limits depending upon OS and is usually smaller then Heap|There is no size limit on Heap| +|Storage |Stores only primitive variables and references to objects that are created in Heap Space|All the newly created objects are stored here| +|Order |It is accessed using Last-in First-out (LIFO) memory allocation system| This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.| +|Life |Stack memory only exists as long as the current method is running|Heap space exists as long as the application runs| +|Efficiency |Comparatively much faster to allocate when compared to heap| Slower to allocate when compared to stack| +|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 |
- ↥ back to top + ↥ back to top
-## Q. ***How many types of memory areas are allocated by JVM?*** +## Q. How many types of memory areas are allocated by JVM? + JVM 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: * Loading of code @@ -352,687 +375,425 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l **Types of Memory areas allocated by the JVM:** -**1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. -**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. +**1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. + +**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. + **3. Heap**: It is the runtime data area in which objects are allocated. -**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. + +**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. + **5. Program Counter Register**: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. + **6. Native Method Stack**: It contains all the native methods used in the application.
- ↥ back to top + ↥ back to top
-## Q. ***What will be the initial value of an object reference which is defined as an instance variable?*** -The object references are all initialized to `null` in Java. However in order to do anything useful with these references, It must set to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialized references. +## # 3. JAVA DATA TYPES -
- ↥ back to top -
+
-## Q. ***How can constructor chaining be done using this keyword?*** -Java 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 – +## Q. What are autoboxing and unboxing? -* **Within same class**: It can be done using `this()` keyword for constructors in the same class. -* **From base class**: By using `super()` keyword to call a constructor from the base class. +The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. + +**Example:** Autoboxing ```java -// Java program to illustrate Constructor Chaining -// within same class Using this() keyword -class Temp -{ - // default constructor 1 - // default constructor will call another constructor - // using this keyword from same class - Temp() { - // calls constructor 2 - this(5); - System.out.println("The Default constructor"); - } - - // parameterized constructor 2 - Temp(int x) { - // calls constructor 3 - this(10, 20); - System.out.println(x); - } - - // parameterized constructor 3 - Temp(int x, int y) { - System.out.println(10 + 20); - } - - public static void main(String args[]) { - // invokes default constructor first - new Temp(); - } -} -``` -Ouput: -``` -30 -10 -The Default constructor -``` -```java -// Java program to illustrate Constructor Chaining to -// other class using super() keyword -class Base -{ - String name; - - // constructor 1 - Base() { - this(""); - System.out.println("No-argument constructor of base class"); - } - - // constructor 2 - Base(String name) { - this.name = name; - System.out.println("Calling parameterized constructor of base"); - } -} - -class Derived extends Base -{ - // constructor 3 - Derived() { - System.out.println("No-argument constructor of derived"); - } - - // parameterized constructor 4 - Derived(String name) { - // invokes base class constructor 2 - super(name); - System.out.println("Calling parameterized constructor of derived"); - } - - public static void main(String args[]) { - // calls parameterized constructor 4 - Derived obj = new Derived("test"); - - // Calls No-argument constructor - // Derived obj = new Derived(); - } +/** + * Autoboxing + */ +class BoxingExample { + public static void main(String args[]) { + int a = 50; + Integer a2 = new Integer(a); // Boxing + Integer a3 = 5; // Boxing + + System.out.println(a2 + " " + a3); + } } ``` -Output: -``` -Calling parameterized constructor of base -Calling parameterized constructor of derived -``` -
- ↥ back to top -
-## Q. ***Can you declare the main method as final?*** -Yes. 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. The 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. +**Example:** Unboxing + ```java -public class Test { - public final static void main(String[] args) throws Exception { - System.out.println("This is Test Class"); - } -} - -class Child extends Test { - public static void main(String[] args) throws Exception { - System.out.println("This is Child Class"); - } +/** + * Unboxing + */ +class UnboxingExample { + public static void main(String args[]) { + Integer i = new Integer(50); + int a = i; + + System.out.println(a); + } } ``` -Output -``` -Cannot override the final method from Test. -``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between the final method and abstract method?*** -Final method is a method that is marked as final, i.e. it cannot be overridden anymore. Just like final class cannot be inherited anymore. - -Abstract method, on the other hand, is an empty method that is ought to be overridden by the inherited class. Without overriding, you will quickly get compilation error. +## Q. What is the difference between transient and volatile variable in Java? -
- ↥ back to top -
+**1. Transient:** -## Q. ***What is the difference between compile-time polymorphism and runtime polymorphism?*** -There are two types of polymorphism in java: -1) Static Polymorphism also known as compile time polymorphism -2) Dynamic Polymorphism also known as runtime polymorphism +The 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. -**Example of static Polymorphism** +**Example:** -Method 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. ```java -class SimpleCalculator -{ - int add(int a, int b) { - return a + b; - } - int add(int a, int b, int c) { - return a + b + c; - } -} -public class Demo -{ - public static void main(String args[]) { - - SimpleCalculator obj = new SimpleCalculator(); - System.out.println(obj.add(10, 20)); - System.out.println(obj.add(10, 20, 30)); - } -} -``` -Output: -``` -30 -60 +/** + * Transient + */ +public transient int limit = 55; // will not persist +public int b; // will persist ``` -**Runtime Polymorphism (or Dynamic polymorphism)** -It 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. -```java -class ABC { +**2. Volatile:** - public void myMethod() { - System.out.println("Overridden Method"); - } -} -public class XYZ extends ABC { +The 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. - public void myMethod() { - System.out.println("Overriding Method"); +**Example:** + +```java +/** + * Volatile + */ +public class MyRunnable implements Runnable { + private volatile boolean active; + public void run() { + active = true; + while (active) { + } } - public static void main(String args[]) { - ABC obj = new XYZ(); - obj.myMethod(); + public void stop() { + active = false; } } ``` -Output: -``` -Overriding Method -``` +
- ↥ back to top + ↥ back to top
-## Q. ***Can you achieve Runtime Polymorphism by data members?*** -No, we cannot achieve runtime polymorphism by data members. Method is overridden not the data members, so runtime polymorphism can not be achieved by data members. +## Q. What are assertions in Java? -
- ↥ back to top -
+An assertion allows testing the correctness of any assumptions that have been made in the program. Assertion is achieved using the assert statement in Java. -## Q. ***Can you have virtual functions in Java?*** -In 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. +While 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. + +The assert statement is used with a Boolean expression and can be written in two different ways. -**Virtual function with Interface** ```java -/** -* The function applyBrakes() is virtual because -* functions in interfaces are designed to be overridden. -**/ -interface Bicycle { - void applyBrakes(); -} +// First way +assert expression; -class ACMEBicycle implements Bicycle { - public void applyBrakes(){ //Here we implement applyBrakes() - System.out.println("Brakes applied"); //function - } -} +// Second way +assert expression1 : expression2; ``` -
- ↥ back to top -
-## Q. ***What is covariant return type?*** -It 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. +**Example:** + ```java -class SuperClass { - SuperClass get() { - System.out.println("SuperClass"); - return this; - } -} -public class Tester extends SuperClass { - Tester get() { - System.out.println("SubClass"); - return this; - } - public static void main(String[] args) { - SuperClass tester = new Tester(); - tester.get(); - } +/** + * Assertions + */ +public class Example { + public static void main(String[] args) { + int age = 14; + assert age <= 18 : "Cannot Vote"; + System.out.println("The voter's age is " + age); + } } ``` -Output: -``` -Subclass -``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between abstraction and encapsulation?*** -* Abstraction solves the problem at design level while Encapsulation solves it implementation level. -* In Java, Abstraction is supported using `interface` and `abstract class` while Encapsulation is supported using access modifiers e.g. public, private and protected. -* Abstraction 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. - - - - - - - - - - - - - -
AbstractionEncapsulation
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Encapsulation is a process of wrapping code and data together into a single unit
Abstraction lets you focus on what the object does instead of how it does it.Encapsulation provides you the control over the data and keeping it safe from outside misuse.
Abstraction solves the problem in the Design Level.Encapsulation solves the problem in the Implementation Level.
Abstraction is implemented by using Interfaces and Abstract Classes.Encapsulation is implemented by using Access Modifiers (private, default, protected, public)
Abstraction means hiding implementation complexities by using interfaces and abstract class.Encapsulation means hiding data by using setters and getters.
+## Q. What is the final variable, final class, and final blank variable? -
- ↥ back to top -
+**1. Final Variable:** -## Q. ***Can there be an abstract method without an abstract class?*** -Yes. because methods in an interface are also abstract. so the interface can be use to declare abstract method. +Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. -
- ↥ back to top -
+**Example:** -## Q. ***Can we use private or protected member variables in an interface?*** -The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically ```java -public interface Test { - public string name1; - private String email; - protected pass; +/** + * Final Variable + */ +class Demo { + + final int MAX_VALUE = 99; + + void myMethod() { + MAX_VALUE = 101; + } + + public static void main(String args[]) { + Demo obj = new Demo(); + obj.myMethod(); + } } ``` -as 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. + +Output + ```java -public interface Test { - public static final string name1; - public static final String email; - public static final pass; -} +Exception in thread "main" java.lang.Error: Unresolved compilation problem: + The final field Demo.MAX_VALUE cannot be assigned + + at beginnersbook.com.Demo.myMethod(Details.java:6) + at beginnersbook.com.Demo.main(Details.java:10) ``` -* interfaces cannot be instantiated that is why the variable are **static** -* interface are used to achieve the 100% abstraction there for the variable are **final** -* 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** -
- ↥ back to top -
+**2. Blank final variable:** -## Q. ***When can an object reference be cast to a Java interface reference?*** -An interface reference can point to any object of a class that implements this interface -```java -interface Foo { - void display(); -} +A 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` ). -public class TestFoo implements Foo { +**Example:** - void display() { - System.out.println("Hello World"); +```java +/** + * Blank final variable + */ +class Demo { + // Blank final variable + final int MAX_VALUE; + + Demo() { + // It must be initialized in constructor + MAX_VALUE = 100; } - public static void main(String[] args) { - Foo foo = new TestFoo(); - foo.display(); + void myMethod() { + System.out.println(MAX_VALUE); } -} -``` -
- ↥ back to top -
-## Q. ***Give the hierarchy of InputStream and OutputStream classes?*** -A stream can be defined as a sequence of data. There are two kinds of Streams − + public static void main(String args[]) { + Demo obj = new Demo(); + obj.myMethod(); + } +} +``` -* **InPutStream** − The InputStream is used to read data from a source. -* **OutPutStream** − The OutputStream is used for writing data to a destination. - -**Byte Streams** -Java 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. +Output ```java -import java.io.*; -public class CopyFile { - - public static void main(String args[]) throws IOException { - FileInputStream in = null; - FileOutputStream out = null; - - try { - in = new FileInputStream("input.txt"); - out = new FileOutputStream("output.txt"); - - int c; - while ((c = in.read()) != -1) { - out.write(c); - } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - } - } -} +100 ``` -**Character Streams** -Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java 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. + +**3. Final Method:** + +A 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. + +**Example:** ```java -import java.io.*; -public class CopyFile { +/** + * Final Method + */ +class XYZ { + final void demo() { + System.out.println("XYZ Class Method"); + } +} - public static void main(String args[]) throws IOException { - FileReader in = null; - FileWriter out = null; - - try { - in = new FileReader("input.txt"); - out = new FileWriter("output.txt"); - - int c; - while ((c = in.read()) != -1) { - out.write(c); - } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - } - } +class ABC extends XYZ { + void demo() { + System.out.println("ABC Class Method"); + } + + public static void main(String args[]) { + ABC obj = new ABC(); + obj.demo(); + } } ``` -
- ↥ back to top -
- -## Q. ***Can you access non static variable in static context?*** -No, non-static variable cannot be referenced in a static context directly one needs to use object.
- ↥ back to top + ↥ back to top
-## Q. ***What is the purpose of the Runtime class and System class?*** -**Runtime Class**: The purpose of the Runtime class is to provide access to the Java runtime system. The runtime information like memory availability, invoking the garbage collector, etc. +## Q. What is a compile time constant in Java? -**System Class**: The 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. +If 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. -
- ↥ back to top -
+**Compile time constant must be:** -## Q. ***What are assertions in Java?*** -An assertion allows testing the correctness of any assumptions that have been made in the program. Assertion is achieved using the assert statement in Java. While 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. +* Declared final +* Primitive or String +* Initialized within declaration +* Initialized with constant expression -The assert statement is used with a Boolean expression and can be written in two different ways. -``` -// First way -assert expression; +They 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. -// Second way -assert expression1 : expression2; -``` -Example: ```java -public class Example { - public static void main(String[] args) { - int age = 14; - assert age <= 18 : "Cannot Vote"; - System.out.println("The voter's age is " + age); - } -} +private final int x = 10; ``` -
- ↥ back to top -
- -## Q. ***Can we have multiple public classes in a java source file?*** -A Java source file can have only one class declared as **public**, we cannot put two or more public classes together in a **.java** file. This is because of the restriction that the file name should be same as the name of the public class with **.java** extension. If we want to multiple classes under consideration are to be declared as public, we have to store them in separate source files and attach the package statement as the first statement in those source files.
- ↥ back to top + ↥ back to top
-## Q. ***What is the difference between abstract class and interface?*** -Abstract 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. +## Q. What are the different access specifiers available in java? -|Sl.No|Abstract Class |Interface | -|-----|-----------------------------|---------------------------------| -| 01. |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.| -| 02. |Abstract class doesn't support multiple inheritance.| Interface supports multiple inheritance.| -| 03. |Abstract class can have final, non-final, static and non-static variables. |Interface has only static and final variables.| -| 04. |Abstract class can provide the implementation of interface.|Interface can't provide the implementation of abstract class.| -| 05. |The abstract keyword is used to declare abstract class.|The interface keyword is used to declare interface.| -| 06. |An abstract class can extend another Java class and implement multiple Java interfaces.|An interface can extend another Java interface only.| -| 07. |An abstract class can be extended using keyword "extends".|An interface can be implemented using keyword "implements".| -| 08. |A Java abstract class can have class members like private, protected, etc.|Members of a Java interface are public by default.| - -
- ↥ back to top -
- -## Q. ***What are Wrapper classes?*** -The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. - -**Use of Wrapper classes in Java** - -* **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. -* **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. -* **Synchronization**: Java synchronization works with objects in Multithreading. -* **java.util package**: The java.util package provides the utility classes to deal with objects. -* **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. - -| Sl.No|Primitive Type | Wrapper class | -|------|----------------|----------------------| -| 01. |boolean |Boolean| -| 02. |char |Character| -| 03. |byte |Byte| -| 04. |short |Short| -| 05. |int |Integer| -| 06. |long |Long| -| 07. |float |Float| -| 08. |double |Double| +* access specifiers/modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. +* There are four types of access modifiers available in java: + 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. + 2. `private` - when declared as a private , access scope is limited within the enclosing class. + 3. `protected` - when declared as protocted, access scope is limited to enclosing classes, subclasses from same package as well as other packages. + 4. `public` - when declared as public, accessible everywhere in the program. -Example: Primitive to Wrapper ```java -//Java program to convert primitive into objects -//Autoboxing example of int to Integer -class WrapperExample { - public static void main(String args[]){ - //Converting int into Integer - int a=20; - Integer i = Integer.valueOf(a);//converting int into Integer explicitly - Integer j = a; //autoboxing, now compiler will write Integer.valueOf(a) internally - - System.out.println(a+" "+i+" "+j); - } -} -``` -Output -``` -20 20 20 + ... /* data member variables */ + String firstName="Pradeep"; /* default scope */ + protected isValid=true; /* protected scope */ + private String otp="AB0392"; /* private scope */ + public int id = 12334; /* public scope */ + ... + ... /* data member functions */ + String getFirstName(){ return this.firstName; } /* default scope */ + protected boolean getStatus(){this.isValid;} /* protected scope */ + private void generateOtp(){ /* private scope */ + this.otp = this.hashCode() << 16; + }; + public int getId(){ return this.id; } /* public scope */ + ... + .../* inner classes */ + class A{} /* default scope */ + protected class B{} /* protected scope */ + private class C{} /* private scope */ + public class D{} /* public scope */ + ... ``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is Java Reflection API?*** -Java Reflection is the process of analyzing and modifying all the capabilities of a class at runtime. Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at runtime. The **java.lang.Class** class provides many methods that can be used to get metadata, examine and change the run time behavior of a class. +## # 4. JAVA METHODS -There are 3 ways to get the instance of Class class. They are as follows: +
-* forName() method of Class class -* getClass() method of Object class -* the .class syntax +## Q. Can you have virtual functions in Java? -**1. forName() method of Class class** +In 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. -* is used to load the class dynamically. -* returns the instance of Class class. -* It should be used if you know the fully qualified name of class.This cannot be used for primitive types. -```java -class Simple{} - -class Test { - public static void main(String args[]) { - Class c = Class.forName("Simple"); - System.out.println(c.getName()); - } -} -``` -Output -``` -Simple -``` -**2. getClass() method of Object class** +**Example:** Virtual function with Interface -It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives. ```java -class Simple{} - -class Test { - void printName(Object obj) { - Class c=obj.getClass(); - System.out.println(c.getName()); - } - public static void main(String args[]) { - Simple s=new Simple(); - Test t=new Test(); - t.printName(s); - } -} -``` -Output -``` -Simple -``` -**3. The .class syntax** +/** + * The function applyBrakes() is virtual because + * functions in interfaces are designed to be overridden. + **/ +interface Bicycle { + void applyBrakes(); +} -If 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. -```java -class Test { - public static void main(String args[]) { - Class c = boolean.class; - System.out.println(c.getName()); - - Class c2 = Test.class; - System.out.println(c2.getName()); - } -} -``` -Output -``` -boolean -Test +class ACMEBicycle implements Bicycle { + public void applyBrakes() { // Here we implement applyBrakes() + System.out.println("Brakes applied"); // function + } +} ``` -
- ↥ back to top -
- -## Q. ***What is the default value of the local variables?*** -There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
- ↥ back to top + ↥ back to top
-## Q. ***How many types of constructors are used in Java?*** -In 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. +## Q. What is a native method? -**Types of Java Constructors** +A 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: -* Default Constructor (or) no-arg Constructor -* Parameterized Constructor +**Main.java:** -Example: Default Constructor (or) no-arg constructor ```java -public class Car -{ - Car() { - System.out.println("Default Constructor of Car class called"); - } - public static void main(String args[]) { - //Calling the default constructor - Car c = new Car(); +public class Main { + public native int intMethod(int i); + + public static void main(String[] args) { + System.loadLibrary("Main"); + System.out.println(new Main().intMethod(2)); } } ``` -Output + +**Main.c:** + +```c +#include +#include "Main.h" + +JNIEXPORT jint JNICALL Java_Main_intMethod( + JNIEnv *env, jobject obj, jint i) { + return i * i; +} ``` -Default Constructor of Car class called + +**Compile and Run:** + +```java +javac Main.java +javah -jni Main +gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \ + -I${JAVA_HOME}/include/linux Main.c +java -Djava.library.path=. Main ``` -Example: Parameterized Constructor + +Output + ```java -public class Car -{ - String carColor; - Car(String carColor) { - this.carColor = carColor; - } - - public void disp() { - System.out.println("Color of the Car is : "+carColor); - } - public static void main(String args[]) { - //Calling the parameterized constructor - Car c = new Car("Blue"); - c.disp(); - } -} +4 ``` +
- ↥ back to top + ↥ back to top
-## Q. ***What are the restrictions that are applied to the Java static methods?*** +## Q. What are the restrictions that are applied to the Java static methods? + If 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. -* There are a few restrictions imposed on a static method +There are a few restrictions imposed on a static method + * The static method cannot use non-static data member or invoke non-static method directly. * The `this` and `super` cannot be used in static context. -* The static method can access only static type data (static type instance variable). +* The static method can access only static type data ( static type instance variable ). * There is no need to create an object of the class to invoke the static method. * A static method cannot be overridden in a subclass +**Example:** + ```java +/** + * Static Methods + */ class Parent { - static void display() { - System.out.println("Super class"); - } + static void display() { + System.out.println("Super class"); + } } + public class Example extends Parent { - void display() // trying to override display() { - System.out.println("Sub class"); - } - public static void main(String[] args) { - Parent obj = new Example(); - obj.display(); - } + void display() // trying to override display() { + System.out.println("Sub class"); + } + + public static void main(String[] args) { + Parent obj = new Example(); + obj.display(); + } } ``` + This generates a compile time error. The output is as follows − -``` + +```java Example.java:10: error: display() in Example cannot override display() in Parent void display() // trying to override display() ^ @@ -1040,350 +801,2853 @@ overridden method is static 1 error ``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is the final variable, final class, and final blank variable?*** -**Final Variable**: final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. +## Q. What is a lambda? + + What is the structure and features of using a lambda expression? +A lambda is a set of instructions that can be separated into a separate variable and then repeatedly called in various places of the program. + +The basis of the lambda expression is the _lambda operator_ , which represents the arrow `->`. 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. + +The 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. + ```java -class Demo { +interface Operationable { + int calculate ( int x , int y ); +} - final int MAX_VALUE = 99; - void myMethod() { - MAX_VALUE = 101; - } - public static void main(String args[]) { - Demo obj = new Demo(); - obj.myMethod(); - } +public static void main ( String [] args) { + Operationable operation = (x, y) - > x + y; + int result = operation.calculate ( 10 , 20 ); + System.out.println (result); // 30 } ``` -Output -``` -Exception in thread "main" java.lang.Error: Unresolved compilation problem: - The final field Demo.MAX_VALUE cannot be assigned - at beginnersbook.com.Demo.myMethod(Details.java:6) - at beginnersbook.com.Demo.main(Details.java:10) +In fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java. + +* _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. + +* _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method: + +```javascript +operation = ( int x, int y) - > x + y; +// When writing the lambda expression itself, the parameter type is allowed not to be specified: +(x, y) - > x + y; +// If the method does not accept any parameters, then empty brackets are written, for example: +() - > 30 + 20 ; +// If the method accepts only one parameter, then the brackets can be omitted: +n - > n * n; ``` -**Blank final variable**: A 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`). + +* Trailing lambda expressions are not required to return any value. + ```java -class Demo { - //Blank final variable - final int MAX_VALUE; - - Demo() { - //It must be initialized in constructor - MAX_VALUE = 100; - } - void myMethod() { - System.out.println(MAX_VALUE); - } - public static void main(String args[]) { - Demo obj = new Demo(); - obj.myMethod(); - } +interface Printable { + void print( String s ); } + +public static void main ( String [] args) { + Printable printer = s - > System.out.println(s); + printer.print("Hello, world"); +} + +// _ 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 ' : + + +Operationable operation = ( int x, int y) - > { + if (y == 0 ) { + return 0 ; + } + else { + return x / y; + } +}; ``` -Output -``` -100 -``` -**Final Method**: A 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. + +* Passing a lambda expression as a method parameter + ```java -class XYZ { - final void demo() { - System.out.println("XYZ Class Method"); - } -} - -class ABC extends XYZ { - void demo() { - System.out.println("ABC Class Method"); - } - - public static void main(String args[]) { - ABC obj= new ABC(); - obj.demo(); - } +interface Condition { + boolean isAppropriate ( int n ); +} + +private static int sum ( int [] numbers, Condition condition) { + int result = 0 ; + for ( int i : numbers) { + if (condition.isAppropriate(i)) { + result + = i; + } + } + return result; } + +public static void main ( String [] args) { + System.out.println(sum ( new int [] { 0 , 1 , 0 , 3 , 0 , 5 , 0 , 7 , 0 , 9 }, (n) - > n ! = 0 )); +} ``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is the static import?*** -The 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. -```java -import static java.lang.System.*; -class StaticImportExample { +## Q. What variables do lambda expressions have access to? + +Access to external scope variables from a lambda expression is very similar to access from anonymous objects. + +* immutable ( effectively final - not necessarily marked as final) local variables; +* class fields +* static variables. + +The default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression. - public static void main(String args[]) { - out.println("Hello");//Now no need of System.out - out.println("Java"); - } -} -```
- ↥ back to top + ↥ back to top
-## Q. ***Name some classes present in java.util.regex package?*** -**Java Regex**: The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. +## Q. What is a method reference? -**java.util.regex package** +If 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. -* MatchResult interface -* Matcher class -* Pattern class -* PatternSyntaxException class +**Example:** ```java -import java.util.regex.*; -public class RegexExample { - public static void main(String args[]) { - //1st way - Pattern p = Pattern.compile(".s");//. represents single character - Matcher m = p.matcher("as"); - boolean b = m.matches(); - - //2nd way - boolean b2 = Pattern.compile(".s").matcher("as").matches(); - - //3rd way - boolean b3 = Pattern.matches(".s", "as"); - - System.out.println(b + " " + b2 + " " + b3); - } -} +private interface Measurable { + public int length(String string); +} + +public static void main ( String [] args) { + Measurable a = String::length; + System.out.println(a.length("abc")); +} ``` + +Method 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. +
- ↥ back to top + ↥ back to top
-## Q. ***How will you invoke any external process in Java?*** -We can invoke the external process in Java using **exec()** method of **Runtime Class**. -```java -class ExternalProcessExample -{ - public static void main(String[] args) { - try { - // Command to create an external process - String command = "C:\Program Files (x86)"+ - "\Google\Chrome\Application\chrome.exe"; - - // Running the above command - Runtime run = Runtime.getRuntime(); - Process proc = run.exec(command); - } catch (IOException e) { - e.printStackTrace(); - } - } +## Q. What types of method references do you know? + +* on the static method; +* per instance method; +* to the constructor. + +
+ ↥ back to top +
+ +## # 5. JAVA FUNCTIONAL PROGRAMMING + +
+ +## # 6. JAVA LAMBDA EXPRESSIONS + +
+ +## # 7. JAVA CLASSES + +
+ +## Q. What is difference between the Inner Class and Sub Class? + +Nested 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. + +**Example:** + +```java +/** + * Inner Class + */ +class Outer { + class Inner { + public void show() { + System.out.println("In a nested class method"); + } + } +} +class Main { + public static void main(String[] args) { + Outer.Inner in = new Outer().new Inner(); + in.show(); + } } ``` + +A subclass is class which inherits a method or methods from a superclass. + +**Example:** + +```java +/** + * Sub Class + */ +class Car { + //... +} + +class HybridCar extends Car { + //... +} +``` +
- ↥ back to top + ↥ back to top
-## Q. ***What is the purpose of using BufferedInputStream and BufferedOutputStream classes?*** -`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. +## Q. Distinguish between static loading and dynamic class loading? + +**1. Static Class Loading:** + +Creating 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. + +**Example:** -**BufferedInputStreamExample.java** ```java -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; +/** + * Static Class Loading + */ +class TestClass { + public static void main(String args[]) { + TestClass tc = new TestClass(); + } +} +``` -public class BufferedInputStreamExample { +**2. Dynamic Class Loading:** - public static void main(String[] args) { - File file = new File("file.txt"); - FileInputStream fileInputStream = null; - BufferedInputStream bufferedInputStream = null; +Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. - try { - fileInputStream = new FileInputStream(file); - bufferedInputStream = new BufferedInputStream(fileInputStream); - // Create buffer - byte[] buffer = new byte[1024]; - int bytesRead = 0; - while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { - System.out.println(new String(buffer, 0, bytesRead)); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (fileInputStream != null) { - fileInputStream.close(); - } - if (bufferedInputStream != null) { - bufferedInputStream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } +**Example:** + +```java +/** + * Dynamic Class Loading + */ +Class.forName (String className); +``` + +
+ ↥ back to top +
+ +## Q. What is the purpose of the Runtime class and System class? + +**1. Runtime Class:** + +The **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. + +**Example:** + +```java +/** + * Runtime Class + */ +public class RuntimeTest +{ + static class Message extends Thread { + public void run() { + System.out.println(" Exit"); + } + } + + public static void main(String[] args) { + try { + Runtime.getRuntime().addShutdownHook(new Message()); + System.out.println(" Program Started..."); + System.out.println(" Wait for 5 seconds..."); + Thread.sleep(5000); + System.out.println(" Program Ended..."); + } catch (Exception e) { + e.printStackTrace(); + } + } } ``` -Output + +**2. System Class:** + +The 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. + +
+ ↥ back to top +
+ +## Q. What are the ways to instantiate the Class class? + +**1. Using new keyword:** + +```java +MyObject object = new MyObject(); ``` -This is an example of reading data from file + +**2. Using Class.forName():** + +```java +MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); ``` -**BufferedOutputStreamExample.java** + +**3. Using clone():** + ```java -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; +MyObject anotherObject = new MyObject(); +MyObject object = (MyObject) anotherObject.clone(); +``` -public class BufferedOutputStreamExample { +**4. Using object deserialization:** - public static void main(String[] args) { - File file = new File("outfile.txt"); - FileOutputStream fileOutputStream=null; - BufferedOutputStream bufferedOutputStream=null; - try { - fileOutputStream = new FileOutputStream(file); - bufferedOutputStream = new BufferedOutputStream(fileOutputStream); - bufferedOutputStream.write("This is an example of writing data to a file".getBytes()); - bufferedOutputStream.flush(); - - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if(fileOutputStream != null) { - fileOutputStream.close(); - } - if(bufferedOutputStream != null) { - bufferedOutputStream.close(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } -} +```java +ObjectInputStream inStream = new ObjectInputStream(anInputStream ); +MyObject object = (MyObject) inStream.readObject(); ``` -Output + +
+ ↥ back to top +
+ +## Q. What is immutable object? + +Immutable 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. + +**Creating an Immutable Object:** + +* Do not add any setter method +* Declare all fields final and private +* If a field is a mutable object create defensive copies of it for getter methods +* If a mutable object passed to the constructor must be assigned to a field create a defensive copy of it +* Don\'t allow subclasses to override methods. + +```java +/** + * Immutable Object + */ +public class DateContainer { + private final Date date; + + public DateContainer() { + this.date = new Date(); + } + + public Date getDate() { + return new Date(date.getTime()); + } +} ``` -This is an example of writing data to a file + +
+ ↥ back to top +
+ +## Q. How can we create an immutable class in Java? + +Immutable 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. + +**Rules to create immutable classes:** + +* The class must be declared as final +* Data members in the class must be declared as final +* A parameterized constructor +* Getter method for all the variables in it +* No setters + +```java +/** + * Immutable Class + */ +public final class Employee { + + final String pancardNumber; + + public Employee(String pancardNumber) { + this.pancardNumber = pancardNumber; + } + + public String getPancardNumber() { + return pancardNumber; + } +} ``` +
- ↥ back to top + ↥ back to top
-## Q. ***How to set the Permissions to a file in Java?*** -Java 7 has introduced PosixFilePermission Enum and **java.nio.file.Files** includes a method setPosixFilePermissions(Path path, `Set perms`) that can be used to set file permissions easily. +## Q. How bootstrap class loader works in java? + +Bootstrap 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: + +**1. Bootstrap Class Loader:** It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes + +**2. Extensions Class Loader:** It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory. + +**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. + ```java -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.attribute.PosixFilePermission; -import java.util.HashSet; -import java.util.Set; +/** + * ClassLoader + */ +import java.util.logging.Level; +import java.util.logging.Logger; -public class FilePermissions { +public class ClassLoaderTest { - public static void main(String[] args) throws IOException { - File file = new File("/Users/file.txt"); - - //change permission to 777 for all the users - //no option for group and others - file.setExecutable(true, false); - file.setReadable(true, false); - file.setWritable(true, false); - - //using PosixFilePermission to set file permissions 777 - Set perms = new HashSet(); - //add owners permission - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.add(PosixFilePermission.OWNER_EXECUTE); - //add group permissions - perms.add(PosixFilePermission.GROUP_READ); - perms.add(PosixFilePermission.GROUP_WRITE); - perms.add(PosixFilePermission.GROUP_EXECUTE); - //add others permissions - perms.add(PosixFilePermission.OTHERS_READ); - perms.add(PosixFilePermission.OTHERS_WRITE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); - - Files.setPosixFilePermissions(Paths.get("/Users/run.sh"), perms); + public static void main(String args[]) { + try { + // printing ClassLoader of this class + System.out.println("ClassLoader : " + ClassLoaderTest.class.getClassLoader()); + + // trying to explicitly load this class again using Extension class loader + Class.forName("Explicitly load class", true, ClassLoaderTest.class.getClassLoader().getParent()); + } catch (ClassNotFoundException ex) { + Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex); + } } } ``` +
- ↥ back to top + ↥ back to top
-## Q. ***In Java, How many ways you can take input from the console?*** -In Java, there are three different ways for reading input from the user in the command line environment(console). +## Q. How can we create a object of a class without using new operator? + +Different ways to create an object in Java + +* **Using new Keyword:** -**1. Using Buffered Reader Class**: This 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. ```java -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -public class Test -{ - public static void main(String[] args) throws IOException { - //Enter data using BufferReader - BufferedReader reader = - new BufferedReader(new InputStreamReader(System.in)); - - // Reading data using readLine - String name = reader.readLine(); - - // Printing the read line - System.out.println(name); - } -} +class ObjectCreationExample{ + String Owner; +} +public class MainClass { + public static void main(String[] args) { + // Here we are creating Object of JBT using new keyword + ObjectCreationExample obj = new ObjectCreationExample(); + } +} ``` -**2. Using Scanner Class**: The 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. + +* **Using New Instance (Reflection)** + ```java -import java.util.Scanner; - -class GetInputFromUser -{ - public static void main(String args[]) { - // Using Scanner for Getting Input from User - Scanner in = new Scanner(System.in); - - String s = in.nextLine(); - System.out.println("You entered string "+s); - - int a = in.nextInt(); - System.out.println("You entered integer "+a); - - float b = in.nextFloat(); - System.out.println("You entered float "+b); - } -} -``` -**3. Using Console Class**: It 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()). +class CreateObjectClass { + static int j = 10; + CreateObjectClass() { + i = j++; + } + int i; + @Override + public String toString() { + return "Value of i :" + i; + } +} + +class MainClass { + public static void main(String[] args) { + try { + Class cls = Class.forName("CreateObjectClass"); + CreateObjectClass obj = (CreateObjectClass) cls.newInstance(); + CreateObjectClass obj1 = (CreateObjectClass) cls.newInstance(); + System.out.println(obj); + System.out.println(obj1); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } +} +``` + +* **Using Clone:** + +```java + class CreateObjectWithClone implements Cloneable { + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } + int i; + static int j = 10; + CreateObjectWithClone() { + i = j++; + } + @Override + public String toString() { + return "Value of i :" + i; + } +} + +class MainClass { + public static void main(String[] args) { + CreateObjectWithClone obj1 = new CreateObjectWithClone(); + System.out.println(obj1); + try { + CreateObjectWithClone obj2 = (CreateObjectWithClone) obj1.clone(); + System.out.println(obj2); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + } +} +``` + +* **Using ClassLoader** + +```java +class CreateObjectWithClassLoader { + static int j = 10; + CreateObjectWithClassLoader() { + i = j++; + } + int i; + @Override + public String toString() { + return "Value of i :" + i; + } +} + +public class MainClass { + public static void main(String[] args) { + CreateObjectWithClassLoader obj = null; + try { + obj = (CreateObjectWithClassLoader) new MainClass().getClass() + .getClassLoader().loadClass("CreateObjectWithClassLoader").newInstance(); + // Fully qualified classname should be used. + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + System.out.println(obj); + } +} +``` + +
+ ↥ back to top +
+ +## Q. What are methods of Object Class? + +The Object class is the parent class of all the classes in java by default. + + + + + + + + + + + + + + +
MethodDescription
public final Class getClass()returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object\'s monitor.
public final void notifyAll() wakes up all the threads, waiting on this object\'s monitor.
public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedExceptioncauses the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
+ +
+ ↥ back to top +
+ +## Q. What is Optional + +An 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`: + +```java +Optional < String > optional = Optional.of( " hello " ); + +optional.isPresent(); // true +optional.ifPresent(s -> System.out.println(s.length())); // 5 +optional.get(); // "hello" +optional.orElse( " ops ... " ); // "hello" +``` + +
+ ↥ back to top +
+ +## # 8. JAVA CONSTRUCTORS + +
+ +## Q. How many types of constructors are used in Java? + +In 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. + +**Types of Java Constructors:** + +* Default Constructor (or) no-arg Constructor +* Parameterized Constructor + +**Example:** Default Constructor (or) no-arg constructor + +```java +/** + * Default Constructor + */ +public class Car { + Car() { + System.out.println("Default Constructor of Car class called"); + } + + public static void main(String args[]) { + // Calling the default constructor + Car c = new Car(); + } +} +``` + +Output + +```java +Default Constructor of Car class called +``` + +**Example:** Parameterized Constructor + +```java +/** + * Parameterized Constructor + */ +public class Car { + String carColor; + + Car(String carColor) { + this.carColor = carColor; + } + + public void display() { + System.out.println("Color of the Car is : " + carColor); + } + + public static void main(String args[]) { + // Calling the parameterized constructor + Car c = new Car("Blue"); + c.display(); + } +} +``` + +
+ ↥ back to top +
+ +## Q. How can constructor chaining be done using this keyword? + +Java 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 – + +* **Within same class**: It can be done using `this()` keyword for constructors in the same class. +* **From base class**: By using `super()` keyword to call a constructor from the base class. + +```java +/** + * Constructor Chaining + * within same class Using this() keyword + */ +class Temp +{ + // default constructor 1 + // default constructor will call another constructor + // using this keyword from same class + Temp() { + // calls constructor 2 + this(5); + System.out.println("The Default constructor"); + } + + // parameterized constructor 2 + Temp(int x) { + // calls constructor 3 + this(10, 20); + System.out.println(x); + } + + // parameterized constructor 3 + Temp(int x, int y) { + System.out.println(10 + 20); + } + + public static void main(String args[]) { + // invokes default constructor first + new Temp(); + } +} +``` + +Ouput: + +```java +30 +10 +The Default constructor +``` + +```java +/** + * Constructor Chaining to + * other class using super() keyword + */ +class Base +{ + String name; + + // constructor 1 + Base() { + this(""); + System.out.println("No-argument constructor of base class"); + } + + // constructor 2 + Base(String name) { + this.name = name; + System.out.println("Calling parameterized constructor of base"); + } +} + +class Derived extends Base +{ + // constructor 3 + Derived() { + System.out.println("No-argument constructor of derived"); + } + + // parameterized constructor 4 + Derived(String name) { + // invokes base class constructor 2 + super(name); + System.out.println("Calling parameterized constructor of derived"); + } + + public static void main(String args[]) { + // calls parameterized constructor 4 + Derived obj = new Derived("test"); + + // Calls No-argument constructor + // Derived obj = new Derived(); + } +} +``` + +Output: + +```java +Calling parameterized constructor of base +Calling parameterized constructor of derived +``` + +
+ ↥ back to top +
+ +## Q. What is a private constructor? + +* A constructor with private access specifier/modifier is private constructor. +* It is only accessible inside the class by its data members(instance fields,methods,inner classes) and in static block. +* Private Constructor be used in **Internal Constructor chaining and Singleton class design pattern** + +```java +public class MyClass { + + static{ + System.out.println("outer static block.."); + new MyClass(); + } + + private MyInner in; + + { + System.out.println("outer instance block.."); + //new MyClass(); //private constructor accessbile but bad practive will cause infinite loop + } + + private MyClass(){ + System.out.println("outer private constructor.."); + } + + public void getInner(){ + System.out.println("outer data member function.."); + + new MyInner(); + } + + private static class MyInner{ + { + System.out.println("inner instance block.."); + new MyClass(); + } + + MyInner(){ + System.out.println("inner constructor.."); + } + } + + + public static void main(String args[]) { + System.out.println("static main method.."); + MyClass m=new MyClass(); + m.getInner(); + } +} + +class Visitor{ + { + new MyClass();//gives compilation error as MyClass() has private access in MyClass + } +} +``` + +
+ ↥ back to top +
+ +## # 9. JAVA ARRAY + +
+ +## Q. What is copyonwritearraylist in java? + +* `CopyOnWriteArrayList` class implements `List` and `RandomAccess` interfaces and thus provide all functionalities available in `ArrayList` class. +* Using `CopyOnWriteArrayList` is costly for update operations, because each mutation creates a cloned copy of underlying array and add/update element to it. +* 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. +* Because it gets `snapshot` of underlying array while creating iterator, it does not throw `ConcurrentModificationException`. +* Mutation operations on iterators (remove, set, and add) are not supported. These methods throw `UnsupportedOperationException`. +* CopyOnWriteArrayList is a concurrent `replacement for a synchronized List` and offers better concurrency when iterations outnumber mutations. +* It `allows duplicate elements and heterogeneous Objects` (use generics to get compile time errors). +* Because it creates a new copy of array everytime iterator is created, `performance is slower than ArrayList`. +* We can prefer to use CopyOnWriteArrayList over normal ArrayList in following cases: + + - When list is to be used in concurrent environemnt. + - Iterations outnumber the mutation operations. + - Iterators must have snapshot version of list at the time when they were created. + - We don\'t want to synchronize the thread access programatically. + +```java + import java.util.concurrent.CopyOnWriteArrayList; + CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(); + copyOnWriteArrayList.add("captain america"); + Iterator it = copyOnWriteArrayList.iterator(); //iterator creates separate snapshot + copyOnWriteArrayList.add("iron man"); //doesn't throw ConcurrentModificationException + while(it.hasNext()) + System.out.println(it.next()); // prints captain america only , since add operation is after returning iterator + + it = copyOnWriteArrayList.iterator(); //fresh snapshot + while(it.hasNext()) + System.out.println(it.next()); // prints captain america and iron man, + + it = copyOnWriteArrayList.iterator(); //fresh snapshot + while(it.hasNext()){ + System.out.println(it.next()); + it.remove(); //mutable operation 'remove' not allowed ,throws UnsupportedOperationException + } + + ArrayList list = new ArrayList(); + list.add("A"); + Iterator ait = list.iterator(); + list.add("B"); // immediately throws ConcurrentModificationException + while(ait.hasNext()) + System.out.println(ait.next()); + + ait = list.iterator(); + while(ait.hasNext()){ + System.out.println(ait.next()); + ait.remove(); //mutable operation 'remove' allowed without any exception + } +``` + + + +## # 10. JAVA STRINGS + +
+ +## Q. What is the difference between creating String as new() and literal? + +When 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. + +**Example:** + +```java +/** + * String literal + */ +String a = "abc"; +String b = "abc"; +System.out.println(a == b); // true + +/** + * Using new() + */ +String c = new String("abc"); +String d = new String("abc"); +System.out.println(c == d); // false +``` + + + +## Q. What is difference between String, StringBuffer and StringBuilder? + +**1. Mutability Difference:** + +`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. + +**2. Thread-Safety Difference:** + +The 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. + +**Example:** + +```java +/** + * StringBuffer + */ +public class BufferTest { + public static void main(String[] args) { + StringBuffer buffer = new StringBuffer("Hello"); + buffer.append(" World"); + System.out.println(buffer); + } +} +``` + +**Example:** + +```java +/** + * StringBuilder + */ +public class BuilderTest { + public static void main(String[] args) { + StringBuilder builder = new StringBuilder("Hello"); + builder.append(" World"); + System.out.println(builder); + } +} +``` + + + +## Q. Why string is immutable in java? + +The 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. + +Since string is immutable it can safely share between many threads and avoid any synchronization issues in java. + + + +## Q. What is Java String Pool? + +String 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. + +When 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. + +```java +/** + * String Pool + */ +public class StringPool { + + public static void main(String[] args) { + String s1 = "Java"; + String s2 = "Java"; + String s3 = new String("Java"); + + System.out.println("s1 == s2 :" + (s1 == s2)); // true + System.out.println("s1 == s3 :" + (s1 == s3)); // false + } +} +``` + + + +## Q. What is difference between String, StringBuilder and StringBuffer? + +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. + +The 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. + +**Situations:** + +* If your string is not going to change use a String class because a `String` object is immutable. +* 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. +* If your string can change, and will be accessed from multiple threads, use a `StringBuffer` because `StringBuffer` is synchronous so you have thread-safety. + +**Example:** + +```java +class StringExample { + + // Concatenates to String + public static void concat1(String s1) { + s1 = s1 + "World"; + } + + // Concatenates to StringBuilder + public static void concat2(StringBuilder s2) { + s2.append("World"); + } + + // Concatenates to StringBuffer + public static void concat3(StringBuffer s3) { + s3.append("World"); + } + + public static void main(String[] args) { + String s1 = "Hello"; + concat1(s1); // s1 is not changed + System.out.println("String: " + s1); + + StringBuilder s2 = new StringBuilder("Hello"); + concat2(s2); // s2 is changed + System.out.println("StringBuilder: " + s2); + + StringBuffer s3 = new StringBuffer("Hello"); + concat3(s3); // s3 is changed + System.out.println("StringBuffer: " + s3); + } +} +``` + +Output + +```java +String: Hello +StringBuilder: World +StringBuffer: World +``` + + + +## Q. What is StringJoiner? + +The 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: + +```java +StringJoiner joiner = new StringJoiner ( " . " , " Prefix- " , " -suffix " ); +for ( String s : " Hello the brave world " . split ( " " )) { + , joiner, . add (s); +} +System.out.println(joiner); // prefix-Hello.the.brave.world-suffix +``` + + + +## # 11. JAVA REFLECTION + +
+ +## Q. What is Java Reflection API? + +Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at **runtime**. + +The **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. + +* forName() method of Class class +* getClass() method of Object class +* the .class syntax + +**1. forName() method:** + +* is used to load the class dynamically. +* returns the instance of Class class. +* It should be used if you know the fully qualified name of class.This cannot be used for primitive types. + +```java +/** + * forName() + */ +class Simple { +} + +class Test { + public static void main(String args[]) { + Class c = Class.forName("Simple"); + System.out.println(c.getName()); + } +} +``` + +Output + +```java +Simple +``` + +**2. getClass() method:** + +It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives. + +```java +/** + * getClass + */ +class Simple { +} + +class Test { + void printName(Object obj) { + Class c = obj.getClass(); + System.out.println(c.getName()); + } + + public static void main(String args[]) { + Simple s = new Simple(); + Test t = new Test(); + t.printName(s); + } +} +``` + +Output + +```java +Simple +``` + +**3. The .class syntax:** + +If 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. + +```java +/** + * .class Syntax + */ +class Test { + public static void main(String args[]) { + Class c = boolean.class; + System.out.println(c.getName()); + + Class c2 = Test.class; + System.out.println(c2.getName()); + } +} +``` + +Output + +```java +boolean +Test +``` + + + +## # 12. JAVA STREAMS + +
+ +## Q. What is Stream? + +An interface `java.util.Stream` is a sequence of elements on which various operations can be performed. + +Operations 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. + +A 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()`). + +Streams are created based on sources of some, for example, classes from `java.util.Collection`. + +Associative arrays (maps), for example `HashMap`, are not supported. + +Operations on streams can be performed both sequentially and in parallel. + +Streams cannot be reused. As soon as some final operation has been called, the flow is closed. + +In 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: + +* use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`; +* support additional end operations `sum()`, `average()`, `mapToObj()`. + + + +## Q. What are the ways to create a stream? + +* Using collection: + +```java +Stream < String > fromCollection = Arrays.asList ( " x " , " y " , " z " ).stream (); +``` + +* Using set of values: + +```java +Stream < String > fromValues = Stream.of( " x " , " y " , " z " ); +``` + +* Using Array + +```java +Stream < String > fromArray = Arrays.stream( new String [] { " x " , " y " , " z " }); +``` + +* Using file (each line in the file will be a separate element in the stream): + +```java +Stream < String > fromFile = Files.lines( Paths.get(" input.txt ")); +``` + +* From the line: + +```java +IntStream fromString = " 0123456789 " . chars (); +``` + +* With the help of `Stream.builder()`: + +```java +Stream < String > fromBuilder = Stream.builder().add (" z ").add(" y ").add(" z ").build (); +``` + +* Using `Stream.iterate()(infinite)`: + +```java +Stream < Integer > fromIterate = Stream.iterate ( 1 , n - > n + 1 ); +``` + +* Using `Stream.generate()(infinite)`: + +```java +Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); +``` + + + +## Q. What is the difference between `Collection` and `Stream`? + +Collections 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. + + + +## Q. What is the method `collect()`for streams for? + +A method `collect()`is the final operation that is used to represent the result as a collection or some other data structure. + +`collect()`accepts an input that contains four stages: + +* **supplier** — initialization of the battery, +* **accumulator** — processing of each element, +* **combiner** — connection of two accumulators in parallel execution, +* **[finisher]** —a non-mandatory method of the last processing of the accumulator. + +In Java 8, the class `Collectors` implements several common collectors: + +* `toList()`, `toCollection()`, `toSet()`- present stream in the form of a list, collection or set; +* `toConcurrentMap()`, `toMap()`- allow you to convert the stream to `Map`; +* `averagingInt()`, `averagingDouble()`, `averagingLong()`- return the average value; +* `summingInt()`, `summingDouble()`, `summingLong()`- returns the sum; +* `summarizingInt()`, `summarizingDouble()`, `summarizingLong()`- return SummaryStatisticswith different values of the aggregate; +* `partitioningBy()`- divides the collection into two parts according to the condition and returns them as `Map`; +* `groupingBy()`- divides the collection into several parts and returns `Map>`; +* `mapping()`- Additional value conversions for complex Collectors. + +There is also the possibility of creating your own collector through `Collector.of()`: + +```java +Collector < String , a List < String > , a List < String > > toList = Collector.of ( + ArrayList :: new , + List :: add, + (l1, l2) -> {l1 . addAll (l2); return l1; } +); +``` + + + +## Q. Why do streams use `forEach()`and `forEachOrdered()` methods? + +* `forEach()` applies a function to each stream object; ordering in parallel execution is not guaranteed; +* `forEachOrdered()` applies a function to each stream object while maintaining the order of the elements. + + + +## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream? + +The method `map()`is an intermediate operation, which transforms each element of the stream in a specified way. + +`mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`, returns the corresponding numerical stream (ie the stream of numerical primitives): +```java +Stream + .of ( " 12 " , " 22 " , " 4 " , " 444 " , " 123 " ) + .mapToInt ( Integer :: parseInt) + .toArray (); // [12, 22, 4, 444, 123] +``` + + + +## Q. What is the purpose of `filter()` method in streams? + +The method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition. + + + +## Q. What is the use of `limit()` method in streams? + +The method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements. + + + +## Q. What is the use of `sorted()` method in streams? + +The method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator. + +The order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation. + + + +## Q. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`? + +The 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. + +```java +Stream + .of ( " Hello " , " world! " ) + .flatMap ((p) -> Arrays.stream (p . split ( " , " ))) + .toArray ( String [] :: new ); // ["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"] +``` + +`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. + + + +## Q. What are the final methods of working with streams you know? + +* `findFirst()` returns the first element +* `findAny()` returns any suitable item +* `collect()` presentation of results in the form of collections and other data structures +* `count()` returns the number of elements +* `anyMatch()`returns trueif the condition is satisfied for at least one element +* `noneMatch()`returns trueif the condition is not satisfied for any element +* `allMatch()`returns trueif the condition is satisfied for all elements +* `min()`returns the minimum element, using as a condition Comparator +* `max()`returns the maximum element, using as a condition Comparator +* `forEach()` applies a function to each object (order is not guaranteed in parallel execution) +* `forEachOrdered()` applies a function to each object while preserving the order of elements +* `toArray()` returns an array of values +* `reduce()`allows you to perform aggregate functions and return a single result. +* `sum()` returns the sum of all numbers +* `average()` returns the arithmetic mean of all numbers. + + + +## Q. What intermediate methods of working with streams do you know? + +* `filter()` filters records, returning only records matching the condition; +* `skip()` allows you to skip a certain number of elements at the beginning; +* `distinct()`returns a stream without duplicates (for a method `equals()`); +* `map()` converts each element; +* `peek()` returns the same stream, applying a function to each element; +* `limit()` allows you to limit the selection to a certain number of first elements; +* `sorted()`allows you to sort values ​​either in natural order or by setting `Comparator`; +* `mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`return stream numeric primitives; +* `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- similar to `map()`, but can create a single element more. + +For numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream. + + + +#### Q. Explain Difference between Collection API and Stream API? + +*ToDo* + + + +## # 13. JAVA REGULAR EXPRESSIONS + +
+ +## Q. Name some classes present in java.util.regex package? + +The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. + +**Regular Expression Package:** + +* MatchResult interface +* Matcher class +* Pattern class +* PatternSyntaxException class + +**Example:** + +```java +/** + * Regular Expression + */ +import java.util.regex.*; + +public class Index { + public static void main(String args[]) { + + // Pattern, String + boolean b = Pattern.matches(".s", "as"); + + System.out.println("Match: " + b); + } +} +``` + + + +## # 14. JAVA FILE HANDLING + +
+ +## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? + +`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. + +**Example:** + +```java +/** + * BufferedInputStream + */ +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +public class BufferedInputStreamExample { + + public static void main(String[] args) { + File file = new File("file.txt"); + FileInputStream fileInputStream = null; + BufferedInputStream bufferedInputStream = null; + + try { + fileInputStream = new FileInputStream(file); + bufferedInputStream = new BufferedInputStream(fileInputStream); + // Create buffer + byte[] buffer = new byte[1024]; + int bytesRead = 0; + while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { + System.out.println(new String(buffer, 0, bytesRead)); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (fileInputStream != null) { + fileInputStream.close(); + } + if (bufferedInputStream != null) { + bufferedInputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} +``` + +Output + +```java +This is an example of reading data from file +``` + +**Example:** + +```java +/** + * BufferedOutputStream + */ +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +public class BufferedOutputStreamExample { + + public static void main(String[] args) { + File file = new File("outfile.txt"); + FileOutputStream fileOutputStream = null; + BufferedOutputStream bufferedOutputStream = null; + try { + fileOutputStream = new FileOutputStream(file); + bufferedOutputStream = new BufferedOutputStream(fileOutputStream); + bufferedOutputStream.write("This is an example of writing data to a file".getBytes()); + bufferedOutputStream.flush(); + + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (fileOutputStream != null) { + fileOutputStream.close(); + } + if (bufferedOutputStream != null) { + bufferedOutputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} +``` + +Output + +```java +This is an example of writing data to a file +``` + + + +## Q. How to set the Permissions to a file in Java? + +Java 7 has introduced PosixFilePermission Enum and **java.nio.file.Files** includes a method setPosixFilePermissions( Path path, `Set perms` ) that can be used to set file permissions easily. + +**Example:** + +```java +/** + * FilePermissions + */ +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermission; +import java.util.HashSet; +import java.util.Set; + +public class FilePermissions { + + public static void main(String[] args) throws IOException { + File file = new File("/Users/file.txt"); + + // change permission to 777 for all the users + // no option for group and others + file.setExecutable(true, false); + file.setReadable(true, false); + file.setWritable(true, false); + + // using PosixFilePermission to set file permissions 777 + Set perms = new HashSet(); + + // add owners permission + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_WRITE); + perms.add(PosixFilePermission.OWNER_EXECUTE); + + // add group permissions + perms.add(PosixFilePermission.GROUP_READ); + perms.add(PosixFilePermission.GROUP_WRITE); + perms.add(PosixFilePermission.GROUP_EXECUTE); + + // add others permissions + perms.add(PosixFilePermission.OTHERS_READ); + perms.add(PosixFilePermission.OTHERS_WRITE); + perms.add(PosixFilePermission.OTHERS_EXECUTE); + + Files.setPosixFilePermissions(Paths.get("/Users/run.sh"), perms); + } +} +``` + + + +## Q. Give the hierarchy of InputStream and OutputStream classes? + +A stream can be defined as a sequence of data. There are two kinds of Streams − + +* **InPutStream** − The InputStream is used to read data from a source. +* **OutPutStream** − The OutputStream is used for writing data to a destination. + +**1. Byte Streams:** + +Java 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. + +**Example:** + +```java +/** + * Byte Streams + */ +import java.io.*; + +public class CopyFile { + + public static void main(String args[]) throws IOException { + FileInputStream in = null; + FileOutputStream out = null; + + try { + in = new FileInputStream("input.txt"); + out = new FileOutputStream("output.txt"); + + int c; + while ((c = in.read()) != -1) { + out.write(c); + } + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } +} +``` + +**2. Character Streams:** + +Java 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. + +**Example:** + +```java +/** + * Character Streams + */ +import java.io.*; + +public class CopyFile { + + public static void main(String args[]) throws IOException { + FileReader in = null; + FileWriter out = null; + + try { + in = new FileReader("input.txt"); + out = new FileWriter("output.txt"); + + int c; + while ((c = in.read()) != -1) { + out.write(c); + } + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } +} +``` + + + +## Q. How serialization works in java? + +Serialization 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. + +**Example:** + +```java +/** +* Serialization and Deserialization +*/ +import java.io.*; + +class Employee implements Serializable { + private static final long serialversionUID = 129348938L; + transient int a; + static int b; + String name; + int age; + + // Default constructor + public Employee(String name, int age, int a, int b) { + this.name = name; + this.age = age; + this.a = a; + this.b = b; + } +} + +public class SerialExample { + + public static void printdata(Employee object1) { + System.out.println("name = " + object1.name); + System.out.println("age = " + object1.age); + System.out.println("a = " + object1.a); + System.out.println("b = " + object1.b); + } + + public static void main(String[] args) { + Employee object = new Employee("ab", 20, 2, 1000); + String filename = "file.txt"; + + // Serialization + try { + // Saving of object in a file + FileOutputStream file = new FileOutputStream(filename); + ObjectOutputStream out = new ObjectOutputStream(file); + + // Method for serialization of object + out.writeObject(object); + + out.close(); + file.close(); + + System.out.println("Object has been serialized\n" + + "Data before Deserialization."); + printdata(object); + // value of static variable changed + object.b = 2000; + } catch (IOException ex) { + System.out.println("IOException is caught"); + } + + object = null; + + // Deserialization + try { + // Reading the object from a file + FileInputStream file = new FileInputStream(filename); + ObjectInputStream in = new ObjectInputStream(file); + + // Method for deserialization of object + object = (Employee) in.readObject(); + + in.close(); + file.close(); + System.out.println("Object has been deserialized\n" + + "Data after Deserialization."); + printdata(object); + System.out.println("z = " + object1.z); + } catch (IOException ex) { + System.out.println("IOException is caught"); + } catch (ClassNotFoundException ex) { + System.out.println("ClassNotFoundException is caught"); + } + } +} +``` + + + +## # 15. JAVA EXCEPTIONS + +
+ +## Q. What are the types of Exceptions? + +Exception is an error event that can happen during the execution of a program and disrupts its normal flow. + +**1. Checked Exception**: + +The 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. + +**2. Unchecked Exception**: + +The 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. + +**3. Error**: + +Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. + + + +## Q. Explain hierarchy of Java Exception classes? + +The **java.lang.Throwable** class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. + +

+ Exception in Java +

+ +**Example:** + +```java +/** + * Exception classes + */ +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +public class CustomExceptionExample { + + public static void main(String[] args) throws MyException { + try { + processFile("file.txt"); + } catch (MyException e) { + processErrorCodes(e); + } + } + + private static void processErrorCodes(MyException e) throws MyException { + switch(e.getErrorCode()){ + case "BAD_FILE_TYPE": + System.out.println("Bad File Type, notify user"); + throw e; + case "FILE_NOT_FOUND_EXCEPTION": + System.out.println("File Not Found, notify user"); + throw e; + case "FILE_CLOSE_EXCEPTION": + System.out.println("File Close failed, just log it."); + break; + default: + System.out.println("Unknown exception occured," +e.getMessage()); + e.printStackTrace(); + } + } + + private static void processFile(String file) throws MyException { + InputStream fis = null; + try { + fis = new FileInputStream(file); + } catch (FileNotFoundException e) { + throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION"); + } finally { + try { + if(fis !=null) fis.close(); + } catch (IOException e) { + throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION"); + } + } + } +} +``` + + + +## Q. What is difference between Error and Exception? + +|BASIS FOR COMPARISON |ERROR |EXCEPTION | +|-----------------------|-----------------------------------------|----------------------------------------| +|Basic |An error is caused due to lack of system resources.|An exception is caused because of the code.| +|Recovery |An error is irrecoverable. |An exception is recoverable.| +|Keywords |There is no means to handle an error by the program code.| Exceptions are handled using three keywords "try", "catch", and "throw".| +|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.| +|Types |Errors are classified as unchecked type.|Exceptions are classified as checked or unchecked type.| +|Package |In Java, errors are defined "java.lang.Error" package.|In Java, an exceptions are defined in"java.lang.Exception".| +|Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.| + + + +## Q. Explain about Exception Propagation? + +An 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. + +**Example:** + +```java +/** + * Exception Propagation + */ +class TestExceptionPropagation { + + void method1() { + int data = 10 / 0; // generates an exception + System.out.println(data); + } + + void method2() { + method1(); // doesn't catch the exception + } + + void method3() { // method3 catches the exception + try { + method2(); + } catch (Exception e) { + System.out.println("Exception is caught"); + } + } + + public static void main(String args[]) { + TestExceptionPropagation obj = new TestExceptionPropagation(); + obj.method3(); + } +} +``` + + + +## Q. What are different scenarios causing "Exception in thread main"? + +Some of the common main thread exception are as follows: + +* **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. + +* **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. + +* **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. + +* **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. + + + +## Q. What are the differences between throw and throws? + +**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. + +**Example:** + +```java +/** + * Throw in Java + */ +public class ThrowExample { + void checkAge(int age) { + if (age < 18) + throw new ArithmeticException("Not Eligible for voting"); + else + System.out.println("Eligible for voting"); + } + + public static void main(String args[]) { + ThrowExample obj = new ThrowExample(); + obj.checkAge(13); + System.out.println("End Of Program"); + } +} +``` + +Output + +```java +Exception in thread "main" java.lang.ArithmeticException: +Not Eligible for voting +at Example1.checkAge(Example1.java:4) +at Example1.main(Example1.java:10) +``` + +**Example:** + +```java +/** + * Throws in Java + */ +public class ThrowsExample { + int division(int a, int b) throws ArithmeticException { + int t = a / b; + return t; + } + + public static void main(String args[]) { + ThrowsExample obj = new ThrowsExample(); + try { + System.out.println(obj.division(15, 0)); + } catch (ArithmeticException e) { + System.out.println("You shouldn't divide number by zero"); + } + } +} +``` + +Output + +```java +You shouldn\'t divide number by zero +``` + + + +## Q. While overriding a method can you throw another exception or broader exception? + +If 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. + +**Example:** + +```java +class A { + public void message() throws IOException {..} +} + +class B extends A { + @Override + public void message() throws SocketException {..} // allowed + + @Override + public void message() throws SQLException {..} // NOT allowed + + public static void main(String args[]) { + A a = new B(); + try { + a.message(); + } catch (IOException ex) { + // forced to catch this by the compiler + } + } +} +``` + + + +## Q. What is checked, unchecked exception and errors? + +**1. Checked Exception**: + +* These are the classes that extend **Throwable** except **RuntimeException** and **Error**. +* 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. +* 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). + +**Example:** **IOException, SQLException** etc. + +```java +import java.io.*; + +class Main { + public static void main(String[] args) { + FileReader file = new FileReader("C:\\assets\\file.txt"); + BufferedReader fileInput = new BufferedReader(file); + + for (int counter = 0; counter < 3; counter++) + System.out.println(fileInput.readLine()); + + fileInput.close(); + } +} +``` + +output: + +```java +Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - +unreported exception java.io.FileNotFoundException; must be caught or declared to be +thrown + at Main.main(Main.java:5) +``` + +After adding IOException + +```java +import java.io.*; + +class Main { + public static void main(String[] args) throws IOException { + FileReader file = new FileReader("C:\\assets\\file.txt"); + BufferedReader fileInput = new BufferedReader(file); + + for (int counter = 0; counter < 3; counter++) + System.out.println(fileInput.readLine()); + + fileInput.close(); + } +} +``` + +output: + +```java +Output: First three lines of file “C:\assets\file.txt” +``` + +**2. Unchecked Exception**: + +* The classes that extend **RuntimeException** are known as unchecked exceptions. +* Unchecked exceptions are not checked at compile-time, but rather at **runtime**, hence the name. +* They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration. + +**Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. + +```java +class Main { + public static void main(String args[]) { + int x = 0; + int y = 10; + int z = y/x; + } +} +``` + +Output: + +```java +Exception in thread "main" java.lang.ArithmeticException: / by zero + at Main.main(Main.java:5) +Java Result: 1 +``` + +**3. Error**: + +**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. +Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. + + + +## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? + +`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. + +`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. + +`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. + + + +## # 16. JAVA INHERITANCE + +
+ +## Q. What is the difference between aggregation and composition? + +**1. Aggregation:** + +We call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object. + +**Example:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes + +```java +/** + * Aggregation + */ +public class Organization { + private List employees; +} + +public class Person { + private String name; +} +``` + +**2. Composition:** + +We 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. + +**Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. + +```java +/** + * Composition + */ +public class Car { + //final will make sure engine is initialized + private final Engine engine; + + public Car(){ + engine = new Engine(); + } +} + +class Engine { + private String type; +} +``` + +

+ Aggregation +

+ + + + + + + + + + + + +
AggregationComposition
Aggregation is a weak Association.Composition is a strong Association.
Class can exist independently without owner.Class can not meaningfully exist without owner.
Have their own Life Time.Life Time depends on the Owner.
A uses B.A owns B.
Child is not owned by 1 owner.Child can have only 1 owner.
Has-A relationship. A has B.Part-Of relationship. B is part of A.
Denoted by a empty diamond in UML.Denoted by a filled diamond in UML.
We do not use "final" keyword for Aggregation."final" keyword is used to represent Composition.
Examples:
- Car has a Driver.
- A Human uses Clothes.
- A Company is an aggregation of People.
- A Text Editor uses a File.
- Mobile has a SIM Card.
Examples:
- Engine is a part of Car.
- A Human owns the Heart.
- A Company is a composition of Accounts.
- A Text Editor owns a Buffer.
- IMEI Number is a part of a Mobile.
+ +*Note: "final" keyword is used in Composition to make sure child variable is initialized.* + + + +## Q. The difference between Inheritance and Composition? + +Though 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"**. + +**Example:** Inheritance + +```java +/** + * Inheritance + */ +class Fruit { + // ... +} + +class Apple extends Fruit { + // ... +} +``` + +**Example:** Composition + +```java +/** + * Composition + */ +class Fruit { + // ... +} + +class Apple { + private Fruit fruit = new Fruit(); + // ... +} +``` + + + +## Q. Can you declare the main method as final? + +Yes. 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. + +The 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. + +**Example:** + +```java +public class Test { + public final static void main(String[] args) throws Exception { + System.out.println("This is Test Class"); + } +} + +class Child extends Test { + public static void main(String[] args) throws Exception { + System.out.println("This is Child Class"); + } +} +``` + +Output + +```java +Cannot override the final method from Test. +``` + + + +## Q. What is covariant return type? + +It 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. + +**Example:** + +```java +/** + * Covariant Return Type + */ +class SuperClass { + SuperClass get() { + System.out.println("SuperClass"); + return this; + } +} + +public class Tester extends SuperClass { + Tester get() { + System.out.println("SubClass"); + return this; + } + + public static void main(String[] args) { + SuperClass tester = new Tester(); + tester.get(); + } +} +``` + +Output: + +```java +Subclass +``` + + + +## Q. Can you explain Liskov Substitution principle? + +Liskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.** + +Given 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. + +`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**. + +```java +public class MediaPlayer { + + // Play audio implementation + public void playAudio() { + System.out.println("Playing audio..."); + } + + // Play video implementation + public void playVideo() { + System.out.println("Playing video..."); + } +} + +public class VlcMediaPlayer extends MediaPlayer {} + +public class WinampMediaPlayer extends MediaPlayer { + + // Play video is not supported in Winamp player + public void playVideo() { + throw new VideoUnsupportedException(); + } +} + +public class VideoUnsupportedException extends RuntimeException { + + private static final long serialVersionUID = 1 L; + +} + +public class ClientTestProgram { + + public static void main(String[] args) { + + // Created list of players + List < MediaPlayer > allPlayers = new ArrayList < MediaPlayer > (); + allPlayers.add(new VlcMediaPlayer()); + allPlayers.add(new DivMediaPlayer()); + + // Play video in all players + playVideoInAllMediaPlayers(allPlayers); + + // Well - all works as of now...... :-) + System.out.println("---------------------------"); + + // Now adding new Winamp player + allPlayers.add(new WinampMediaPlayer()); + + // Again play video in all players & Oops it broke the program... :-( + // Why we got unexpected behavior in client? --- Because LSP is violated in WinampMediaPlayer.java, + // as it changed the original behavior of super class MediaPlayer.java + playVideoInAllMediaPlayers(allPlayers); + } + + /** + * This method is playing video in all players + * + * @param allPlayers + */ + public static void playVideoInAllMediaPlayers(List < MediaPlayer > allPlayers) { + + for (MediaPlayer player: allPlayers) { + player.playVideo(); + } + } +} +``` + +Let\'s refactor the code to make "good" design using **LSP**? +- `MediaPlayer` is super class having play audio ability. +- `VideoMediaPlayer` extends `MediaPlayer` and adds play video ability. +- `DivMediaPlayer` and `VlcMediaPlayer` both extends `VideoMediaPlayer` for playing audio and video ability. +- `WinampMediaPlayer` which extends `MediaPlayer` for playing audio ability only. +- so client program can substitute `DivMediaPlayer` or `VlcMediaPlayer` for their super class `VideoMediaPlayer` + +lets reimplement the refactored code + +```java +public class MediaPlayer { + + // Play audio implementation + public void playAudio() { + System.out.println("Playing audio..."); + } +} + +//separated video playing ability from base class +public class VideoMediaPlayer extends MediaPlayer { + + // Play video implementation + public void playVideo() { + System.out.println("Playing video..."); + } +} + +public class DivMediaPlayer extends VideoMediaPlayer {} + +public class VlcMediaPlayer extends VideoMediaPlayer {} + +//as Winamp expects only audio playing ability, so it must only extend relative base class behaviour, no need to inherit unnecessary behaviour +public class WinampMediaPlayer extends MediaPlayer {} + + /** + * This method is playing video in all players + * + * @param allPlayers + */ + public static void playVideoInAllMediaPlayers(List allPlayers) { + + for (VideoMediaPlayer player: allPlayers) { + player.playVideo(); + } + } +``` + +Now, 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 +that satisefies *Liskov's substitution principle*. + + + +## # 17. JAVA METHOD OVERRIDING + +
+ +## # 18. JAVA POLYMORPHISM + +
+ +## Q. What is the difference between compile-time polymorphism and runtime polymorphism? + +There are two types of polymorphism in java: + +1. Static Polymorphism also known as Compile time polymorphism +2. Runtime polymorphism also known as Dynamic Polymorphism + +**1. Static Polymorphism:** + +Method 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. + +**Example:** + +```java +/** + * Static Polymorphism + */ +class SimpleCalculator { + int add(int a, int b) { + return a + b; + } + + int add(int a, int b, int c) { + return a + b + c; + } +} + +public class Demo { + public static void main(String args[]) { + SimpleCalculator obj = new SimpleCalculator(); + System.out.println(obj.add(10, 20)); + System.out.println(obj.add(10, 20, 30)); + } +} +``` + +Output + +```java +30 +60 +``` + +**2. Runtime Polymorphism:** + +It 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. + +**Example:** + +```java +/** + * Runtime Polymorphism + */ +class ABC { + + public void myMethod() { + System.out.println("Overridden Method"); + } +} + +public class XYZ extends ABC { + + public void myMethod() { + System.out.println("Overriding Method"); + } + + public static void main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } +} +``` + +Output: + +```java +Overriding Method +``` + + + +## Q. What do you mean Run time Polymorphism? + +`Polymorphism` in Java is a concept by which we can perform a single action in different ways. +There are two types of polymorphism in java: + +* **Static Polymorphism** also known as compile time polymorphism +* **Dynamic Polymorphism** also known as runtime polymorphism + +**Example:** Static Polymorphism + +```java +class SimpleCalculator { + + int add(int a, int b) { + return a + b; + } + int add(int a, int b, int c) { + return a + b + c; + } +} +public class MainClass +{ + public static void main(String args[]) { + SimpleCalculator obj = new SimpleCalculator(); + System.out.println(obj.add(10, 20)); + System.out.println(obj.add(10, 20, 30)); + } +} +``` + +Output + +```java +30 +60 +``` + +**Example:** Runtime polymorphism + +```java +class ABC { + public void myMethod() { + System.out.println("Overridden Method"); + } +} +public class XYZ extends ABC { + + public void myMethod() { + System.out.println("Overriding Method"); + } + public static void main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } +} +``` + +Output + +```java +Overriding Method +``` + + + +## Q. What is runtime polymorphism in java? + +**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. + +An 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. + +```java +class Bank{ + public float roi=0.0f; +float getRateOfInterest(){return this.roi;} +} +class SBI extends Bank{ + float roi=8.4f; +float getRateOfInterest(){return this.roi;} +} +class ICICI extends Bank{ + float roi=7.3f; +float getRateOfInterest(){return this.roi;} +} +class AXIS extends Bank{ + float roi=9.7f; +float getRateOfInterest(){return this.roi;} +} + +Bank b; +b=new SBI(); +System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); + +b=new ICICI(); +System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); + +b=new AXIS(); +System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); + +System.out.println("Bank Rate of Interest: "+b.roi); + +/**output: +SBI Rate of Interest: 8.4 +ICICI Rate of Interest: 7.3 +AXIS Rate of Interest: 9.7 +Bank Rate of Interest: 0.0 + +//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. +**/ +``` + + + +## # 19. JAVA ABSTRACTION + +
+ +## Q. What is the difference between abstract class and interface? + +Abstract 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. + +|Abstract Class |Interface | +|-----------------------------|---------------------------------| +|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.| +|Abstract class doesn\'t support multiple inheritance.|Interface supports multiple inheritance.| +|Abstract class can have final, non-final, static and non-static variables.|Interface has only static and final variables.| +|Abstract class can provide the implementation of interface.|Interface can\'t provide the implementation of abstract class.| +|An abstract class can extend another Java class and implement multiple Java interfaces.|An interface can extend another Java interface only.| +|An abstract class can be extended using keyword "extends".|An interface can be implemented using keyword "implements".| +|A Java abstract class can have class members like private, protected, etc.|Members of a Java interface are public by default.| + + + +## Q. What are Wrapper classes? + +The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. + +**Use of Wrapper classes in Java:** + +* **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. + +* **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. + +* **Synchronization**: Java synchronization works with objects in Multithreading. + +* **java.util package**: The java.util package provides the utility classes to deal with objects. + +* **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. + +| Sl.No|Primitive Type | Wrapper class | +|------|----------------|----------------------| +| 01. |boolean |Boolean| +| 02. |char |Character| +| 03. |byte |Byte| +| 04. |short |Short| +| 05. |int |Integer| +| 06. |long |Long| +| 07. |float |Float| +| 08. |double |Double| + +**Example:** Primitive to Wrapper + +```java +/** + * Java program to convert primitive into objects + * Autoboxing example of int to Integer + */ +class WrapperExample { + public static void main(String args[]) { + int a = 20; + Integer i = Integer.valueOf(a); // converting int into Integer explicitly + Integer j = a; // autoboxing, now compiler will write Integer.valueOf(a) internally + + System.out.println(a + " " + i + " " + j); + } +} +``` + +Output + +```java +20 20 20 +``` + + + +## Q. What is the difference between abstraction and encapsulation? + +In 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. + +Abstraction 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. + +**Difference:** + + + + + + + + + + + + + +
AbstractionEncapsulation
Abstraction is a process of hiding the implementation details and showing only functionality to the user. Encapsulation is a process of wrapping code and data together into a single unit
Abstraction lets you focus on what the object does instead of how it does it.Encapsulation provides you the control over the data and keeping it safe from outside misuse.
Abstraction solves the problem in the Design Level.Encapsulation solves the problem in the Implementation Level.
Abstraction is implemented by using Interfaces and Abstract Classes.Encapsulation is implemented by using Access Modifiers (private, default, protected, public)
Abstraction means hiding implementation complexities by using interfaces and abstract class.Encapsulation means hiding data by using setters and getters.
+ + + +## # 20. JAVA INTERFACES + +
+ +## Q. Can we use private or protected member variables in an interface? + +The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically + +```java +public interface Test { + public string name1; + private String email; + protected pass; +} +``` + +as 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. + +```java +public interface Test { + public static final string name1; + public static final String email; + public static final pass; +} +``` + +* Interfaces cannot be instantiated that is why the variable are **static** +* Interface are used to achieve the 100% abstraction there for the variable are **final** +* 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** + + + +## Q. When can an object reference be cast to a Java interface reference? + +An interface reference can point to any object of a class that implements this interface + ```java -public class Sample -{ - public static void main(String[] args) { - // Using Console to input data from user - String name = System.console().readLine(); - System.out.println(name); - } +/** + * Interface + */ +interface MyInterface { + void display(); +} + +public class TestInterface implements MyInterface { + + void display() { + System.out.println("Hello World"); + } + + public static void main(String[] args) { + MyInterface myInterface = new TestInterface(); + MyInterface.display(); + } } ``` + -## Q. ***How can you avoid serialization in child class if the base class is implementing the Serializable interface?*** -If 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. +## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface? + +If 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. + ```java +/** + * Serialization + */ import java.io.FileOutputStream; import java.io.IOException; import java.io.NotSerializableException; @@ -1393,52 +3657,54 @@ import java.io.OutputStream; import java.io.Serializable; class Super implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } - + class Sub extends Super { - + private static final long serialVersionUID = 1L; private Integer id; - + public Sub(Integer id) { - this.id = id; + this.id = id; } - + @Override public String toString() { - return "Employee [id=" + id + "]"; + return "Employee [id=" + id + "]"; } - + /* - * define how Serialization process will write objects. + * define how Serialization process will write objects. */ - private void writeObject(ObjectOutputStream os) throws NotSerializableException { - throw new NotSerializableException("This class cannot be Serialized"); - } + private void writeObject(ObjectOutputStream os) throws NotSerializableException { + throw new NotSerializableException("This class cannot be Serialized"); + } } - + public class SerializeDeserialize { - + public static void main(String[] args) { - - Sub object1 = new Sub(8); - try { - OutputStream fout = new FileOutputStream("ser.txt"); - ObjectOutput oout = new ObjectOutputStream(fout); - System.out.println("Serialization process has started, serializing objects..."); - oout.writeObject(object1); - fout.close(); - oout.close(); - System.out.println("Object Serialization completed."); - } catch (IOException e) { - e.printStackTrace(); - } + + Sub object1 = new Sub(8); + try { + OutputStream fout = new FileOutputStream("ser.txt"); + ObjectOutput oout = new ObjectOutputStream(fout); + System.out.println("Serialization process has started, serializing objects..."); + oout.writeObject(object1); + fout.close(); + oout.close(); + System.out.println("Object Serialization completed."); + } catch (IOException e) { + e.printStackTrace(); + } } } ``` + Output -``` + +```java Serialization process has started, serializing objects... java.io.NotSerializableException: This class cannot be Serialized at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) @@ -1453,814 +3719,643 @@ java.io.NotSerializableException: This class cannot be Serialized at java.io.ObjectOutputStream.writeObject(Unknown Source) at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) ``` + -## Q. ***What is the difference between Serializable and Externalizable interface?*** +## Q. What is the difference between Serializable and Externalizable interface? -|Sl.No |SERIALIZABLE | EXTERNALIZABLE | -|----|----------------|-----------------------| -| 01.|Serializable is a marker interface i.e. does not contain any method.| Externalizable interface contains two methods writeExternal() and readExternal() which implementing classes MUST override.| -| 02.|Serializable interface pass the responsibility of serialization to JVM and it’s default algorithm.| Externalizable provides control of serialization logic to programmer – to write custom logic.| -| 03.|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.| -| 04.|It’s hard to analyze and modify class structure because any change may break the serialization.| It’s more easy to analyze and modify class structure because of complete control over serialization logic.| -| 05.|Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. | +|SERIALIZABLE |EXTERNALIZABLE | +|----------------|-----------------------| +|Serializable is a marker interface i.e. does not contain any method.| Externalizable interface contains two methods writeExternal() and readExternal() which implementing classes MUST override.| +|Serializable interface pass the responsibility of serialization to JVM and it\'s default algorithm.| Externalizable provides control of serialization logic to programmer – to write custom logic.| +|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.| +|It\'s hard to analyze and modify class structure because any change may break the serialization.| It\'s more easy to analyze and modify class structure because of complete control over serialization logic.| +|Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. | -## Q. ***What are the ways to instantiate the Class class?*** -**1. Using new keyword** -```java -MyObject object = new MyObject(); -``` -**2. Using Class.forName()** -```java -MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); -``` -**3. Using clone()** +## Q. How to create marker interface? + +An 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. + +**Syntax:** + ```java -MyObject anotherObject = new MyObject(); -MyObject object = (MyObject) anotherObject.clone(); +public interface Interface_Name { + +} ``` -**4. Using object deserialization** + +**Example:** + ```java -ObjectInputStream inStream = new ObjectInputStream(anInputStream ); -MyObject object = (MyObject) inStream.readObject(); -``` - +/** + * Maker Interface + */ +interface Marker { +} -## Q. ***What is the purpose of using javap?*** -The 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. +class MakerExample implements Marker { + // do some task +} - ```java -class Simple { - public static void main(String args[]) { - System.out.println("Hello World"); - } -} -``` -``` -cmd> javap Simple.class -``` -Output -``` -Compiled from ".java" -class Simple { - Simple(); - public static void main(java.lang.String[]); -} +class Main { + public static void main(String[] args) { + MakerExample obj = new MakerExample(); + if (obj instanceOf Marker) { + // do some task + } + } +} ``` + -## Q. ***What are autoboxing and unboxing? When does it occur?*** -The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. +## Q. Can you declare an interface method static? -Example: Autoboxing -```java -class BoxingExample1 { - public static void main(String args[]) { - int a = 50; - Integer a2 = new Integer(a); //Boxing - Integer a3 = 5; //Boxing - - System.out.println(a2+" "+a3); - } -} -``` +Java 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. -Example: Unboxing -```java -class UnboxingExample1 { - public static void main(String args[]) { - Integer i = new Integer(50); - int a = i; - - System.out.println(a); - } -} -``` -## Q. ***What is a native method?*** -A 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: +## Q. What is a Functional Interface? -**Main.java** -```java -public class Main { - public native int intMethod(int i); - public static void main(String[] args) { - System.loadLibrary("Main"); - System.out.println(new Main().intMethod(2)); - } -} -``` -**Main.c** -```c -#include -#include "Main.h" +A **functional interface** is an interface that defines only one abstract method. + +To 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. + +An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. -JNIEXPORT jint JNICALL Java_Main_intMethod( - JNIEnv *env, jobject obj, jint i) { - return i * i; -} -``` -**Compile and run** -``` -javac Main.java -javah -jni Main -gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \ - -I${JAVA_HOME}/include/linux Main.c -java -Djava.library.path=. Main -``` -Output -``` -4 -``` -## Q. ***What is immutable object? Can you write immutable object?*** -Immutable 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. +## Q. What are `default` interface methods? -**Creating an Immutable Object** - -* Do not add any setter method -* Declare all fields final and private -* If a field is a mutable object create defensive copies of it for getter methods -* If a mutable object passed to the constructor must be assigned to a field create a defensive copy of it -* Don't allow subclasses to override methods. +Java 8 allows you to add non-abstract method implementations to an interface using the keyword default: ```java -public class DateContainer { - private final Date date; - public DateContainer() { - this.date = new Date(); - } - public Date getDate() { - return new Date(date.getTime()); - } +interface Example { + int process ( int a ); + default void show () { + System.out.println("default show ()"); + } } ``` + +* 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. +* 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. +* The default method cannot override the class method `java.lang.Object`. +* They help implement interfaces without fear of disrupting other classes. +* Avoid creating utility classes, since all the necessary methods can be represented in the interfaces themselves. +* They give classes the freedom to choose the method to be redefined. +* One of the main reasons for introducing default methods is the ability of collections in Java 8 to use lambda expressions. + -## Q. ***The difference between Inheritance and Composition?*** -Though 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"**. +## Q. How to call `default` interface method in a class that implements this interface? + +Using the keyword superalong with the interface name: -Example: Inheritance -```java -class Fruit { - //... -} -class Apple extends Fruit { - //... -} -``` -Example: Composition ```java -class Fruit { - //... +interface Paper { + default void show () { + System.out.println(" default show ()"); + } } -class Apple { - private Fruit fruit = new Fruit(); - //... + +class License implements Paper { + public void show () { + Paper.super.show(); + } } ``` + -## Q. ***The difference between DOM and SAX parser in Java?*** -DOM and SAX parser are extensively used to read and parse XML file in java and have their own set of advantage and disadvantage. +## Q. What is `static` interface method? + +Static interface methods are similar to default methods, except that there is no way to override them in classes that implement the interface. -| |DOM (Document Object Model) |Parser SAX (Simple API for XML) Parser | -|-----------------|--------------------------------|--------------------------------------------------| -|Abbreviation |DOM stands for Document Object Model| SAX stands for Simple API for XML Parsing | -|type |Load entire memory and keep in tree structure| event based parser | -|size of Document |good for smaller size |good to choose for larger size of file. | -|Load |Load entire document in memory |does not load entire document. | -|suitable |better suitable for smaller and efficient memory| SAX is suitable for larger XML doc| +* Static methods in the interface are part of the interface without the ability to use them for objects of the implementation class +* Class methods `java.lang.Object`cannot be overridden as static +* Static methods in the interface are used to provide helper methods, for example, checking for null, sorting collections, etc. -## Q. ***What is the difference between creating String as new() and literal?*** -When 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. +## Q. How to call `static` interface method? + +Using the interface name: + ```java -String a = "abc"; -String b = "abc"; -System.out.println(a == b); // true +interface Paper { + static void show () { + System.out.println( " static show () " ); + } +} -String c = new String("abc"); -String d = new String("abc"); -System.out.println(c == d); // false +class License { + public void showPaper () { + Paper.show (); + } +} ``` + -## Q. ***How can we create an immutable class in Java?*** -Immutable 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. +## Q. What are the functional interfaces `Function`, `DoubleFunction`, `IntFunction` and `LongFunction`? -**Rules to create immutable classes** +`Function`- 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`. -* The class must be declared as final (So that child classes can’t be created) -* Data members in the class must be declared as final (So that we can’t change the value of it after object creation) -* A parameterized constructor -* Getter method for all the variables in it -* No setters(To not have the option to change the value of the instance variable) +Default methods can be used to build call chains ( `compose`, `andThen`). ```java -public final class Employee { - - final String pancardNumber; - - public Employee(String pancardNumber) { - this.pancardNumber = pancardNumber; - } - public String getPancardNumber() { - return pancardNumber; - } -} +Function < String , Integer > toInteger = Integer :: valueOf; +Function < String , String > backToString = toInteger.andThen ( String :: valueOf); +backToString.apply("123"); // "123" ``` + +* `DoubleFunction`- a function that receives input `Double` and returns an instance of the class at the output `R`; +* `IntFunction`- a function that receives input `Integer`and returns an instance of the class at the output `R`; +* `LongFunction`- a function that receives input `Long`and returns an instance of the class at the output `R`. + -## Q. ***What is difference between String, StringBuffer and StringBuilder?*** -**Mutability Difference:** `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. +## Q. What are the functional interfaces `UnaryOperator`, `DoubleUnaryOperator`, `IntUnaryOperator`and `LongUnaryOperator`? -**Thread-Safety Difference:** The 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. +`UnaryOperator`(**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`: -Example: StringBuffer ```java -public class BufferTest{ - public static void main(String[] args){ - StringBuffer buffer=new StringBuffer("Hello"); - buffer.append(" World"); - System.out.println(buffer); - } -} +UnaryOperator < Integer > operator = x - > x * x; +System.out.println(operator.apply ( 5 )); // 25 ``` -Example: StringBuilder + +* `DoubleUnaryOperator`- unary operator receiving input `Double`; +* `IntUnaryOperator`- unary operator receiving input `Integer`; +* `LongUnaryOperator`- unary operator receiving input `Long`. + + + +## Q. What are the functional interfaces `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`? + +`BinaryOperator`(**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`. + ```java -public class BuilderTest{ - public static void main(String[] args){ - StringBuilder builder=new StringBuilder("Hello"); - builder.append(" World"); - System.out.println(builder); - } -} +BinaryOperator < Integer > operator = (a, b) -> a + b; +System.out.println(operator.apply ( 1 , 2 )); // 3 ``` + +* `DoubleBinaryOperator`- binary operator receiving input Double; +* `IntBinaryOperator`- binary operator receiving input Integer; +* `LongBinaryOperator`- binary operator receiving input Long. + -## Q. ***What is a Memory Leak? How can a memory leak appear in garbage collected language?*** -The 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. +## Q. What are the functional interfaces `Predicate`, `DoublePredicate`, `IntPredicateand` `LongPredicate`? -Some tools that do memory management to identifies useless objects or memeory leaks like: +`Predicate`(**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`. -* HP OpenView -* HP JMETER -* JProbe -* IBM Tivoli +The interface contains a variety of methods by default, allow to build complex conditions ( `and`, `or`, `negate`). ```java -// Java Program to illustrate memory leaks -import java.util.Vector; -public class MemoryLeaksDemo -{ - public static void main(String[] args) { - Vector v = new Vector(214444); - Vector v1 = new Vector(214744444); - Vector v2 = new Vector(214444); - System.out.println("Memory Leaks Example"); - } -} -``` -Output -``` -Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed +Predicate < String > predicate = (s) -> s.length () > 0 ; +predicate.test("foo"); // true +predicate.negate().test("foo"); // false ``` -**Types of Memory Leaks in Java** +* `DoublePredicate`- predicate receiving input `Double`; +* `IntPredicate`- predicate receiving input `Integer`; +* `LongPredicate`- predicate receiving input `Long`. -* Memory Leak through static Fields -* Unclosed Resources/connections -* Adding Objects With no `hashCode()` and `equals()` Into a HashSet -* Inner Classes that Reference Outer Classes -* Through `finalize()` Methods -* Calling `String.intern()` on Long String -## Q. ***Why String is popular HashMap key in Java?*** -Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys. +## Q. What are the functional interfaces `Consumer`, `DoubleConsumer`, `IntConsumer`and `LongConsumer`? - +`Consumer`(**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. -## Q. ***What is difference between Error and Exception?*** +```java +Consumer hello = (name) -> System.out.println( " Hello, " + name); +hello.accept( " world " ); +``` -|BASIS FOR COMPARISON |ERROR |EXCEPTION | -|-----------------------|-----------------------------------------|----------------------------------------| -|Basic |An error is caused due to lack of system resources.|An exception is caused because of the code.| -|Recovery |An error is irrecoverable. |An exception is recoverable.| -|Keywords |There is no means to handle an error by the program code.| Exceptions are handled using three keywords "try", "catch", and "throw".| -|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.| -|Types |Errors are classified as unchecked type.|Exceptions are classified as checked or unchecked type.| -|Package |In Java, errors are defined "java.lang.Error" package.|In Java, an exceptions are defined in"java.lang.Exception".| -|Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.| +* `DoubleConsumer`- the consumer receiving the input `Double`; +* `IntConsumer`- the consumer receiving the input `Integer`; +* `LongConsumer`- the consumer receiving the input `Long`. -## Q. ***Explain about Exception Propagation?*** -An 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. -```java -class TestExceptionPropagation { +## Q. What are the functional interfaces `Supplier`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier`and `LongSupplier`? - void m() { - int data = 50/0; - } - void n() { - m(); - } - void p() { - try { - n(); - } catch(Exception e) { - System.out.println("exception handled"); - } - } - public static void main(String args[]) { - TestExceptionPropagation obj = new TestExceptionPropagation(); - obj.p(); - System.out.println("Normal Flow..."); - } -} +`Supplier`(**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`; + +```java +Supplier < LocalDateTime > now = LocalDateTime::now; +now.get(); ``` + +* `DoubleSupplier`- the supplier is returning `Double`; +* `IntSupplier`- the supplier is returning `Integer`; +* `LongSupplier`- the supplier is returning `Long`. + -## Q. ***What are different scenarios causing "Exception in thread main"?*** -Some of the common main thread exception are as follows: -* **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. -* **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. -* **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. -* **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. +#### Q. What is Spliterator in Java SE 8? +#### Q. What is Type Inference in Java 8? +#### Q. What is difference between External Iteration and Internal Iteration? + +*ToDo* -## Q. ***What are the differences between throw and throws?*** -**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. +## # 21. JAVA ENCAPSULATION + +
+ +## Q. How Encapsulation concept implemented in JAVA? + +Encapsulation 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`. + +To achieve encapsulation in Java − + +* Declare the variables of a class as private. +* Provide public setter and getter methods to modify and view the variables values. + +**Example:** + +```java +public class EncapClass { + private String name; + + public String getName() { + return name; + } + public void setName(String newName) { + name = newName; + } +} + +public class MainClass { -**Throw Example** -```java -public class ThrowExample { - void checkAge(int age) { - if(age < 18) - throw new ArithmeticException("Not Eligible for voting"); - else - System.out.println("Eligible for voting"); - } - public static void main(String args[]) { - ThrowExample obj = new ThrowExample(); - obj.checkAge(13); - System.out.println("End Of Program"); - } -} -``` -Output -``` -Exception in thread "main" java.lang.ArithmeticException: -Not Eligible for voting -at Example1.checkAge(Example1.java:4) -at Example1.main(Example1.java:10) -``` -**Throws Example** -```java -public class ThrowsExample { - int division(int a, int b) throws ArithmeticException { - int t = a/b; - return t; - } - public static void main(String args[]) { - ThrowsExample obj = new ThrowsExample(); - try { - System.out.println(obj.division(15,0)); - } - catch(ArithmeticException e) { - System.out.println("You shouldn't divide number by zero"); - } - } + public static void main(String args[]) { + EncapClass obj = new EncapClass(); + obj.setName("Pradeep Kumar"); + System.out.print("Name : " + obj.getName()); + } } ``` -Output -``` -You shouldn't divide number by zero -``` + -## Q. ***The difference between Serial and Parallel Garbage Collector?*** -**Serial Garbage Collector** +## # 22. JAVA GENERICS -Serial 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. - -Turn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector. - -**Parallel Garbage Collector** +
-Parallel 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. +## Q. Do you know Generics? How did you used in your coding? - +`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. -## Q. ***What is difference between WeakReference and SoftReference in Java?*** -In Java there are four types of references differentiated on the way by which they are garbage collected. +**Advantages:** -* Strong References -* Weak References -* Soft References -* Phantom References +* **Type-safety**: We can hold only a single type of objects in generics. It doesn\'t allow to store other objects. +* **Type Casting**: There is no need to typecast the object. +* **Compile-Time Checking**: It is checked at compile time so problem will not occur at runtime. -**Strong References**: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null. -```java -MyClass obj = new MyClass(); -``` +**Example:** -**Weak References**: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. ```java -//Java Code to illustrate Weak reference -import java.lang.ref.WeakReference; -class MainClass -{ - public void message() { - System.out.println("Weak References Example"); - } -} +/** +* A Simple Java program to show multiple +* type parameters in Java Generics +* +* We use < > to specify Parameter type +* +**/ +class GenericClass { + T obj1; // An object of type T + U obj2; // An object of type U -public class Example -{ - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); - - // Creating Weak Reference to MainClass-type object to which 'g' - // is also pointing. - WeakReference weakref = new WeakReference(g); - g = null; - g = weakref.get(); - g.message(); - } -} -``` - -**Soft References**: In 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. -```java -//Java Code to illustrate Weak reference -import java.lang.ref.SoftReference; -class MainClass -{ - public void message() { - System.out.println("Weak References Example"); + // constructor + GenericClass(T obj1, U obj2) { + this.obj1 = obj1; + this.obj2 = obj2; } -} -public class Example -{ - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); - - // Creating Weak Reference to MainClass-type object to which 'g' - // is also pointing. - SoftReference softref = new SoftReference(g); - g = null; - g = softref.get(); - g.message(); - } -} -``` -**Phantom References**: The objects which are being referenced by phantom references are eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called ‘reference queue’ . They are put in a reference queue after calling finalize() method on them.To create such references java.lang.ref.PhantomReference class is used. -```java -//Java Code to illustrate Weak reference -import java.lang.ref.*; -class MainClass -{ - public void message() { - System.out.println("Phantom References Example"); + // To print objects of T and U + public void print() { + System.out.println(obj1); + System.out.println(obj2); } } -public class Example -{ - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); - - // Creating Phantom Reference to MainClass-type object to which 'g' - // is also pointing. - PhantomReference phantomRef = null; - phantomRef = new PhantomReference(g,refQueue); - g = null; - g = phantomRef.get(); - g.message(); +// Driver class to test above +class MainClass { + public static void main (String[] args) { + GenericClass obj = + new GenericClass("Generic Class Example !", 100); + + obj.print(); } -} +} ``` - - -## Q. ***What is a compile time constant in Java? What is the risk of using it?*** -If 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. - -**Compile time constant must be:** -* declared final -* primitive or String -* initialized within declaration -* initialized with constant expression +Output: -They 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. ```java -private final int x = 10; +Generic Class Example ! +100 ``` + -## Q. ***How bootstrap class loader works in java?*** +## # 23. MISCELLANEOUS -Bootstrap **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: +
-**1. Bootstrap Class Loader** – It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes +## Q. How will you invoke any external process in Java? -**2. Extensions Class Loader** – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory. +In java, external process can be invoked using **exec()** method of **Runtime Class**. -**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. +**Example:** ```java -import java.util.logging.Level; -import java.util.logging.Logger; - /** - * Java program to demonstrate How ClassLoader works in Java - * - **/ + * exec() + */ +import java.io.IOException; -public class ClassLoaderTest { +class ExternalProcessExample { + public static void main(String[] args) { + try { + // Command to create an external process + String command = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; - public static void main(String args[]) { - try { - //printing ClassLoader of this class - System.out.println("ClassLoader : "+ ClassLoaderTest.class.getClassLoader()); - - //trying to explicitly load this class again using Extension class loader - Class.forName("Explicitly load class", true - , ClassLoaderTest.class.getClassLoader().getParent()); - } catch (ClassNotFoundException ex) { - Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex); - } + // Running the above command + Runtime run = Runtime.getRuntime(); + Process proc = run.exec(command); + } catch (IOException e) { + e.printStackTrace(); + } } } ``` + -## Q. ***Why string is immutable in java?*** +## Q. What is the static import? -The 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. +The 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. -Since string is immutable it can safely share between many threads and avoid any synchronization issues in java. +```java +/** + * Static Import + */ +import static java.lang.System.*; + +class StaticImportExample { + + public static void main(String args[]) { + out.println("Hello");// Now no need of System.out + out.println("Java"); + } +} +``` -## Q. ***What is Java String Pool?*** +## Q. What is the difference between factory and abstract factory pattern? -String 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. +The 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. -When 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. +**Example:** credit card validator factory which returns a different validator for each card type. ```java /** -* Java program to illustrate String Pool -* -**/ -public class StringPool { - - public static void main(String[] args) { - String s1 = "Java"; - String s2 = "Java"; - String s3 = new String("Java"); - - System.out.println("s1 == s2 :" +(s1==s2)); // true - System.out.println("s1 == s3 :" +(s1==s3)); // false + * Abstract Factory Pattern + */ +public ICardValidator GetCardValidator (string cardType) +{ + switch (cardType.ToLower()) + { + case "visa": + return new VisaCardValidator(); + case "mastercard": + case "ecmc": + return new MastercardValidator(); + default: + throw new CreditCardTypeException("Do not recognise this type"); } } ``` + +Abstract 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. + +In 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. + -## Q. ***How Garbage collector algorithm works?*** -Garbage 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. +## Q. What are the methods used to implement for key Object in HashMap? + +**1. equals()** and **2. hashcode()** + +Class inherits methods from the following classes in terms of HashMap -There 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 +* java.util.AbstractMap +* java.util.Object +* java.util.Map -## Q. ***How to create marker interface?*** -An 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. Example: **Serializable, Clonnable** etc. +## Q. What is a Memory Leak? -Syntax: -```java -public interface Interface_Name { +The 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. + +Some tools that do memory management to identifies useless objects or memeory leaks like: + +* HP OpenView +* HP JMETER +* JProbe +* IBM Tivoli + +**Example:** -} -``` -Example: ```java /** -* Java program to illustrate Maker Interface -* -**/ -interface Marker { } + * Memory Leaks + */ +import java.util.Vector; -class A implements Marker { - //do some task +public class MemoryLeaksExample { + public static void main(String[] args) { + Vector v = new Vector(214444); + Vector v1 = new Vector(214744444); + Vector v2 = new Vector(214444); + System.out.println("Memory Leaks Example"); + } } +``` -class Main { - public static void main(String[] args) { - A obj = new A(); - if (obj instanceOf Marker){ - // do some task - } - } -} +Output + +```java +Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ``` + +**Types of Memory Leaks in Java:** + +* Memory Leak through static Fields +* Unclosed Resources/connections +* Adding Objects With no `hashCode()` and `equals()` Into a HashSet +* Inner Classes that Reference Outer Classes +* Through `finalize()` Methods +* Calling `String.intern()` on Long String + -## Q. ***How serialization works in java?*** -Serialization 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. +## Q. The difference between Serial and Parallel Garbage Collector? -Example: -```java -/** -* Serialization and Deserialization -* example of a Java object -* -**/ -import java.io.*; - -class Employee implements Serializable { -private static final long serialversionUID = - 129348938L; - transient int a; - static int b; - String name; - int age; - - // Default constructor - public Employee(String name, int age, int a, int b) { - this.name = name; - this.age = age; - this.a = a; - this.b = b; - } -} - -public class SerialExample { +**1. Serial Garbage Collector:** + +Serial 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. + +Turn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector. + +**2. Parallel Garbage Collector:** + +Parallel 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. - public static void printdata(Employee object1) { - System.out.println("name = " + object1.name); - System.out.println("age = " + object1.age); - System.out.println("a = " + object1.a); - System.out.println("b = " + object1.b); - } - - public static void main(String[] args) { - Employee object = new Employee("ab", 20, 2, 1000); - String filename = "shubham.txt"; - - // Serialization - try { - // Saving of object in a file - FileOutputStream file = new FileOutputStream(filename); - ObjectOutputStream out = new ObjectOutputStream(file); - - // Method for serialization of object - out.writeObject(object); - - out.close(); - file.close(); - - System.out.println("Object has been serialized\n" - + "Data before Deserialization."); - printdata(object); - // value of static variable changed - object.b = 2000; - } - catch (IOException ex) { - System.out.println("IOException is caught"); - } - - object = null; - - // Deserialization - try { - // Reading the object from a file - FileInputStream file = new FileInputStream(filename); - ObjectInputStream in = new ObjectInputStream(file); - - // Method for deserialization of object - object = (Employee)in.readObject(); - - in.close(); - file.close(); - System.out.println("Object has been deserialized\n" - + "Data after Deserialization."); - printdata(object); - System.out.println("z = " + object1.z); - } - catch (IOException ex) { - System.out.println("IOException is caught"); - } - catch (ClassNotFoundException ex) { - System.out.println("ClassNotFoundException is caught"); - } - } -} -``` -## Q. ***What are the various ways to load a class in Java?*** +## Q. What is difference between WeakReference and SoftReference in Java? + +**1. Weak References:** -**a). Creating a reference**: -```java -SomeClass someInstance = null; -``` +Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. -**b). Using Class.forName(String)**: ```java - Class.forName("SomeClass"); -``` +/** + * Weak Reference + */ +import java.lang.ref.WeakReference; -**c). Using SystemClassLoader()**: -```java -ClassLoader.getSystemClassLoader().loadClass("SomeClass"); +class MainClass { + public void message() { + System.out.println("Weak References Example"); + } +} + +public class Example { + public static void main(String[] args) { + // Strong Reference + MainClass g = new MainClass(); + g.message(); + + // Creating Weak Reference to MainClass-type object to which 'g' + // is also pointing. + WeakReference weakref = new WeakReference(g); + g = null; + g = weakref.get(); + g.message(); + } +} ``` -**d). Using Overloaded Class.forName()**: +**2. Soft References:** + +In 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. + ```java -Class.forName(String name, boolean initialize, ClassLoader loader); +/** + * Soft Reference + */ +import java.lang.ref.SoftReference; + +class MainClass { + public void message() { + System.out.println("Soft References Example"); + } +} + +public class Example { + public static void main(String[] args) { + // Strong Reference + MainClass g = new MainClass(); + g.message(); + + // Creating Soft Reference to MainClass-type object to which 'g' + // is also pointing. + SoftReference softref = new SoftReference(g); + g = null; + g = softref.get(); + g.message(); + } +} ``` + + + +## Q. How Garbage collector algorithm works? + +Garbage 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. + +There 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 + -## Q. ***Java Program to Implement Singly Linked List?*** +## Q. Java Program to Implement Singly Linked List? + +The 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. -The 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. +**Example:** -Example: ```java public class SinglyLinkedList { // Represent a node of the singly linked list @@ -2330,163 +4425,29 @@ public class SinglyLinkedList { } } ``` + **Output:** + ```java Nodes of singly linked list: 10 20 30 40 ``` - - -## Q. ***While overriding a method can you throw another exception or broader exception?*** - -If 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. - -Example: -```java -class A { - public void message() throws IOException {..} -} - -class B extends A { - @Override - public void message() throws SocketException {..} // allowed - - @Override - public void message() throws SQLException {..} // NOT allowed - - public static void main(String args[]) { - A a = new B(); - try { - a.message(); - } catch (IOException ex) { - // forced to catch this by the compiler - } - } -} -``` - - -## Q. ***What is checked, unchecked exception and errors?*** - -**1. Checked Exception**: - -* These are the classes that extend **Throwable** except **RuntimeException** and **Error**. -* 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. -* 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). -* Example: **IOException, SQLException** etc. - -```java -import java.io.*; - -class Main { - public static void main(String[] args) { - FileReader file = new FileReader("C:\\assets\\file.txt"); - BufferedReader fileInput = new BufferedReader(file); - - for (int counter = 0; counter < 3; counter++) - System.out.println(fileInput.readLine()); - - fileInput.close(); - } -} -``` -output: -``` -Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - -unreported exception java.io.FileNotFoundException; must be caught or declared to be -thrown - at Main.main(Main.java:5) -``` -After adding IOException -```java -import java.io.*; - -class Main { - public static void main(String[] args) throws IOException { - FileReader file = new FileReader("C:\\assets\\file.txt"); - BufferedReader fileInput = new BufferedReader(file); - - for (int counter = 0; counter < 3; counter++) - System.out.println(fileInput.readLine()); - - fileInput.close(); - } -} -``` -output: -```java -Output: First three lines of file “C:\assets\file.txt” -``` - -**2. Unchecked Exception**: - -* The classes that extend **RuntimeException** are known as unchecked exceptions. -* Unchecked exceptions are not checked at compile-time, but rather at **runtime**, hence the name. -* They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration. -* Example: **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. - -```java -class Main { - public static void main(String args[]) { - int x = 0; - int y = 10; - int z = y/x; - } -} -``` -Output: -```java -Exception in thread "main" java.lang.ArithmeticException: / by zero - at Main.main(Main.java:5) -Java Result: 1 -``` - -**3. Error**: - -**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. -Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. - - - -## Q. ***What is difference between ClassNotFoundException and NoClassDefFoundError?*** -`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. - -`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. - -`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. -## Q. ***What do we mean by weak reference?*** -In Java there are four types of references differentiated on the way by which they are garbage collected. - -1. Strong Reference -1. Weak Reference -1. Soft Reference -1. Phantom Reference +## Q. What do we mean by weak reference? -**1. Strong Reference**: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null. -```java -StrongReferenceClass obj = new StrongReferenceClass(); -``` -Here `obj` object is strong reference to newly created instance of MyClass, currently obj is active object so can't be garbage collected. - -**2. Weak Reference**: A weakly referenced object is cleared by the Garbage Collector when it’s weakly reachable. +A weakly referenced object is cleared by the Garbage Collector when it\'s weakly reachable. Weak 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. + ```java /** -* Java Code to illustrate Weak reference -* -**/ +* Weak reference +*/ import java.lang.ref.WeakReference; + class WeakReferenceExample { public void message() { @@ -2511,153 +4472,21 @@ public class MainClass { } } ``` + Output -``` -Weak Reference Example! -Weak Reference Example! -``` -**3. Soft Reference**: In 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. -```java -/** -* Java Code to illustrate Soft reference -* -**/ -import java.lang.ref.SoftReference; -class SoftReferenceExample { - - public void message() { - System.out.println("Soft Reference Example!"); - } -} - -public class MainClass { - - public static void main(String[] args) { - // Soft Reference - SoftReferenceExample obj = new SoftReferenceExample(); - obj.message(); - - // Creating Soft Reference to SoftReferenceExample-type object to which 'obj' - // is also pointing. - SoftReference softref = new SoftReference(obj); - - obj = null; // is available for garbage collection. - obj = softref.get(); - obj.message(); - } -} -``` -Output -``` -Soft Reference Example! -Soft Reference Example! -``` -**4. Phantom Reference**: The objects which are being referenced by phantom references are eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called **reference queue**. They are put in a reference queue after calling finalize() method on them. To create such references `java.lang.ref.PhantomReference` class is used. -```java -/** -* Code to illustrate Phantom reference -* -**/ -import java.lang.ref.*; -class PhantomReferenceExample { - - public void message() { - System.out.println("Phantom Reference Example!"); - } -} - -public class MainClass { - - public static void main(String[] args) { - - //Strong Reference - PhantomReferenceExample obj = new PhantomReferenceExample(); - obj.message(); - - //Creating reference queue - ReferenceQueue refQueue = new ReferenceQueue(); - - //Creating Phantom Reference to PhantomReferenceExample-type object to which 'obj' - //is also pointing. - PhantomReference phantomRef = null; - phantomRef = new PhantomReference(obj, refQueue); - obj = null; - obj = phantomRef.get(); //It always returns null - obj.message(); //It shows NullPointerException - } -} -``` - - -## Q. ***What do you mean Run time Polymorphism?*** -`Polymorphism` in Java is a concept by which we can perform a single action in different ways. -There are two types of polymorphism in java: - -* **Static Polymorphism** also known as compile time polymorphism -* **Dynamic Polymorphism** also known as runtime polymorphism - -Example: Static Polymorphism -```java -class SimpleCalculator { - - int add(int a, int b) { - return a + b; - } - int add(int a, int b, int c) { - return a + b + c; - } -} -public class MainClass -{ - public static void main(String args[]) { - SimpleCalculator obj = new SimpleCalculator(); - System.out.println(obj.add(10, 20)); - System.out.println(obj.add(10, 20, 30)); - } -} -``` -Output -``` -30 -60 -``` -Example: Runtime polymorphism -```java -class ABC { - public void myMethod() { - System.out.println("Overridden Method"); - } -} -public class XYZ extends ABC { - - public void myMethod() { - System.out.println("Overriding Method"); - } - public static void main(String args[]) { - ABC obj = new XYZ(); - obj.myMethod(); - } -} -``` -Output -``` -Overriding Method -``` - -## Q. ***If I do not have Explicit constructor in parent class and having in child class, while calling the child constructor jvm automatically calls Implicit Constructor of parent class?*** -If the subclass constructor does not specify which superclass constructor to invoke then the compiler will automatically call the accessible no-args constructor in the superclass. +```java +Weak Reference Example! +Weak Reference Example! +``` -## Q. ***What are the different types of JDBC Driver?*** -JDBC Driver is a software component that enables java application to interact with the database. +## Q. What are the different types of JDBC Driver? + +JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers: 1. **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. @@ -2666,324 +4495,124 @@ There are 4 types of JDBC drivers: 1. **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. -## Q. ***How Encapsulation concept implemented in JAVA?*** -Encapsulation 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`. +## Q. What additional methods for working with associative arrays (maps) appeared in Java 8? -To achieve encapsulation in Java − -* Declare the variables of a class as private. -* Provide public setter and getter methods to modify and view the variables values. +* `putIfAbsent()` adds a key-value pair only if the key was missing: -Example: ```java -public class EncapClass { - private String name; - - public String getName() { - return name; - } - public void setName(String newName) { - name = newName; - } -} +map.putIfAbsent("a", "Aa"); +``` -public class MainClass { +* `forEach()` accepts a function that performs an operation on each element: - public static void main(String args[]) { - EncapClass obj = new EncapClass(); - obj.setName("Pradeep Kumar"); - System.out.print("Name : " + obj.getName()); - } -} +```java +map.forEach((k, v) -> System.out.println(v)); ``` - - -## Q. ***Do you know Generics? How did you used in your coding?*** -`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. -**Advantages** -* **Type-safety**: We can hold only a single type of objects in generics. It doesn't allow to store other objects. -* **Type Casting**: There is no need to typecast the object. -* **Compile-Time Checking**: It is checked at compile time so problem will not occur at runtime. +* `compute()` creates or updates the current value to the result of the calculation (it is possible to use the key and the current value): -Example: ```java -/** -* A Simple Java program to show multiple -* type parameters in Java Generics -* -* We use < > to specify Parameter type -* -**/ -class GenericClass { - T obj1; // An object of type T - U obj2; // An object of type U - - // constructor - GenericClass(T obj1, U obj2) { - this.obj1 = obj1; - this.obj2 = obj2; - } - - // To print objects of T and U - public void print() { - System.out.println(obj1); - System.out.println(obj2); - } -} - -// Driver class to test above -class MainClass { - public static void main (String[] args) { - GenericClass obj = - new GenericClass("Generic Class Example !", 100); - - obj.print(); - } -} +map.compute("a", (k, v) -> String.valueOf(k).concat(v)); //["a", "aAa"] ``` -Output: -``` -Generic Class Example ! -100 -``` - -## Q. ***What is difference between String, StringBuilder and StringBuffer?*** -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. +* `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): -The 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. +```java +map.computeIfPresent("a", (k, v) -> k.concat(v)); +``` -**Situations**: -* If your string is not going to change use a String class because a `String` object is immutable. -* 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. -* If your string can change, and will be accessed from multiple threads, use a `StringBuffer` because `StringBuffer` is synchronous so you have thread-safety. +* `computeIfAbsent()` if the key is missing, creates it with the value that is calculated (it is possible to use the key): -Example: ```java -class StringExample { - - // Concatenates to String - public static void concat1(String s1) { - s1 = s1 + "World"; - } - - // Concatenates to StringBuilder - public static void concat2(StringBuilder s2) { - s2.append("World"); - } - - // Concatenates to StringBuffer - public static void concat3(StringBuffer s3) { - s3.append("World"); - } - - public static void main(String[] args) { - String s1 = "Hello"; - concat1(s1); // s1 is not changed - System.out.println("String: " + s1); - - StringBuilder s2 = new StringBuilder("Hello"); - concat2(s2); // s2 is changed - System.out.println("StringBuilder: " + s2); - - StringBuffer s3 = new StringBuffer("Hello"); - concat3(s3); // s3 is changed - System.out.println("StringBuffer: " + s3); - } -} +map.computeIfAbsent("a", k -> "A".concat(k)); //["a","Aa"] ``` -Output + +* `getOrDefault()` if there is no key, returns the passed value by default: + +```java +map.getOrDefault("a", "not found"); ``` -String: Hello -StringBuilder: World -StringBuffer: World + +* `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. + +```java +map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] ``` + -## Q. ***How can we create a object of a class without using new operator?*** -Different ways to create an object in Java -* **Using new Keyword** +## Q. What is LocalDateTime? -```java -class ObjectCreationExample{ - String Owner; -} -public class MainClass { - public static void main(String[] args) { - // Here we are creating Object of JBT using new keyword - ObjectCreationExample obj = new ObjectCreationExample(); - } -} +`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. -``` -* **Using New Instance (Reflection)** + -```java -class CreateObjectClass { - static int j = 10; - CreateObjectClass() { - i = j++; - } - int i; - @Override - public String toString() { - return "Value of i :" + i; - } -} +## Q. What is ZonedDateTime? -class MainClass { - public static void main(String[] args) { - try { - Class cls = Class.forName("CreateObjectClass"); - CreateObjectClass obj = (CreateObjectClass) cls.newInstance(); - CreateObjectClass obj1 = (CreateObjectClass) cls.newInstance(); - System.out.println(obj); - System.out.println(obj1); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } -} +`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. -``` -* **Using Clone** + -```java - class CreateObjectWithClone implements Cloneable { - @Override - protected Object clone() throws CloneNotSupportedException { - return super.clone(); - } - int i; - static int j = 10; - CreateObjectWithClone() { - i = j++; - } - @Override - public String toString() { - return "Value of i :" + i; - } -} +## Q. How to determine repeatable annotation? -class MainClass { - public static void main(String[] args) { - CreateObjectWithClone obj1 = new CreateObjectWithClone(); - System.out.println(obj1); - try { - CreateObjectWithClone obj2 = (CreateObjectWithClone) obj1.clone(); - System.out.println(obj2); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - } -} -``` -* **Using ClassLoader** +To define a repeatable annotation, you must create a container annotation for the list of repeatable annotations and designate a repeatable meta annotation `@Repeatable`: ```java -class CreateObjectWithClassLoader { - static int j = 10; - CreateObjectWithClassLoader() { - i = j++; - } - int i; - @Override - public String toString() { - return "Value of i :" + i; - } +@interface Schedulers { + Scheduler [] value (); } -public class MainClass { - public static void main(String[] args) { - CreateObjectWithClassLoader obj = null; - try { - obj = (CreateObjectWithClassLoader) new MainClass().getClass() - .getClassLoader().loadClass("CreateObjectWithClassLoader").newInstance(); - // Fully qualified classname should be used. - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - System.out.println(obj); - } -} +@Repeatable ( Schedulers . Class) + @interface Scheduler { + String birthday () default "Jan 8 2000"; + } ``` - - -## Q. ***What code coverage tools are you using for your project?*** -* Cobertura -## Q. ***Scenario of browser’s browsing history, where you need to store the browsing history, what data structure will you use.?*** -* use `stack` +## Q. What class appeared in Java 8 for encoding / decoding data? - +`Base64`- a thread-safe class that implements a data encoder and decoder using a base64 encoding scheme according to RFC 4648 and RFC 2045 . + +Base64 contains 6 basic methods: -## Q. ***Scenario where in we have to download a big file by clicking on a link, how will you make sure that connections is reliable throughout?*** -* use `persistent MQueues` +`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 ; +`getMimeEncoder() / getMimeDecoder()`- returns a MIME encoder / decoder conforming to RFC 2045 . -## Q. ***What are methods of Object Class?*** -The Object class is the parent class of all the classes in java by default. +## Q. How to create a Base64 encoder and decoder? - - - - - - - - - - - - - -
MethodDescription
public final Class getClass()returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedExceptioncauses the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
+```java +// Encode +String b64 = Base64.getEncoder().encodeToString ( " input " . getBytes ( " utf-8 " )); // aW5wdXQ == +// Decode +new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // input +``` -#### Q. ***What is copyonwritearraylist in java?*** -#### Q. ***How do you test static method?*** -#### Q. ***How to do you test a method for an exception using JUnit?*** -#### Q. ***Which unit testing libraries you have used for testing Java programs?*** -#### Q. ***What is the difference between @Before and @BeforeClass annotation?*** -#### Q. ***Can you explain Liskov Substitution principle?*** -#### Q. ***Give me an example of design pattern which is based upon open closed principle?*** -#### Q. ***What is Law of Demeter violation? Why it matters?*** -#### Q. ***What is differences between External Iteration and Internal Iteration?*** -*ToDo* +#### Q. Give me an example of design pattern which is based upon open closed principle? +#### Q. How do you test static method? +#### Q. How to do you test a method for an exception using JUnit? +#### Q. Which unit testing libraries you have used for testing Java programs? +#### Q. What is the difference between @Before and @BeforeClass annotation? - - diff --git a/assets/collection.png b/assets/collection.png index 7361723..663721d 100644 Binary files a/assets/collection.png and b/assets/collection.png differ diff --git a/collections-questions.md b/collections-questions.md index 9b3ef16..d195c48 100644 --- a/collections-questions.md +++ b/collections-questions.md @@ -1,10 +1,12 @@ -# Collections Interview Questions and Answers +# Collections Interview Questions +
## Q. What is Java Collections Framework? List out some benefits of Collections framework? -![Java Collections Framework](https://github.com/learning-zone/java-interview-questions/blob/master/assets/collection.png) - +

+ Java Collections +

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that we perform on a data such as searching, sorting, insertion, manipulation, and deletion. @@ -65,7 +67,6 @@ Some common known classes implementing this interface are **ArrayDeque, Concurre * Reduces effort to design new APIs * Fosters software reuse - **Methods of Collection Interface** @@ -95,6 +96,7 @@ Some common known classes implementing this interface are **ArrayDeque, Concurre ## Q. What will be the problem if you do not override hashcode() method? + Some collections, like HashSet, HashMap or HashTable use the hashcode value of an object to find out how the object would be stored in the collection, and subsequently hashcode is used to help locate the object in the collection. Hashing retrieval involves: * First, find out the right bucket using hashCode(). @@ -102,7 +104,8 @@ Some collections, like HashSet, HashMap or HashTable use the hashcode value of a If hashcode() in not overridden then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method. -Example: +**Example:** + ```java public class Student { private int id; @@ -146,10 +149,15 @@ Checking equality between alex1 and alex2 = false ## Q. What is the benefit of Generics in Collections Framework? + Generics allow us to provide the type of Object that a collection can contain, so if we try to add any element of other type it throws compile time error. This avoids ClassCastException at Runtime because we will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator. ## Q. How do WeakHashMap works? + WeakHashMap is a Hash table-based implementation of the Map interface with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Both null values and the null key are supported. This class has performance characteristics similar to those of the HashMap class and has the same efficiency parameters of initial capacity and load factor. + +**Example:** + ```java // Java program to illustrate // WeakHashmap @@ -197,6 +205,7 @@ INACTIVE [project id : 200, project name : Employee Management System, ## Q. What is difference between Array and ArrayList? + **1. Size**: Array in Java is fixed in size. We can not change the size of array after creating it. ArrayList is dynamic in size. When we add elements to an ArrayList, its capacity increases automatically. **2. Performance**: In Java Array and ArrayList give different performance for different operations. @@ -216,6 +225,7 @@ resize(): Automatic resize of ArrayList slows down the performance. ArrayList is **7. Adding elements**: In an ArrayList we can use add() method to add objects. In an Array assignment operator is used for adding elements. **8. Multi-dimension**: An Array can be multi-dimensional. An ArrayList is always of single dimension + ```java // A Java program to demonstrate differences between array // and ArrayList @@ -254,6 +264,7 @@ Output ## Q. What is difference between ArrayList and LinkedList? + ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes. |Sl.No |ArrayList |LinkedList | @@ -306,70 +317,13 @@ public class ArrayListLinkedListExample ↥ back to top -## Q. What is difference between Comparable and Comparator interface? -**Comparable**: A comparable object is capable of comparing itself with another object. The class itself must implements the `java.lang.Comparable` interface in order to be able to compare its instances. - -**Comparator**: A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the `java.util.Comparator` interface. - -Comparable and Comparator both are interfaces and can be used to sort collection elements. - -| Sl.No|Comparable |Comparator | -|------|-----------------------|----------------------------------------------------------| -| 01.|Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price.|The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.| -| 02.|Comparable affects the original class, i.e., the actual class is modified.|Comparator doesn't affect the original class, i.e., the actual class is not modified.| -| 03.|Comparable provides compareTo() method to sort elements.| Comparator provides compare() method to sort elements.| -| 04.|Comparable is present in java.lang package.|A Comparator is present in the java.util package.| -| 05.|We can sort the list elements of Comparable type by Collections.sort(List) method.|We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.| - -```java -//Java Program to demonstrate the use of Java Comparable. -//Creating a class which implements Comparable Interface -import java.util.*; -import java.io.*; - -class Student implements Comparable { - int rollno; - String name; - int age; - Student(int rollno,String name,int age) { - this.rollno = rollno; - this.name = name; - this.age = age; - } - public int compareTo(Student st){ - if(age == st.age) - return 0; - else if(age > st.age) - return 1; - else - return -1; - } -} -//Creating a test class to sort the elements -public class TestSort3 { - - public static void main(String args[]) { - ArrayList al = new ArrayList(); - al.add(new Student(101,"Vijay",23)); - al.add(new Student(106,"Ajay",27)); - al.add(new Student(105,"Jai",21)); - - Collections.sort(al); - for(Student st:al) { - System.out.println(st.rollno+" "+st.name+" "+st.age); - } - } -} -``` - - ## Q. How to remove duplicates from ArrayList? + The LinkedHashSet is the best approach for removing duplicate elements in an arraylist. LinkedHashSet does two things internally : * Remove duplicate elements * Maintain the order of elements added to it + ```java import java.util.ArrayList; import java.util.Arrays; @@ -397,6 +351,7 @@ ArrayList with duplicate elements: [1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8] ArrayList without duplicate elements: [1, 2, 3, 4, 5, 6, 7, 8] ``` ## Q. What is Java Priority Queue? + A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation. The front of the priority queue contains the least element according to the specified ordering, and the rear of the priority queue contains the greatest element. So when we remove an element from the priority queue, the least element according to the specified ordering is removed first. The Priority Queue class is part of Java’s collections framework and implements the Queue interface. @@ -465,6 +420,7 @@ Vijay ## Q. What is LinkedHashMap in Java? + LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface. **Features** @@ -526,6 +482,7 @@ In the inheritance tree of the Map interface, there are several implementations **1. HashMap** This implementation uses a hash table as the underlying data structure. It implements all of the Map operations and allows null values and one null key. This class is roughly equivalent to Hashtable - a legacy data structure before Java Collections Framework, but it is not synchronized and permits nulls. HashMap does not guarantee the order of its key-value elements. Therefore, consider to use a HashMap when order does not matter and nulls are acceptable. + ```java Map mapHttpErrors = new HashMap<>(); @@ -543,6 +500,7 @@ Output **2. LinkedHashMap** This implementation uses a hash table and a linked list as the underlying data structures, thus the order of a LinkedHashMap is predictable, with insertion-order as the default order. This implementation also allows nulls like HashMap. So consider using a LinkedHashMap when you want a Map with its key-value pairs are sorted by their insertion order. + ```java Map mapContacts = new LinkedHashMap<>(); @@ -560,6 +518,7 @@ Output **3. TreeMap** This implementation uses a red-black tree as the underlying data structure. A TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at creation time. This implementation does not allow nulls. So consider using a TreeMap when you want a Map sorts its key-value pairs by the natural order of the keys (e.g. alphabetic order or numeric order), or by a custom order you specify. + ```java Map mapLang = new TreeMap<>(); @@ -604,6 +563,7 @@ Output ## Q. What is difference between HashMap and Hashtable? + HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. |Sl.No|HashMap |Hashtable | @@ -672,6 +632,7 @@ Hash map: ## Q. What is EnumSet? + Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface. **Features** @@ -750,6 +711,7 @@ drawing line in color : BLUE ## Q. What is the difference between fail-fast and fail-safe iterator? + **fail-fast Iterator** `Iterators` in java are used to iterate over the Collection objects.Fail-Fast iterators immediately throw `ConcurrentModificationException` if there is **structural modification** of the collection. Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection. Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator. @@ -831,6 +793,7 @@ THREE : 3 ## Q. What are concurrent collection classes? + The concurrent collection APIs of Java provide a range of classes that are specifically designed to deal with concurrent operations. These classes are alternatives to the Java Collection Framework and provide similar functionality except with the additional support of concurrency. **Java Concurrent Collection Classes** @@ -851,6 +814,7 @@ The concurrent collection APIs of Java provide a range of classes that are speci * ConcurrentSkipListMap ## Q. What is BlockingQueue? How to implement producer-consumer problem by using BlockingQueue? + **BlockingQueue**: When a thread try to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. Also, when a thread try to enqueue an item in a full queue is blocked until some other thread makes space in the queue, either by dequeuing one or more items or clearing the queue completely. **Producter-Consumer Problem** @@ -920,6 +884,7 @@ Here, The Producer start producing objects and pushing it to the Queue. Once the ## Q. What is difference between Enumeration and Iterator interface? + Enumeration and Iterator are two interfaces in java.util package which are used to traverse over the elements of a Collection object. **Differences** @@ -980,6 +945,7 @@ public class PerformanceTest { ## Q. What is difference between Iterator and ListIterator? + ListIterator is the child interface of Iterator interface. The major difference between Iterator and ListIterator is that Iterator can traverse the elements in the collection only in **forward direction** whereas, the ListIterator can traverse the elements in a collection in both the **forward as well as the backwards direction**. ```java @@ -1049,6 +1015,7 @@ Backward Traversal : ## Q. How can we create a synchronized collection from given collection? + In Java, normally collections aren't synchronized, which leads to fast performance. However, in multi-threaded situations, it can be very useful for collections to be synchronized. The Java Collections class has several static methods on it that provide synchronized collections. These methods are: * Synchronized Collection Methods of Collections class @@ -1125,6 +1092,7 @@ Synchronized view is : [10, 20, 30, 40, 50] * **Hashset**: Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75). ## Q. What is the difference between Collection and Collections? + **Collection Interface** Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. **List, Set and Queue** are main sub interfaces of this interface. JDK provides direct implementations of it’s sub interfaces. **ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue** are some indirect implementations of Collection interface. @@ -1146,6 +1114,7 @@ Collections is an utility class in java.util package. It consists of only static |Collections.reverse() |This method reverses the order of elements in the specified collection.| ## Q. What is the difference between HashSet and TreeSet? + 1) HashSet gives better performance (faster) than TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations. 2) HashSet does not maintain any order of elements while TreeSet elements are sorted in ascending order by default. @@ -1175,8 +1144,10 @@ class HashSetExample { } } ``` + Output -``` + +```java HashSet contains: Rick @@ -1185,6 +1156,7 @@ Ram Kevin Abhijeet ``` + ```java import java.util.TreeSet; class TreeSetExample { @@ -1260,6 +1232,7 @@ Singh 5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly. ## Q. What is the difference between HashMap and TreeMap? + Java **HashMap** and **TreeMap** both are the classes of the Java Collections framework. Java Map implementation usually acts as a bucketed hash table. When buckets get too large, they get transformed into nodes of **TreeNodes**, each structured similarly to those in java.util.TreeMap. |HashMap |TreeMap | @@ -1280,6 +1253,7 @@ Java **HashMap** and **TreeMap** both are the classes of the Java Collections fr ## Q. What is the Dictionary class? + **util.Dictionary** is an abstract class, representing a key-value relation and works similiar to a map. Both keys and values can be objects of any type but not null. An attempt to insert either a null key or a null value to a dictionary causes a NullPointerException exception. ```java @@ -1348,6 +1322,7 @@ Size of Dictionary : 1 ## Q. What are all the Classes and Interfaces that are available in the collections? + **Java Collections Interfaces** * Collection Interface @@ -1372,6 +1347,7 @@ Size of Dictionary : 1 * PriorityQueue Class ## Q. What is the difference between HashMap and ConcurrentHashMap? + |HashMap |ConcurrentHashMap | |------------------------------|------------------------------------------------------| @@ -1382,6 +1358,7 @@ Size of Dictionary : 1 |HashMap is faster. |ConcurrentHashMap is slower than HashMap.| ## Q. What is CopyOnWriteArrayList? How it is different from ArrayList in Java? + CopyOnWriteArrayList class is introduced in JDK 1.5, which implements List interface. It is enhanced version of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. ```java @@ -1444,6 +1421,7 @@ D ## Q. How to make an ArrayList read only in Java? + An ArrayList can be made read-only easily with the help of **Collections.unmodifiableList()** method. This method takes the modifiable ArrayList as a parameter and returns the read-only unmodifiable view of this ArrayList. ```java @@ -1501,16 +1479,19 @@ Exception thrown : java.lang.UnsupportedOperationException ## Q. Why Collection doesn’t extend Cloneable and Serializable interfaces? + Collection is an interface that specifies a group of objects known as elements. The details of how the group of elements is maintained is left up to the concrete implementations of `Collection`. For example, some Collection implementations like `List` allow duplicate elements whereas other implementations like `Set` don't. Collection is the root interface for all the collection classes ( like ArrayList, LinkedList ). If collection interface extends Cloneable/Serializable interfaces, then it is mandating all the concrete implementations of this interface to implement cloneable and serializable interfaces. To give freedom to concrete implementation classes, Collection interface don’t extended Cloneable or Serializable interfaces. ## Q. Why ConcurrentHashMap is faster than Hashtable in Java? + ConcurrentHashMap uses multiple buckets to store data. This avoids read locks and greatly improves performance over a HashTable. Both are thread safe, but there are obvious performance wins with ConcurrentHashMap. When we read from a ConcurrentHashMap using get(), there are no locks, contrary to the HashTable for which all operations are simply synchronized. HashTable was released in old versions of Java whereas ConcurrentHashMap is added in java 1.5 version. ## Q. What is the difference between peek(), poll() and remove() method of the Queue interface? + This represents a collection that is indented to hold data before processing. It is an arrangement of the type First-In-First-Out (FIFO). The first element put in the queue is the first element taken out from it. **The peek() method** @@ -1553,7 +1534,7 @@ Hbase ``` **The poll() method** -The peek() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null. +The poll() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null. ```java import java.util.Iterator; @@ -1599,13 +1580,15 @@ The main difference lies when the Queue is empty(). If Queue is empty then poll( ## Q. How HashMap works in Java? + HashMap in Java works on **hashing** principle. It is a data structure which allow to store object and retrieve it in constant time O(1). In hashing, hash functions are used to link key and value in HashMap. Objects are stored by calling **put(key, value)** method of HashMap and retrieved by calling **get(key)** method. When we call put method, **hashcode()** method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal array, known as the table. HashMap internally stores mapping in the form of **Map.Entry** object which contains both key and value object. Since the internal array of HashMap is of fixed size, and if you keep storing objects, at some point of time hash function will return same bucket location for two different keys, this is called **collision** in HashMap. In this case, a linked list is formed at that bucket location and a new entry is stored as next node. If we try to retrieve an object from this linked list, we need an extra check to search correct value, this is done by **equals()** method. Since each node contains an entry, HashMap keeps comparing entry's key object with the passed key using equals() and when it return true, Map returns the corresponding value. -Example: + + ```java /** * Java program to illustrate internal working of HashMap @@ -1647,11 +1630,13 @@ public class HashMapExample { } ``` ## Q. How does HashMap handle collisions in java? + Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handle collision by chaining, i.e. they use linked list to store map entries which ended in the same bucket due to a collision. If a key end up in same bucket location where an entry is already stored then this entry is just added at the head of the linked list there. In the worst case this degrades the performance of the `get()` method of HashMap to `O(n)` from `O(1)`. In order to address this issue in the case of frequent HashMap collisions, Java 8 has started using a **balanced tree** instead of linked list for storing collided entries. This also means that in the worst case you will get a performance boost from `O(n)` to `O(log n)`. The threshold of switching to the balanced tree is defined as TREEIFY_THRESHOLD constant in java.util.HashMap JDK 8 code. Currently, it's value is 8, which means if there are more than 8 elements in the same bucket than HashMap will use a tree instead of linked list to hold them in the same bucket. ## Q. Write a code to convert HashMap to ArrayList. + ```java import java.util.ArrayList; import java.util.Collection; @@ -1737,7 +1722,8 @@ Java HashSet class is used to create a collection that uses a hash table for sto * HashSet is the best approach for search operations. * The initial default capacity of HashSet is 16, and the load factor is 0.75. -Example: +**Example:** + ```java import java.util.*; class HashSetExample { @@ -1776,7 +1762,8 @@ Comparable and Comparator both are interfaces and can be used to sort collection |4) Comparable is present in java.lang package.|A Comparator is present in the java.util package.| 5) We can sort the list elements of Comparable type by Collections.sort(List) method.|We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.| -Example: +**Example:** + ```java /** * Java Program to demonstrate the use of Java Comparable. @@ -1819,7 +1806,9 @@ public class ComparableMain { } } ``` -Example: Java Comparator + +**Example:** Java Comparator + Student.java ```java class Student { @@ -1833,7 +1822,9 @@ class Student { } } ``` + AgeComparator.java + ```java import java.util.*; @@ -1848,7 +1839,9 @@ class AgeComparator implements Comparator { } } ``` + NameComparator.java + ```java import java.util.*; @@ -1859,6 +1852,7 @@ class NameComparator implements Comparator { } ``` TestComparator.java + ```java /** * Java Program to demonstrate the use of Java Comparator @@ -1896,6 +1890,7 @@ class TestComparator { ``` Output: + ```java Sorting by Name 106 Caelyn Romero 23 @@ -1907,6 +1902,7 @@ Sorting by Age 101 Caelyn Romero 23 106 Olivea Gold 27 ``` + @@ -1922,7 +1918,8 @@ It returns true if this map maps one or more keys to the specified value. * **The values() methods**: It returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. -Example: +**Example:** + ```java /** * Java program illustrating usage of HashMap class methods @@ -1969,14 +1966,16 @@ public class HashMapExample { ↥ back to top -## Q. What is the difference between Array and ArrayList data-structure? +## Q. What is the difference between Array and ArrayList data-structure? + * **Resizable**: Implementation of array is simple fixed sized array but Implementation of ArrayList is dynamic sized array. * **Primitives**: Array can contain both primitives and objects but ArrayList can contain only object elements * **Generics**: We can’t use generics along with array but ArrayList allows us to use generics to ensure type safety. * **Length**: We can use length variable to calculate length of an array but size() method to calculate size of ArrayList. * **Store**: Array use assignment operator to store elements but ArrayList use add() to insert elements. -Example: +**Example:** + ```java /* * A Java program to demonstrate differences between array @@ -2016,13 +2015,16 @@ class ArrayExample { ↥ back to top -## Q. Array or ArrayList which one is faster? +## Q. Array or ArrayList which one is faster? + * Array is faster ## Q. What is difference between HashSet and LinkedHashSet? + A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of HashSet. The only difference between HashSet and LinkedHashSet is that LinkedHashSet maintains the **insertion order**. When we iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet. The reason why LinkedHashSet maintains insertion order is because the underlying data structure is a doubly-linked list. ## Q. What is the difference between HashTable and HashMap? + |HashMap |Hashtable | |------------------------------------------------------|--------------------------------------------------------| |HashMap is **non synchronized**. It is not-thread safe and can't be shared between many threads without proper synchronization code. | Hashtable is **synchronized**. It is thread-safe and can be shared with many threads.| @@ -2035,7 +2037,8 @@ A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of |Iterator in HashMap is fail-fast. |Enumerator in Hashtable is not fail-fast.| |HashMap inherits AbstractMap class. | Hashtable inherits Dictionary class.| -Example: +**Example:** + ```java /** * A sample Java program to demonstrate HashMap and HashTable @@ -2086,11 +2089,13 @@ Hash Map Values ## Q. What happens when a duplicate key is put into a HashMap? + By definition, the `put` command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types). The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or `null` if none present), so you can determine what was there and maintain a reference if necessary. ## Q. What are the differences between ArrayList and Vector? + |ArrayList |Vector | |-------------------------------|-------------------------------------| |ArrayList is **not synchronized**. |Vector is **synchronized**. | @@ -2099,7 +2104,8 @@ The map simply drops its reference to the value. If nothing else holds a referen |ArrayList is **fast** because it is non-synchronized. | Vector is **slow** because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object.| |ArrayList uses the **Iterator** interface to traverse the elements. |A Vector can use the **Iterator** interface or **Enumeration** interface to traverse the elements.| -Example: +**Example:** + ```java /** * Java Program to illustrate use of ArrayList @@ -2156,12 +2162,14 @@ Six ↥ back to top -## Q. If you store Employee object as key say: Employee emp = new Employee(“name1”,20); store it in a HashMap as key, now if we add a new parameter emp.setMarriedStatus(true) and try to override it what will happen? +## Q. If you store Employee object as key say: Employee emp = new Employee(“name1”,20); store it in a HashMap as key, now if we add a new parameter emp.setMarriedStatus(true) and try to override it what will happen? + new instance of Employee will be inserted to HashMap ### Q. Why Map interface does not extend Collection interface? ### Q. What is CompareAndSwap approach? + diff --git a/core-java/arrays/package-info.java b/core-java/arrays/package-info.java index 42241cb..2c0f888 100644 --- a/core-java/arrays/package-info.java +++ b/core-java/arrays/package-info.java @@ -1,8 +1,6 @@ -/** - * - */ -/** - * @author U6044324 - * Nov 5, 2018 - */ -package arrays; \ No newline at end of file + +/* + @author U6044324 + Nov 5, 2018 +*/ +package arrays; diff --git a/core-java/basics/BinarySearch.java b/core-java/basics/BinarySearch.java index d30ba02..c8d6694 100644 --- a/core-java/basics/BinarySearch.java +++ b/core-java/basics/BinarySearch.java @@ -1,19 +1,47 @@ -package basics; -import java.util.Arrays; - -public class BinarySearch { - - public static void main(String[] args) { - - int arr[] = {10, 20, 15, 22, 35}; - Arrays.sort(arr); - - int key = 35; - int res = Arrays.binarySearch(arr, key); - if(res >= 0){ - System.out.println(key + " found at index = "+ res); - } else { - System.out.println(key + " not found"); - } +// Java implementation of iterative Binary Search + +import java.io.*; + +class BinarySearch { + + // Returns index of x if it is present in arr[]. + int binarySearch(int arr[], int x) + { + int l = 0, r = arr.length - 1; + while (l <= r) { + int m = l + (r - l) / 2; + + // Check if x is present at mid + if (arr[m] == x) + return m; + + // If x greater, ignore left half + if (arr[m] < x) + l = m + 1; + + // If x is smaller, ignore right half + else + r = m - 1; + } + + // If we reach here, then element was + // not present + return -1; + } + + // Driver code + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, x); + if (result == -1) + System.out.println( + "Element is not present in array"); + else + System.out.println("Element is present at " + + "index " + result); } } diff --git a/core-java/basics/BoundedTypesGenerics02.java b/core-java/basics/BoundedTypesGenerics02.java index 7657f86..a1ad4e4 100644 --- a/core-java/basics/BoundedTypesGenerics02.java +++ b/core-java/basics/BoundedTypesGenerics02.java @@ -1,29 +1,28 @@ -package basics; - interface SampleInterface { - public void displayClass(); + void displayClass(); } + class BoundTest { - private T objRef; - public BoundTest(T obj) { - this.objRef = obj; - } - - public void doRunTest(){ - this.objRef.displayClass(); - } -} + private T objRef; + public BoundTest(T obj) { + this.objRef = obj; + } + + public void doRunTest() { + objRef.displayClass(); + } +} class SampleClass implements SampleInterface { - public void displayClass() { - System.out.println("Inside supper Class A"); - } + public void displayClass() { + System.out.println("Inside super Class A"); + } } -class BoundedTypesGenerics02 { - public static void main(String a[]) { - BoundTest b = new BoundTest<>(new SampleClass()); - b.doRunTest(); - } +public class BoundedTypesGenerics02 { + public static void main(String[] args) { + BoundTest b = new BoundTest<>(new SampleClass()); + b.doRunTest(); + } } diff --git a/core-java/basics/EnumConstructorExample.java b/core-java/basics/EnumConstructorExample.java index b3e0cfe..6600380 100644 --- a/core-java/basics/EnumConstructorExample.java +++ b/core-java/basics/EnumConstructorExample.java @@ -1,24 +1,21 @@ -package basics; - enum TrafficSignal { RED("STOP"), GREEN("GO"), ORANGE("SLOW DOWN"); - - private String action; - public String getAction() { - return this.action; - } - private TrafficSignal(String action) { + + private final String action; + + TrafficSignal(String action) { this.action = action; } + + public String getAction() { + return action; + } } -public class EnumConstructorExample { +public class EnumConstructorExample { public static void main(String[] args) { - - TrafficSignal[] signals = TrafficSignal.values(); - - for(TrafficSignal signal: signals){ - System.out.println("name: "+ signal.name() + " action: " + signal.getAction()); + for (TrafficSignal signal : TrafficSignal.values()) { + System.out.println("name: " + signal.name() + " action: " + signal.getAction()); } } } diff --git a/hibernate-questions.md b/hibernate-questions.md deleted file mode 100644 index 7bb8bb4..0000000 --- a/hibernate-questions.md +++ /dev/null @@ -1,1854 +0,0 @@ -# Hibernate Interview Questions & Answers - -## Q. How to integrate hibernate with spring boot? - -**Step 01: Maven Dependencies** -```xml - - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.5.RELEASE - - - com.javaexample.demo - SpringBoot2Demo - 0.0.1-SNAPSHOT - SpringBoot2Demo - Demo project for Spring Boot - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - runtime - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - -``` -* **spring-boot-starter-data-jpa**(required): It includes spring data, hibernate, HikariCP, JPA API, JPA Implementation (default is hibernate), JDBC and other required libraries. - -**Step 02: Create JPA entity classes** - -```java -/** EmployeeEntity.java **/ - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="TBL_EMPLOYEES") -public class EmployeeEntity { - - @Id - @GeneratedValue - private Long id; - - @Column(name="first_name") - private String firstName; - - @Column(name="last_name") - private String lastName; - - @Column(name="email", nullable=false, length=200) - private String email; - - //Setters and getters left out for brevity. - - @Override - public String toString() { - return "EmployeeEntity [id=" + id + ", firstName=" + firstName + - ", lastName=" + lastName + ", email=" + email + "]"; - } -} -``` -**Step 03: Create JPA Repository** - -Extend `JpaRepository` interface to allows to create repository implementations automatically, at runtime, for any given entity class. The types of entity class and it’s ID field are specified in the generic parameters on JpaRepository. -```java -/** EmployeeRepository.java **/ -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.javaexample.demo.entity.EmployeeEntity; - -@Repository -public interface EmployeeRepository extends JpaRepository { - -} -``` -By this simple extension, EmployeeRepository inherits several methods for working with Employee persistence, including methods for saving, deleting, and finding Employee entities. - -**Step 04: Properties Configuration** - -**application.properties** -``` -spring.datasource.url=jdbc:h2:file:~/test -spring.datasource.driverClassName=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password= -spring.jpa.database-platform=org.hibernate.dialect.H2Dialect - -# Enabling H2 Console -spring.h2.console.enabled=true - -# Custom H2 Console URL -spring.h2.console.path=/h2-console - - -#Turn Statistics on and log SQL stmts - -spring.jpa.show-sql=true -spring.jpa.properties.hibernate.format_sql=true - -#If want to see very extensive logging -spring.jpa.properties.hibernate.generate_statistics=true -logging.level.org.hibernate.type=trace -logging.level.org.hibernate.stat=debug - -#Schema will be created using schema.sql and data.sql files - -spring.jpa.hibernate.ddl-auto=none -``` -```sql -## schama.sql -DROP TABLE IF EXISTS TBL_EMPLOYEES; - -CREATE TABLE TBL_EMPLOYEES ( - id INT AUTO_INCREMENT PRIMARY KEY, - first_name VARCHAR(250) NOT NULL, - last_name VARCHAR(250) NOT NULL, - email VARCHAR(250) DEFAULT NULL -); - -## data.sql -INSERT INTO TBL_EMPLOYEES - (first_name, last_name, email) -VALUES - ('Lokesh', 'Gupta', 'abc@gmail.com'), - ('Deja', 'Vu', 'xyz@email.com'), - ('Caption', 'America', 'cap@marvel.com'); -``` -**Step 05. Spring boot hibernate demo** - -To test hibernate configuration with Spring boot, we need to autowire the EmployeeRepository dependency in a class and use it’s method to save or fetch employee entities. - -**SpringBoot2DemoApplication.java** -```java -import java.util.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.javaexample.demo.entity.EmployeeEntity; -import com.javaexample.demo.repository.EmployeeRepository; - -@SpringBootApplication -public class SpringBoot2DemoApplication implements CommandLineRunner { - - private Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - EmployeeRepository repository; - - public static void main(String[] args) { - SpringApplication.run(SpringBoot2DemoApplication.class, args); - } - - @Override - public void run(String... args) throws Exception - { - Optional emp = repository.findById(2L); - - logger.info("Employee id 2 -> {}", emp.get()); - } -} -``` -Output -``` -Tomcat initialized with port(s): 8080 (http) -Starting service [Tomcat] -Starting Servlet engine: [Apache Tomcat/9.0.19] -Initializing Spring embedded WebApplicationContext -Root WebApplicationContext: initialization completed in 5748 ms - -HikariPool-1 - Starting... -HikariPool-1 - Start completed. -HHH000204: Processing PersistenceUnitInfo [ - name: default - ...] -HHH000412: Hibernate Core {5.3.10.Final} -HHH000206: hibernate.properties not found -HCANN000001: Hibernate Commons Annotations {5.0.4.Final} -HHH000400: Using dialect: org.hibernate.dialect.H2Dialect - -Initialized JPA EntityManagerFactory for persistence unit 'default' -Initializing ExecutorService 'applicationTaskExecutor' -spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. -Explicitly configure spring.jpa.open-in-view to disable this warning -Tomcat started on port(s): 8080 (http) with context path '' -Started SpringBoot2DemoApplication in 17.638 seconds (JVM running for 19.1) - -Hibernate: - select - employeeen0_.id as id1_0_0_, - employeeen0_.email as email2_0_0_, - employeeen0_.first_name as first_na3_0_0_, - employeeen0_.last_name as last_nam4_0_0_ - from - tbl_employees employeeen0_ - where - employeeen0_.id=? - -Employee id 2 -> EmployeeEntity [id=2, firstName=Deja, lastName=Vu, email=xyz@email.com] -``` - - -## Q. Mention the differences between JPA and Hibernate? -JPA is a specification for accessing, persisting and managing the data between Java objects and the relational database. - -Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation. - -|Hibernate |JPA | -|-------------------------------------------|-----------------------------------------------------| -|Hibernate is the object-relational mapping framework which helps to deal with the data persistence.|It is the Java specification to manage the java application with relational data.| -|It’s is one of the best JPA providers. |It is the only specification which doesn’t deal with any implementation.| -|In this, we use Session for handling the persistence in an application.|In this, we use the Entity manager. | -|It is used to map Java data types with database tables and SQL data types.|It is the standard API which allows developers to perform database operations smoothly.| -|The Query language in this is Hibernate Query Language.|The query language of JPA is JPQL (Java Persistence Query Language)| - -## Q. What is HQL and what are its benefits? -Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database. - -**Advantages Of HQL:** - -* HQL is database independent, means if we write any program using HQL commands then our program will be able to execute in all the databases with out doing any further changes to it -* HQL supports object oriented features like Inheritance, polymorphism,Associations(Relation ships) -* HQL is initially given for selecting object from database and in hibernate 3.x we can doDML operations ( insert, update…) too - -**Different Ways Of Construction HQL Select** - -**FROM Clause** -```sql -/** In SQL **/ -sql> select * from Employee - -/** In HQL **/ -String hql = "FROM Employee"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**AS Clause** -```sql -String hql = "FROM Employee AS E"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**SELECT Clause** -```sql -String hql = "SELECT E.firstName FROM Employee E"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**WHERE Clause** -```sql -String hql = "FROM Employee E WHERE E.id = 10"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**ORDER BY Clause** -```sql -String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**GROUP BY Clause** -```sql -String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " + - "GROUP BY E.firstName"; -Query query = session.createQuery(hql); -List results = query.list(); -``` -**Using Named Parameters** -Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks. Following is the simple syntax of using named parameters − - -```sql -String hql = "FROM Employee E WHERE E.id = :employee_id"; -Query query = session.createQuery(hql); -query.setParameter("employee_id",10); -List results = query.list(); -``` -**UPDATE Clause** -```sql -String hql = "UPDATE Employee set salary = :salary " + - "WHERE id = :employee_id"; -Query query = session.createQuery(hql); -query.setParameter("salary", 1000); -query.setParameter("employee_id", 10); -int result = query.executeUpdate(); -System.out.println("Rows affected: " + result); -``` -**DELETE Clause** -```sql -String hql = "DELETE FROM Employee " + - "WHERE id = :employee_id"; -Query query = session.createQuery(hql); -query.setParameter("employee_id", 10); -int result = query.executeUpdate(); -System.out.println("Rows affected: " + result); -``` -**INSERT Clause** -```sql -String hql = "INSERT INTO Employee(firstName, lastName, salary)" + - "SELECT firstName, lastName, salary FROM old_employee"; -Query query = session.createQuery(hql); -int result = query.executeUpdate(); -System.out.println("Rows affected: " + result); -``` -**Pagination using Query** -```sql -String hql = "FROM Employee"; -Query query = session.createQuery(hql); -query.setFirstResult(1); -query.setMaxResults(10); -List results = query.list(); -``` - - -## Q. Mention the Key components of Hibernate? - -**hibernate.cfg.xml**: This file has database connection details - -**hbm.xml or Annotation**: Defines the database table mapping with POJO. Also defines the relation between tables in java way. -**SessionFactory**: -* There will be a session factory per database. -* The SessionFacory is built once at start-up -* It is a thread safe class -* SessionFactory will create a new Session object when requested -**Session**: -* The Session object will get physical connection to the database. -* Session is the Java object used for any DB operations. -* Session is not thread safe. Hence do not share hibernate session between threads -* Session represents unit of work with database -* Session should be closed once the task is completed - -## Q. Explain Session object in Hibernate? -A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. - -The lifecycle of a Session is bounded by the beginning and end of a logical transaction. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: - -* **transient** − A new instance of a persistent class, which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate. - -* **persistent** − You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session. - -* **detached** − Once we close the Hibernate Session, the persistent instance will become a detached instance. - -```java -Session session = factory.openSession(); -Transaction tx = null; - -try { - tx = session.beginTransaction(); - // do some work - ... - tx.commit(); -} - -catch (Exception e) { - if (tx!=null) tx.rollback(); - e.printStackTrace(); -} finally { - session.close(); -} -``` - - -## Q. How transaction management works in Hibernate? -A **Transaction** is a sequence of operation which works as an atomic unit. A transaction only completes if all the operations completed successfully. A transaction has the Atomicity, Consistency, Isolation, and Durability properties (ACID). - -In hibernate framework, **Transaction interface** that defines the unit of work. It maintains abstraction from the transaction implementation (JTA, JDBC). A transaction is associated with Session and instantiated by calling **session.beginTransaction()**. - - -|Transaction interface | Description | -|---------------------------|--------------------------| -|void begin() |starts a new transaction. | -|void commit() |ends the unit of work unless we are in FlushMode.NEVER.| -|void rollback() |forces this transaction to rollback.| -|void setTimeout(int seconds)| It sets a transaction timeout for any transaction started by a subsequent call to begin on this |instance.| -|boolean isAlive() |checks if the transaction is still alive.| -|void registerSynchronization(Synchronization s) |registers a user synchronization callback for this transaction.| -|boolean wasCommited() |checks if the transaction is commited successfully.| -|boolean wasRolledBack() |checks if the transaction is rolledback successfully.| - -Example: -```java -Transaction transObj = null; -Session sessionObj = null; -try { - sessionObj = HibernateUtil.buildSessionFactory().openSession(); - transObj = sessionObj.beginTransaction(); - - //Perform Some Operation Here - transObj.commit(); -} catch (HibernateException exObj) { - if(transObj!=null){ - transObj.rollback(); - } - exObj.printStackTrace(); -} finally { - sessionObj.close(); -} -``` -## Q. Explain the Criteria object in Hibernate? -The Criteria API allows to build up a criteria query object programmatically; the `org.hibernate.Criteria` interface defines the available methods for one of these objects. The Hibernate Session interface contains several overloaded `createCriteria()` methods. - -**1. Restrictions with Criteria** - -```java -Criteria cr = session.createCriteria(Employee.class); - -// To get records having salary is equal to 2000 -cr.add(Restrictions.eq("salary", 2000)); -List results = cr.list(); - -// To get records having salary more than 2000 -cr.add(Restrictions.gt("salary", 2000)); - -// To get records having salary less than 2000 -cr.add(Restrictions.lt("salary", 2000)); - -// To get records having fistName starting with zara -cr.add(Restrictions.like("firstName", "zara%")); - -// Case sensitive form of the above restriction. -cr.add(Restrictions.ilike("firstName", "zara%")); - -// To get records having salary in between 1000 and 2000 -cr.add(Restrictions.between("salary", 1000, 2000)); - -// To check if the given property is null -cr.add(Restrictions.isNull("salary")); - -// To check if the given property is not null -cr.add(Restrictions.isNotNull("salary")); - -// To check if the given property is empty -cr.add(Restrictions.isEmpty("salary")); - -// To check if the given property is not empty -cr.add(Restrictions.isNotEmpty("salary")); -``` - -**2. Logical Expression Restrictions** -```java -Criteria cr = session.createCriteria(Employee.class); - -Criterion salary = Restrictions.gt("salary", 2000); -Criterion name = Restrictions.ilike("firstNname","zara%"); - -// To get records matching with OR conditions -LogicalExpression orExp = Restrictions.or(salary, name); -cr.add( orExp ); - -// To get records matching with AND conditions -LogicalExpression andExp = Restrictions.and(salary, name); -cr.add( andExp ); - -List results = cr.list(); -``` - -**3. Pagination Using Criteria** -```java -Criteria cr = session.createCriteria(Employee.class); -cr.setFirstResult(1); -cr.setMaxResults(10); -List results = cr.list(); -``` - -**4. Sorting the Results** -The Criteria API provides the **org.hibernate.criterion.Order** class to sort your result set in either ascending or descending order, according to one of your object's properties. -```java -Criteria cr = session.createCriteria(Employee.class); - -// To get records having salary more than 2000 -cr.add(Restrictions.gt("salary", 2000)); - -// To sort records in descening order -cr.addOrder(Order.desc("salary")); - -// To sort records in ascending order -cr.addOrder(Order.asc("salary")); - -List results = cr.list(); -``` - -**5. Projections & Aggregations** -The Criteria API provides the **org.hibernate.criterion.Projections** class, which can be used to get average, maximum, or minimum of the property values. The Projections class is similar to the Restrictions class, in that it provides several static factory methods for obtaining **Projection** instances. -```java -Criteria cr = session.createCriteria(Employee.class); - -// To get total row count. -cr.setProjection(Projections.rowCount()); - -// To get average of a property. -cr.setProjection(Projections.avg("salary")); - -// To get distinct count of a property. -cr.setProjection(Projections.countDistinct("firstName")); - -// To get maximum of a property. -cr.setProjection(Projections.max("salary")); - -// To get minimum of a property. -cr.setProjection(Projections.min("salary")); - -// To get sum of a property. -cr.setProjection(Projections.sum("salary")); -``` - -**Criteria Queries Example** - -Employee.java -```java -public class Employee { - private int id; - private String firstName; - private String lastName; - private int salary; - - public Employee() {} - - public Employee(String fname, String lname, int salary) { - this.firstName = fname; - this.lastName = lname; - this.salary = salary; - } - - public int getId() { - return id; - } - - public void setId( int id ) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName( String first_name ) { - this.firstName = first_name; - } - - public String getLastName() { - return lastName; - } - - public void setLastName( String last_name ) { - this.lastName = last_name; - } - - public int getSalary() { - return salary; - } - - public void setSalary( int salary ) { - this.salary = salary; - } -} -``` -EMPLOYEE.sql -```sql -create table EMPLOYEE ( - id INT NOT NULL auto_increment, - first_name VARCHAR(20) default NULL, - last_name VARCHAR(20) default NULL, - salary INT default NULL, - PRIMARY KEY (id) -); -``` -Hibernate Mapping File -```xml - - - - - - - - This class contains the employee detail. - - - - - - - - - - - - -``` -ManageEmployee.java -```java -import java.util.List; -import java.util.Date; -import java.util.Iterator; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.SessionFactory; -import org.hibernate.Criteria; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Projections; -import org.hibernate.cfg.Configuration; - -public class ManageEmployee { - private static SessionFactory factory; - public static void main(String[] args) { - - try { - factory = new Configuration().configure().buildSessionFactory(); - } catch (Throwable ex) { - System.err.println("Failed to create sessionFactory object." + ex); - throw new ExceptionInInitializerError(ex); - } - - ManageEmployee ME = new ManageEmployee(); - - /* Add few employee records in database */ - Integer empID1 = ME.addEmployee("Zara", "Ali", 2000); - Integer empID2 = ME.addEmployee("Daisy", "Das", 5000); - Integer empID3 = ME.addEmployee("John", "Paul", 5000); - Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000); - - /* List down all the employees */ - ME.listEmployees(); - - /* Print Total employee's count */ - ME.countEmployee(); - - /* Print Total salary */ - ME.totalSalary(); - } - - /* Method to CREATE an employee in the database */ - public Integer addEmployee(String fname, String lname, int salary){ - Session session = factory.openSession(); - Transaction tx = null; - Integer employeeID = null; - - try { - tx = session.beginTransaction(); - Employee employee = new Employee(fname, lname, salary); - employeeID = (Integer) session.save(employee); - tx.commit(); - } catch (HibernateException e) { - if (tx!=null) tx.rollback(); - e.printStackTrace(); - } finally { - session.close(); - } - return employeeID; - } - - /* Method to READ all the employees having salary more than 2000 */ - public void listEmployees( ) { - Session session = factory.openSession(); - Transaction tx = null; - - try { - tx = session.beginTransaction(); - Criteria cr = session.createCriteria(Employee.class); - // Add restriction. - cr.add(Restrictions.gt("salary", 2000)); - List employees = cr.list(); - - for (Iterator iterator = employees.iterator(); iterator.hasNext();){ - Employee employee = (Employee) iterator.next(); - System.out.print("First Name: " + employee.getFirstName()); - System.out.print(" Last Name: " + employee.getLastName()); - System.out.println(" Salary: " + employee.getSalary()); - } - tx.commit(); - } catch (HibernateException e) { - if (tx!=null) tx.rollback(); - e.printStackTrace(); - } finally { - session.close(); - } - } - - /* Method to print total number of records */ - public void countEmployee(){ - Session session = factory.openSession(); - Transaction tx = null; - - try { - tx = session.beginTransaction(); - Criteria cr = session.createCriteria(Employee.class); - - // To get total row count. - cr.setProjection(Projections.rowCount()); - List rowCount = cr.list(); - - System.out.println("Total Coint: " + rowCount.get(0) ); - tx.commit(); - } catch (HibernateException e) { - if (tx!=null) tx.rollback(); - e.printStackTrace(); - } finally { - session.close(); - } - } - - /* Method to print sum of salaries */ - public void totalSalary(){ - Session session = factory.openSession(); - Transaction tx = null; - - try { - tx = session.beginTransaction(); - Criteria cr = session.createCriteria(Employee.class); - - // To get total salary. - cr.setProjection(Projections.sum("salary")); - List totalSalary = cr.list(); - - System.out.println("Total Salary: " + totalSalary.get(0) ); - tx.commit(); - } catch (HibernateException e) { - if (tx!=null) tx.rollback(); - e.printStackTrace(); - } finally { - session.close(); - } - } -} -``` -Output -``` -cmd> java ManageEmployee -.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ - -First Name: Daisy Last Name: Das Salary: 5000 -First Name: John Last Name: Paul Salary: 5000 -First Name: Mohd Last Name: Yasee Salary: 3000 -Total Coint: 4 -Total Salary: 15000 -``` - - -## Q. What is a One-to-One association in Hibernate? -A **One-to-One** Association is similar to Many-to-One association with a difference that the column will be set as unique i.e. Two entities are said to be in a One-to-One relationship if one entity has only one occurrence in the other entity. For example, an address object can be associated with a single employee object. However, these relationships are rarely used in the relational table models and therefore, we won’t need this mapping too often. - -In One-to-One association, the source entity has a field that references another target entity. The `@OneToOne` JPA annotation is used to map the source entity with the target entity. - -Example: Hibernate One to One Mapping Annotation - -**hibernate-annotation.cfg.xml** -```xml - - - - - com.mysql.jdbc.Driver - dbpassword - jdbc:mysql://localhost/TestDB - dbusername - org.hibernate.dialect.MySQLDialect - - thread - true - - - - - -``` -For hibernate one to one mapping annotation configuration, model classes are the most important part. -```java -package com.example.hibernate.model; - -import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import org.hibernate.annotations.Cascade; - -@Entity -@Table(name="TRANSACTION") -public class Txn1 { - - @Id - @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="txn_id") - private long id; - - @Column(name="txn_date") - private Date date; - - @Column(name="txn_total") - private double total; - - @OneToOne(mappedBy="txn") - @Cascade(value=org.hibernate.annotations.CascadeType.SAVE_UPDATE) - private Customer1 customer; - - @Override - public String toString(){ - return id+", "+total+", "+customer.getName()+", "+customer.getEmail()+", "+customer.getAddress(); - } - - //Getter-Setter methods, omitted for clarity -} -``` -```java - -package com.example.hibernate.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToOne; -import javax.persistence.PrimaryKeyJoinColumn; -import javax.persistence.Table; -import org.hibernate.annotations.GenericGenerator; -import org.hibernate.annotations.Parameter; - -@Entity -@Table(name="CUSTOMER") -public class Customer1 { - - @Id - @Column(name="txn_id", unique=true, nullable=false) - @GeneratedValue(generator="gen") - @GenericGenerator(name="gen", strategy="foreign", parameters={@Parameter(name="property", value="txn")}) - private long id; - - @Column(name="cust_name") - private String name; - - @Column(name="cust_email") - private String email; - - @Column(name="cust_address") - private String address; - - @OneToOne - @PrimaryKeyJoinColumn - private Txn1 txn; - - //Getter-Setter methods -} -``` -**Hibernate SessionFactory Utility class** -```java - -package com.example.hibernate.util; - -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; - -public class HibernateAnnotationUtil { - - private static SessionFactory sessionFactory; - - private static SessionFactory buildSessionFactory() { - try { - // Create the SessionFactory from hibernate-annotation.cfg.xml - Configuration configuration = new Configuration(); - configuration.configure("hibernate-annotation.cfg.xml"); - System.out.println("Hibernate Annotation Configuration loaded"); - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - System.out.println("Hibernate Annotation serviceRegistry created"); - - SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); - - return sessionFactory; - } - catch (Throwable ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - ex.printStackTrace(); - throw new ExceptionInInitializerError(ex); - } - } - - public static SessionFactory getSessionFactory() { - if(sessionFactory == null) sessionFactory = buildSessionFactory(); - return sessionFactory; - } -} -``` -**Hibernate One to One Mapping Annotation Example Test Program** -```java - -package com.example.hibernate.main; - -import java.util.Date; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.example.hibernate.model.Customer1; -import com.example.hibernate.model.Txn1; -import com.example.hibernate.util.HibernateAnnotationUtil; - -public class HibernateOneToOneAnnotationMain { - - public static void main(String[] args) { - - Txn1 txn = buildDemoTransaction(); - - SessionFactory sessionFactory = null; - Session session = null; - Transaction tx = null; - try{ - //Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - System.out.println("Session created using annotations configuration"); - //start transaction - tx = session.beginTransaction(); - //Save the Model object - session.save(txn); - //Commit transaction - tx.commit(); - System.out.println("Annotation Example. Transaction ID="+txn.getId()); - - //Get Saved Trasaction Data - printTransactionData(txn.getId(), sessionFactory); - }catch(Exception e){ - System.out.println("Exception occured. "+e.getMessage()); - e.printStackTrace(); - }finally{ - if(sessionFactory != null && !sessionFactory.isClosed()){ - System.out.println("Closing SessionFactory"); - sessionFactory.close(); - } - } - } - - private static void printTransactionData(long id, SessionFactory sessionFactory) { - Session session = null; - Transaction tx = null; - try{ - //Get Session - sessionFactory = HibernateAnnotationUtil.getSessionFactory(); - session = sessionFactory.getCurrentSession(); - //start transaction - tx = session.beginTransaction(); - //Save the Model object - Txn1 txn = (Txn1) session.get(Txn1.class, id); - //Commit transaction - tx.commit(); - System.out.println("Annotation Example. Transaction Details=\n"+txn); - - }catch(Exception e){ - System.out.println("Exception occured. "+e.getMessage()); - e.printStackTrace(); - } - } - - private static Txn1 buildDemoTransaction() { - Txn1 txn = new Txn1(); - txn.setDate(new Date()); - txn.setTotal(100); - - Customer1 cust = new Customer1(); - cust.setAddress("San Jose, USA"); - cust.setEmail("Alex@yahoo.com"); - cust.setName("Alex Kr"); - - txn.setCustomer(cust); - - cust.setTxn(txn); - return txn; - } -} -``` -Output -``` -Hibernate Annotation Configuration loaded -Hibernate Annotation serviceRegistry created -Session created using annotations configuration -Hibernate: insert into TRANSACTION (txn_date, txn_total) values (?, ?) -Hibernate: insert into CUSTOMER (cust_address, cust_email, cust_name, txn_id) values (?, ?, ?, ?) -Annotation Example. Transaction ID=20 -Hibernate: select txn1x0_.txn_id as txn_id1_1_0_, txn1x0_.txn_date as txn_date2_1_0_, txn1x0_.txn_total as txn_tota3_1_0_, -customer1x1_.txn_id as txn_id1_0_1_, customer1x1_.cust_address as cust_add2_0_1_, customer1x1_.cust_email as cust_ema3_0_1_, -customer1x1_.cust_name as cust_nam4_0_1_ from TRANSACTION txn1x0_ left outer join CUSTOMER customer1x1_ on -txn1x0_.txn_id=customer1x1_.txn_id where txn1x0_.txn_id=? -Annotation Example. Transaction Details= -20, 100.0, Alex Kr, Alex@yahoo.com, San Jose, USA -Closing SessionFactory -``` - - -## Q. What is hibernate caching? Explain Hibernate first level cache? -Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. - -Hibernate comes with different types of Cache: - -**First Level Cache**: Hibernate first level cache is associated with the **Session object**. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction. - -**Second Level Cache**: Second-level cache always associates with the **Session Factory object**. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. - -Hibernate Second Level cache is disabled by default but we can enable it through configuration. Currently EHCache and Infinispan provides implementation for Hibernate Second level cache and we can use them. We will look into this in the next tutorial for hibernate caching. - -**Query Cache**: Hibernate can also cache result set of a query. Hibernate Query Cache doesn’t cache the state of the actual entities in the cache; it caches only identifier values and results of value type. So it should always be used in conjunction with the second-level cache. - -Example: Hibernate Caching – First Level Cache -```java - -package com.example.hibernate.main; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; - -import com.example.hibernate.model.Employee; -import com.example.hibernate.util.HibernateUtil; - -public class HibernateCacheExample { - - public static void main(String[] args) throws InterruptedException { - - SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); - Session session = sessionFactory.getCurrentSession(); - Transaction tx = session.beginTransaction(); - - //Get employee with id=1 - Employee emp = (Employee) session.load(Employee.class, new Long(1)); - printData(emp,1); - - //waiting for sometime to change the data in backend - Thread.sleep(10000); - - //Fetch same data again, check logs that no query fired - Employee emp1 = (Employee) session.load(Employee.class, new Long(1)); - printData(emp1,2); - - //Create new session - Session newSession = sessionFactory.openSession(); - //Get employee with id=1, notice the logs for query - Employee emp2 = (Employee) newSession.load(Employee.class, new Long(1)); - printData(emp2,3); - - //START: evict example to remove specific object from hibernate first level cache - //Get employee with id=2, first time hence query in logs - Employee emp3 = (Employee) session.load(Employee.class, new Long(2)); - printData(emp3,4); - - //evict the employee object with id=1 - session.evict(emp); - System.out.println("Session Contains Employee with id=1?"+session.contains(emp)); - - //since object is removed from first level cache, you will see query in logs - Employee emp4 = (Employee) session.load(Employee.class, new Long(1)); - printData(emp4,5); - - //this object is still present, so you won't see query in logs - Employee emp5 = (Employee) session.load(Employee.class, new Long(2)); - printData(emp5,6); - //END: evict example - - //START: clear example to remove everything from first level cache - session.clear(); - Employee emp6 = (Employee) session.load(Employee.class, new Long(1)); - printData(emp6,7); - Employee emp7 = (Employee) session.load(Employee.class, new Long(2)); - printData(emp7,8); - - System.out.println("Session Contains Employee with id=2?"+session.contains(emp7)); - - tx.commit(); - sessionFactory.close(); - } - - private static void printData(Employee emp, int count) { - System.out.println(count+":: Name="+emp.getName()+", Zipcode="+emp.getAddress().getZipcode()); - } -} -``` -Output -``` -Hibernate Configuration loaded -Hibernate serviceRegistry created -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -1:: Name=Alex, Zipcode=95129 -2:: Name=Alex, Zipcode=95129 -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -3:: Name=AlexK, Zipcode=95129 -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -4:: Name=David, Zipcode=95051 -Session Contains Employee with id=1?false -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -5:: Name=Alex, Zipcode=95129 -6:: Name=David, Zipcode=95051 -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -7:: Name=Alex, Zipcode=95129 -Hibernate: select employee0_.emp_id as emp_id1_1_0_, employee0_.emp_name as emp_name2_1_0_, employee0_.emp_salary as emp_sala3_1_0_, address1_.emp_id as emp_id1_0_1_, address1_.address_line1 as address_2_0_1_, address1_.city as city3_0_1_, address1_.zipcode as zipcode4_0_1_ from EMPLOYEE employee0_ left outer join ADDRESS address1_ on employee0_.emp_id=address1_.emp_id where employee0_.emp_id=? -8:: Name=David, Zipcode=95051 -Session Contains Employee with id=2?true -``` - - -## Q. What is second level cache in Hibernate? -**Hibernate second level cache** uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory. **SessionFactory** holds the second level cache data. It is global for all the session objects and not enabled by default. - -Different vendors have provided the implementation of Second Level Cache. - -* EH Cache -* OS Cache -* Swarm Cache -* JBoss Cache - -Each implementation provides different cache usage functionality. There are four ways to use second level cache. - -* **read-only**: caching will work for read only operation. -* **nonstrict-read-write**: caching will work for read and write but one at a time. -* **read-write**: caching will work for read and write, can be used simultaneously. -* **transactional**: caching will work for transaction. - -The cache-usage property can be applied to class or collection level in hbm.xml file. -```xml - -``` -Example: Hibernate Second Level Cache - - -Step 01: Create the persistent class using Maven -```java -package com.example; -import javax.persistence.*; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; -@Entity -@Table(name="emp1012") -@Cacheable -@Cache(usage=CacheConcurrencyStrategy.READ_ONLY) -public class Employee { - @Id - private int id; - private String name; - private float salary; - - public Employee() {} - public Employee(String name, float salary) { - super(); - this.name = name; - this.salary = salary; - } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public float getSalary() { - return salary; - } - public void setSalary(float salary) { - this.salary = salary; - } -} -``` -Step 02: Add project information and configuration in pom.xml file. -```xml - - org.hibernate - hibernate-core - 5.2.16.Final - - - - com.oracle - ojdbc14 - 10.2.0.4.0 - - - - net.sf.ehcache - ehcache - 2.10.3 - - - - org.hibernate - hibernate-ehcache - 5.2.16.Final - -``` -Step 03: Create the Configuration file (hibernate.cfg.xml) -```xml - - - - - - - true - update - org.hibernate.dialect.Oracle9Dialect - jdbc:oracle:thin:@localhost:1521:xe - system - jtp - oracle.jdbc.driver.OracleDriver - - true - org.hibernate.cache.ehcache.EhCacheRegionFactory - - - -``` -Step 04: Create the class that retrieves the persistent object -```java -package com.example; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; - -public class FetchTest { - - public static void main(String[] args) { - - StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); - Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build(); - - SessionFactory factory = meta.getSessionFactoryBuilder().build(); - - Session session1 = factory.openSession(); - Employee emp1 = (Employee)session1.load(Employee.class,121); - System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary()); - session1.close(); - - Session session2 = factory.openSession(); - Employee emp2 = (Employee)session2.load(Employee.class,121); - System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary()); - session2.close(); - - } -} -``` - - -## Q. What are concurrency strategies? -The READ_WRITE strategy is an asynchronous cache concurrency mechanism and to prevent data integrity issues (e.g. stale cache entries), it uses a locking mechanism that provides unit-of-work isolation guarantees. - -In hibernate, cache concurrency strategy can be set globally using the property hibernate.cache. default_cache_concurrency_strategy. The allowed values are, - -* **read-only**: caching will work for read only operation. supported by ConcurrentHashMap, EHCache, Infinispan -* **nonstrict-read-write**: caching will work for read and write but one at a time. supported by ConcurrentHashMap, EHCache. -* **read-write**: caching will work for read and write, can be used simultaneously. supported by ConcurrentHashMap, EHCache. -* **transactional**: caching will work for transaction. supported by EHCache, Infinispan. - -Example: Inserting data ( READ_WRITE strategy ) -```java -@Override -public boolean afterInsert( - Object key, Object value, Object version) - throws CacheException { - region().writeLock( key ); - try { - final Lockable item = - (Lockable) region().get( key ); - if ( item == null ) { - region().put( key, - new Item( value, version, - region().nextTimestamp() - ) - ); - return true; - } - else { - return false; - } - } - finally { - region().writeUnlock( key ); - } -} -``` -For an entity to be cached upon insertion, it must use a SEQUENCE generator, the cache being populated by the EntityInsertAction: -```java -@Override -public void doAfterTransactionCompletion(boolean success, - SessionImplementor session) - throws HibernateException { - - final EntityPersister persister = getPersister(); - if ( success && isCachePutEnabled( persister, - getSession() ) ) { - final CacheKey ck = getSession() - .generateCacheKey( - getId(), - persister.getIdentifierType(), - persister.getRootEntityName() ); - - final boolean put = cacheAfterInsert( - persister, ck ); - } - } - postCommitInsert( success ); -} -``` - - -## Q. What is Lazy loading in hibernate? -Hibernate defaults to a lazy fetching strategy for all entities and collections. Lazy loading in hibernate improves the performance. It loads the child objects on demand. To enable lazy loading explicitly you must use **fetch = FetchType.LAZY** on a association which you want to lazy load when you are using hibernate annotations. - -Example: -```java -@OneToMany( mappedBy = "category", fetch = FetchType.LAZY ) -private Set products; -``` -## Q. Explain the persistent classes in Hibernate? -Persistence class are simple POJO classes in an application. It works as implementation of the business application for example Employee, department etc. It is not necessary that all instances of persistence class are defined persistence. - -There are following main rules of persistent classes - -* A persistence class should have a default constructor. -* A persistence class should have an id to uniquely identify the class objects. -* All attributes should be declared private. -* Public getter and setter methods should be defined to access the class attributes. - -```java -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.util.Date; - -@Entity -@Table(name = "employee") -public class Employee { - @Id - @GeneratedValue - @Column(name = "emp_id") - private int id; - - @Column(name = "name") - private String name; - - @Column(name = "salary") - private int salary; - - @Column(name = "date_of_join") - private Date dateOfJoin; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getSalary() { - return salary; - } - - public void setSalary(int salary) { - this.salary = salary; - } - - public Date getDateOfJoin() { - return dateOfJoin; - } - - public void setDateOfJoin(Date dateOfJoin) { - this.dateOfJoin = dateOfJoin; - } -} -``` - - -## Q. Explain some of the elements of hbm.xml? -Hibernate mapping file is used by hibernate framework to get the information about the mapping of a POJO class and a database table. - -It mainly contains the following mapping information: - -* Mapping information of a POJO class name to a database table name. -* Mapping information of POJO class properties to database table columns. - -Elements of the Hibernate mapping file: - -* **hibernate-mapping**: It is the root element. -* **Class**: It defines the mapping of a POJO class to a database table. -* **Id**: It defines the unique key attribute or primary key of the table. -* **generator**: It is the sub element of the id element. It is used to automatically generate the id. -* **property**: It is used to define the mapping of a POJO class property to database table column. - -Syntax -```xml - - - - - - - - - . . . . . - - - -``` -## Q. What is Java Persistence API (JPA)? -Java Persistence API is a collection of classes and methods to persistently store the vast amounts of data into a database. -The Java Persistence API (JPA) is one possible approach to ORM. Via JPA the developer can map, store, update and retrieve data from relational databases to Java objects and vice versa. JPA can be used in Java-EE and Java-SE applications. - -JPA metadata is typically defined via annotations in the Java class. Alternatively, the metadata can be defined via XML or a combination of both. A XML configuration overwrites the annotations. - -**Relationship Mapping** - -JPA allows to define relationships between classes. Classes can have one to one, one to many, many to one, and many to many relationships with other classes. A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. - -Relationship annotations: - -* @OneToOne -* @OneToMany -* @ManyToOne -* @ManyToMany - -![Java Exception](https://github.com/learning-zone/java-interview-questions/blob/master/assets/jpa_class_level_architecture.png) - -**JPA - Architecture** - -|Units |Description | -|-----------------------|---------------------------------------------------------------| -|EntityManagerFactory |This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.| -|EntityManager |It is an Interface, it manages the persistence operations on objects. It works like factory for Query instance.| -|Entity |Entities are the persistence objects, stores as records in the database.| -|EntityTransaction |It has one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.| -|Persistence |This class contain static methods to obtain EntityManagerFactory instance.| -|Query |This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.| - - - -## Q. Name some important interfaces of Hibernate framework? -* **Session Interface**: This is the primary interface used by hibernate applications -The instances of this interface are lightweight and are inexpensive to create and destroy -Hibernate sessions are not thread safe - -* **Session Factory Interface**: This is a factory that delivers the session objects to hibernate application. - -* **Configuration Interface**: This interface is used to configure and bootstrap hibernate. -The instance of this interface is used by the application in order to specify the location of hbm documents - -* **Transaction Interface**: This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction - -* **Query and Criteria Interface**: This interface allows the user to perform queries and also control the flow of the query execution - -## Q. What is Hibernate SessionFactory and how to configure it? -SessionFactory can be created by providing Configuration object, which will contain all DB related property details pulled from either hibernate.cfg.xml file or hibernate.properties file. SessionFactory is a factory for Session objects. - -We can create one SessionFactory implementation per database in any application. If your application is referring to multiple databases, then we need to create one SessionFactory per database. - -The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. The SessionFactory is a thread safe object and used by all the threads of an application. -```java -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; - -import com.example.model.Employee; - -public class HibernateUtil { - - private static SessionFactory sessionFactory = null; - - static { - try { - loadSessionFactory(); - } catch(Exception e){ - System.err.println("Exception while initializing hibernate util.. "); - e.printStackTrace(); - } - } - - public static void loadSessionFactory() { - - Configuration configuration = new Configuration(); - configuration.configure("/j2n-hibernate.cfg.xml"); - configuration.addAnnotatedClass(Employee.class); - ServiceRegistry srvcReg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); - sessionFactory = configuration.buildSessionFactory(srvcReg); - } - - public static Session getSession() throws HibernateException { - - Session retSession=null; - try { - retSession = sessionFactory.openSession(); - } catch(Throwable t) { - System.err.println("Exception while getting session.. "); - t.printStackTrace(); - } - if(retSession == null) { - System.err.println("session is discovered null"); - } - return retSession; - } -} -``` - - -## Q. What is the difference between opensession and getcurrentsession in hibernate? -Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed. - -Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. - -|Parameter |openSession |getCurrentSession | -|-------------------|-------------------|--------------------------------| -|Session object |It always create new Session object |It creates a new Session if not exists , else use same session which is in current hibernate context| -|Flush and close |You need to explicitly flush and close session objects|You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally| -|Performance |In single threaded environment , It is slower than getCurrentSession|In single threaded environment , It is faster than getOpenSession| -|Configuration |You do not need to configure any property to call this method|You need to configure additional property “hibernate.current_session_context_class” to call getCurrentSession method, otherwise it will throw exceptions.| - -Example: openSession() -```java -Transaction transaction = null; -Session session = HibernateUtil.getSessionFactory().openSession(); -try { - transaction = session.beginTransaction(); - // do Some work - - session.flush(); // extra work - transaction.commit(); -} catch(Exception ex) { - if(transaction != null) { - transaction.rollback(); - } - ex.printStackTrace(); -} finally { - if(session != null) { - session.close(); // extra work - } -} -``` -Example: getCurrentSession() -```java -Transaction transaction = null; -Session session = HibernateUtil.getSessionFactory().getCurrentSession(); -try { - transaction = session.beginTransaction(); - // do Some work - - // session.flush(); // no need - transaction.commit(); -} catch(Exception ex) { - if(transaction != null) { - transaction.rollback(); - } - ex.printStackTrace(); -} finally { - if(session != null) { - // session.close(); // no need - } -} -``` - - -## Q. What is difference between Hibernate Session get() and load() method? -Hibernate Session class provides two method to access object e.g. `session.get()` and `session.load()`.The difference between get() vs load() method is that get() involves database hit if object doesn't exists in **Session Cache** and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance. - -|load() |get() -|-----------------------------------------------|------------------------------------------------- -|Only use the load() method if you are sure that the object exists.|If you are not sure that the object exists, then use one of the get() methods.| -|load() method will throw an exception if the unique id is not found in the database.|get() method will return null if the unique id is not found in the database.| -|load() just returns a proxy by default and database won't be hit until the proxy is first invoked.|get() will hit the database immediately.| - -## Q. What are different states of an entity bean? -The Entity bean has three states: - -**1. Transient**: Transient objects exist in heap memory. Hibernate does not manage transient objects or persist changes to transient objects. Whenever pojo class object created then it will be in the Transient state. - -Transient state Object does not represent any row of the database, It means not associated with any Session object or no relation with the database its just an normal object. - -**2. Persistent**: Persistent objects exist in the database, and Hibernate manages the persistence for persistent objects. If fields or properties change on a persistent object, Hibernate will keep the database representation up to date when the application marks the changes as to be committed. - -Any instance returned by a **get()** or **load()** method is persistent state object. - -**3. Detached**: Detached objects have a representation in the database, but changes to the object will not be reflected in the database, and vice-versa. A detached object can be created by closing the session that it was associated with, or by evicting it from the session with a call to the session's `evict()` method. - -Example: -```java -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.cfg.AnnotationConfiguration; - -import com.example.hibernate.Student; - -public class ObjectStatesDemo { - - public static void main(String[] args) { - - // Transient object state - Student student = new Student(); - student.setId(101); - student.setName("Alex"); - student.setRoll("10"); - student.setDegree("B.E"); - student.setPhone("9999"); - - // Transient object state - Session session = new AnnotationConfiguration().configure() - .buildSessionFactory().openSession(); - Transaction t = session.beginTransaction(); - - // Persistent object state - session.save(student); - t.commit(); - - // Detached object state - session.close(); - } -} -``` -Output -``` -Hibernate: - insert - into - STUDENT - (degree, name, phone, roll, id) - values - (?, ?, ?, ?, ?) -``` -In The Database : -```sql -mysql> select * from student; -+-----+--------+--------+-------+------+ -| id | degree | name | phone | roll | -+-----+--------+--------+-------+------+ -| 101 | B.E | Alex | 9999 | 10 | -+-----+--------+--------+-------+------+ -1 row in set (0.05 sec) -``` - - -## Q. What is difference between merge() and update() methods in Hibernate? -Both update() and merge() methods in hibernate are used to convert the object which is in detached state into persistence state. But there are different situation where we should be used update() and where should be used merge() method in hibernate - -```java -Employee emp1 = new Employee(); -emp1.setEmpId(100); -emp1.setEmpName("Alex"); -//create session -Session session1 = createNewHibernateSession(); -session1.saveOrUpdate(emp1); -session1.close(); -//emp1 object in detached state now - -emp1.setEmpName("Alex Rajput");// Updated Name -//Create session again -Session session2 = createNewHibernateSession(); -Employee emp2 =(Employee)session2.get(Employee.class, 100); -//emp2 object in persistent state with id 100 - -/** -Try to make on detached object with id 100 to persistent state by using update method of hibernate -It occurs the exception NonUniqueObjectException because emp2 object is having employee with same -empid as 100. In order to avoid this exception we are using merge like given below instead of -**/ -session2.update(emp1); -session.update(emp1); - -session2.merge(emp1); //it merge the object state with emp2 -session2.update(emp1); //Now it will work with exception -``` -In the hibernate session we can maintain only one employee object in persistent state with same primary key, while converting a detached object into persistent, if already that session has a persistent object with the same primary key then hibernate throws an Exception whenever update() method is called to reattach a detached object with a session. In this case we need to call **merge()** method instead of **update()** so that hibernate copies the state changes from detached object into persistent object and we can say a detached object is converted into a persistent object. - - - -#### Q. What is difference between Hibernate save(), saveOrUpdate() and persist() methods? -#### Q. What will happen if we don’t have no-args constructor in Entity bean? -#### Q. What is difference between sorted collection and ordered collection, which one is better? -#### Q. What are the collection types in Hibernate? -#### Q. How to implement Joins in Hibernate? -#### Q. Why we should not make Entity Class final? -#### Q. What is the benefit of native sql query support in hibernate? -#### Q. What is Named SQL Query? What are the benefits of Named SQL Query? -#### Q. How to log hibernate generated sql queries in log files? -#### Q. What is cascading and what are different types of cascading? -#### Q. How to integrate log4j logging in hibernate application? -#### Q. What is HibernateTemplate class? -#### Q. How to integrate Hibernate with Servlet or Struts2 web applications? -#### Q. Which design patterns are used in Hibernate framework? -#### Q. What is Hibernate Validator Framework? -#### Q. What is the benefit of Hibernate Tools Eclipse plugin? -#### Q. What are the technologies that are supported by Hibernate? -#### Q. What is your understanding of Hibernate proxy? -#### Q. Can you explain Hibernate callback interfaces? -#### Q. How to create database applications in Java with the use of Hibernate? -#### Q. Can you share your views on mapping description files? -#### Q. What are your thoughts on file mapping in Hibernate? -#### Q. Can you explain version field? -#### Q. What are your views on the function addClass? -#### Q. Can you explain the role of addDirectory() and addjar() methods? -#### Q. What do you understand by Hibernate tuning? -#### Q. What is your understanding of Light Object Mapping? -#### Q. How does Hibernate create the database connection? -#### Q. What are possible ways to configure object-table mapping? -#### Q. Which annotation is used to declare a class as a hibernate bean? -#### Q. How do I specify table name linked to an entity using annotation? -#### Q. How does a variable in an entity connect to the database column? -#### Q. How do we specify a different column name for the variables mapping? -#### Q. How do we specify a variable to be primary key for the table? -#### Q. How do you configure the dialect in hibernate.cfg.xml? -#### Q. How to configure the database URL and credentials in hibernate.cfg.xml? -#### Q. How to configure the connection pool size? -#### Q. How do you configure folder scan for Hibernate beans? -#### Q. How to configure hibernate beans without Spring framework? -#### Q. Is it possible to connect multiple database in a single Java application using Hibernate? -#### Q. Does Hibernate support polymorphism? -#### Q. How many Hibernate sessions exist at any point of time in an application? -#### Q. What is N+1 SELECT problem in Hibernate? What are some strategies to solve the N+1 SELECT problem in Hibernate? -#### Q. What is the requirement for a Java object to become a Hibernate entity object? -#### Q. How do you log SQL queries issued by the Hibernate framework in Java application? -#### Q. What is the difference between the transient, persistent and detached state in Hibernate? -#### Q. How properties of a class are mapped to the columns of a database table in Hibernate? -#### Q. What is the usage of Configuration Interface in hibernate? -#### Q. How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate? -#### Q. What are POJOs and what is their significance? -#### Q. How can we invoke stored procedures in hibernate? -#### Q. What are the benefits of using Hibernate template? -#### Q. How can we get hibernate statistics? -#### Q. How can we reduce database write action times in Hibernate? -#### Q. When an instance goes in detached state in hibernate? -#### Q. What the four ORM levels are in hibernate? -#### Q. What is the default cache service of hibernate? -#### Q. What are the two mapping associations used in hibernate? -#### Q. What is the usage of Hibernate QBC API? -#### Q. In how many ways, objects can be fetched from database in hibernate? -#### Q. How primary key is created by using hibernate? -#### Q. How can we reattach any detached objects in Hibernate? -#### Q. What are different ways to disable hibernate second level cache? -#### Q. What is ORM metadata? -#### Q. Which one is the default transaction factory in hibernate? -#### Q. What is the role of JMX in hibernate? -#### Q. In how many ways objects can be identified in Hibernate? -#### Q. What different fetching strategies are of hibernate? -#### Q. How mapping of java objects is done with database tables? -#### Q. What are derived properties in hibernate? -#### Q. What is the use of version property in hibernate? -#### Q. What is attribute oriented programming? -#### Q. What is the use of session.lock() in hibernate? -#### Q. What the three inheritance models are of hibernate? -#### Q. What is general hibernate flow using RDBMS? -#### Q. What is difference between managed associations and hibernate associations? -#### Q. What are the inheritance mapping strategies? -#### Q. What is automatic dirty checking in hibernate? -#### Q. Explain Hibernate configuration file and Hibernate mapping file? - - diff --git a/java-design-pattern-questions.md b/java-design-pattern-questions.md deleted file mode 100644 index b04fb5c..0000000 --- a/java-design-pattern-questions.md +++ /dev/null @@ -1,608 +0,0 @@ -# Java Design Pattern Questions and Answers - -## Q. Exaplain MVC, Front-Controller, DAO, DTO, Service-Locator, Prototype design patterns? - -**2. Front-Controller** - -The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern. - -* Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based). - -* Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. - -* View - Views are the object for which the requests are made. - -*Example:* - -We are going to create a `FrontController` and `Dispatcher` to act as Front Controller and Dispatcher correspondingly. `HomeView` and `StudentView` represent various views for which requests can come to front controller. - -FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate Front Controller Design Pattern. - -Step 1 -Create Views. - -*HomeView.java* -```java -public class HomeView { - public void show(){ - System.out.println("Displaying Home Page"); - } -} -``` -*StudentView.java* -```java -public class StudentView { - public void show(){ - System.out.println("Displaying Student Page"); - } -} -``` - -Step2 -Create Dispatcher. - -*Dispatcher.java* -```java -public class Dispatcher { - private StudentView studentView; - private HomeView homeView; - - public Dispatcher(){ - studentView = new StudentView(); - homeView = new HomeView(); - } - - public void dispatch(String request){ - if(request.equalsIgnoreCase("STUDENT")){ - studentView.show(); - } - else{ - homeView.show(); - } - } -} -``` - -Step3 -Create FrontController. - -*FrontController.java* -```java -public class FrontController { - - private Dispatcher dispatcher; - - public FrontController(){ - dispatcher = new Dispatcher(); - } - - private boolean isAuthenticUser(){ - System.out.println("User is authenticated successfully."); - return true; - } - - private void trackRequest(String request){ - System.out.println("Page requested: " + request); - } - - public void dispatchRequest(String request){ - //log each request - trackRequest(request); - - //authenticate the user - if(isAuthenticUser()){ - dispatcher.dispatch(request); - } - } -} -``` - -Step4 -Use the FrontController to demonstrate Front Controller Design Pattern. - -*FrontControllerPatternDemo.java* -```java -public class FrontControllerPatternDemo { - public static void main(String[] args) { - - FrontController frontController = new FrontController(); - frontController.dispatchRequest("HOME"); - frontController.dispatchRequest("STUDENT"); - } -} -``` - - - -## Q. What are the design patterns available in Java? - -Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns. - -**1. Creational Design Patterns** - -* Singleton Pattern -* Factory Pattern -* Abstract Factory Pattern -* Builder Pattern -* Prototype Pattern - -**2. Structural Design Patterns** - -* Adapter Pattern -* Composite Pattern -* Proxy Pattern -* Flyweight Pattern -* Facade Pattern -* Bridge Pattern -* Decorator Pattern - -**3. Behavioral Design Patterns** - -* Template Method Pattern -* Mediator Pattern -* Chain of Responsibility Pattern -* Observer Pattern -* Strategy Pattern -* Command Pattern -* State Pattern -* Visitor Pattern -* Interpreter Pattern -* Iterator Pattern -* Memento Pattern - -**4. Miscellaneous Design Patterns** - -* DAO Design Pattern -* Dependency Injection Pattern -* MVC Pattern - - - -## Q. Explain Singleton Design Pattern in Java? - -**1. Eager initialization:** -In eager initialization, the instance of Singleton Class is created at the time of class loading. - -Example: -```java -public class EagerInitializedSingleton { - - private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); - - // private constructor to avoid client applications to use constructor - private EagerInitializedSingleton(){} - - public static EagerInitializedSingleton getInstance(){ - return instance; - } -} -``` - -**2. Static block initialization** -Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling. - -Example: -```java -public class StaticBlockSingleton { - - private static StaticBlockSingleton instance; - - private StaticBlockSingleton (){} - - // static block initialization for exception handling - static{ - try{ - instance = new StaticBlockSingleton (); - }catch(Exception e){ - throw new RuntimeException("Exception occured in creating Singleton instance"); - } - } - - public static StaticBlockSingleton getInstance(){ - return instance; - } -} -``` - -**3. Lazy Initialization** -Lazy initialization method to implement Singleton pattern creates the instance in the global access method. - -Example: -```java -public class LazyInitializedSingleton { - - private static LazyInitializedSingleton instance; - - private LazyInitializedSingleton(){} - - public static LazyInitializedSingleton getInstance(){ - if(instance == null){ - instance = new LazyInitializedSingleton (); - } - return instance; - } -} -``` - -**4. Thread Safe Singleton** -The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. - -Example: -```java -public class ThreadSafeSingleton { - - private static ThreadSafeSingleton instance; - - private ThreadSafeSingleton(){} - - public static synchronized ThreadSafeSingleton getInstance(){ - if(instance == null){ - instance = new ThreadSafeSingleton(); - } - return instance; - } -} -``` - -**5. Bill Pugh Singleton Implementation** -Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton. - -Example: -```java -public class BillPughSingleton { - - private BillPughSingleton(){} - - private static class SingletonHelper{ - private static final BillPughSingleton INSTANCE = new BillPughSingleton(); - } - - public static BillPughSingleton getInstance(){ - return SingletonHelper.INSTANCE; - } -} -``` - - - -## Q. Explain Adapter Design Pattern in Java? - -Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter. - -Example: - -we have two incompatible interfaces: **MediaPlayer** and **MediaPackage**. MP3 class is an implementation of the MediaPlayer interface and we have VLC and MP4 as implementations of the MediaPackage interface. We want to use MediaPackage implementations as MediaPlayer instances. So, we need to create an adapter to help to work with two incompatible classes. - -MediaPlayer.java -```java -public interface MediaPlayer { - void play(String filename); -} -``` - -MediaPackage.java -```java -public interface MediaPackage { - void playFile(String filename); -} -``` - -MP3.java -```java -public class MP3 implements MediaPlayer { - @Override - public void play(String filename) { - System.out.println("Playing MP3 File " + filename); - } -} -``` - -MP4.java -```java -public class MP4 implements MediaPackage { - @Override - public void playFile(String filename) { - System.out.println("Playing MP4 File " + filename); - } -} -``` - -VLC.java -```java -public class VLC implements MediaPackage { - @Override - public void playFile(String filename) { - System.out.println("Playing VLC File " + filename); - } -} -``` - -FormatAdapter.java -```java -public class FormatAdapter implements MediaPlayer { - private MediaPackage media; - public FormatAdapter(MediaPackage m) { - media = m; - } - @Override - public void play(String filename) { - System.out.print("Using Adapter --> "); - media.playFile(filename); - } -} -``` - -Main.java -```java -public class Main { - public static void main(String[] args) { - MediaPlayer player = new MP3(); - player.play("file.mp3"); - player = new FormatAdapter(new MP4()); - player.play("file.mp4"); - player = new FormatAdapter(new VLC()); - player.play("file.avi"); - } -} -``` - - - -## Q. Explain Factory Design Pattern in Java? - -A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class. - -Example: Calculate Electricity Bill -Plan.java - -```java -import java.io.*; -abstract class Plan { - protected double rate; - abstract void getRate(); - - public void calculateBill(int units){ - System.out.println(units*rate); - } -} -``` - -DomesticPlan.java -```java -class DomesticPlan extends Plan{ - @override - public void getRate(){ - rate=3.50; - } -} -``` - -CommercialPlan.java -```java -class CommercialPlan extends Plan{ - @override - public void getRate(){ - rate=7.50; - } -} -``` - -InstitutionalPlan.java -```java -class InstitutionalPlan extends Plan{ - @override - public void getRate(){ - rate=5.50; - } -} -``` - -GetPlanFactory.java -```java -class GetPlanFactory { - - // use getPlan method to get object of type Plan - public Plan getPlan(String planType){ - if(planType == null){ - return null; - } - if(planType.equalsIgnoreCase("DOMESTICPLAN")) { - return new DomesticPlan(); - } - else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){ - return new CommercialPlan(); - } - else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) { - return new InstitutionalPlan(); - } - return null; - } -} -``` - -GenerateBill.java -```java -import java.io.*; -class GenerateBill { - - public static void main(String args[])throws IOException { - GetPlanFactory planFactory = new GetPlanFactory(); - - System.out.print("Enter the name of plan for which the bill will be generated: "); - BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); - - String planName=br.readLine(); - System.out.print("Enter the number of units for bill will be calculated: "); - int units=Integer.parseInt(br.readLine()); - - Plan p = planFactory.getPlan(planName); - // call getRate() method and calculateBill()method of DomesticPaln. - - System.out.print("Bill amount for "+planName+" of "+units+" units is: "); - p.getRate(); - p.calculateBill(units); - } -} -``` - - - -## Q. Explain Strategy Design Pattern in Java? - -Strategy design pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime. - -Example: Simple Shopping Cart where we have two payment strategies – using Credit Card or using PayPal. - -PaymentStrategy.java -```java -public interface PaymentStrategy { - public void pay(int amount); -} -``` - -CreditCardStrategy.java -```java -public class CreditCardStrategy implements PaymentStrategy { - - private String name; - private String cardNumber; - private String cvv; - private String dateOfExpiry; - - public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ - this.name=nm; - this.cardNumber=ccNum; - this.cvv=cvv; - this.dateOfExpiry=expiryDate; - } - @Override - public void pay(int amount) { - System.out.println(amount +" paid with credit/debit card"); - } -} -``` - -PaypalStrategy.java -```java -public class PaypalStrategy implements PaymentStrategy { - - private String emailId; - private String password; - - public PaypalStrategy(String email, String pwd){ - this.emailId=email; - this.password=pwd; - } - @Override - public void pay(int amount) { - System.out.println(amount + " paid using Paypal."); - } -} -``` - -Item.java -```java -public class Item { - - private String upcCode; - private int price; - - public Item(String upc, int cost){ - this.upcCode=upc; - this.price=cost; - } - public String getUpcCode() { - return upcCode; - } - public int getPrice() { - return price; - } -} -``` - -ShoppingCart.java -```java -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; - -public class ShoppingCart { - - List items; - - public ShoppingCart(){ - this.items=new ArrayList(); - } - public void addItem(Item item){ - this.items.add(item); - } - public void removeItem(Item item){ - this.items.remove(item); - } - public int calculateTotal(){ - int sum = 0; - for(Item item : items){ - sum += item.getPrice(); - } - return sum; - } - public void pay(PaymentStrategy paymentMethod){ - int amount = calculateTotal(); - paymentMethod.pay(amount); - } -} -``` - -ShoppingCartTest.java -```java -public class ShoppingCartTest { - - public static void main(String[] args) { - ShoppingCart cart = new ShoppingCart(); - - Item item1 = new Item("1234",10); - Item item2 = new Item("5678",40); - - cart.addItem(item1); - cart.addItem(item2); - - // pay by paypal - cart.pay(new PaypalStrategy("myemail@example.com", "mypwd")); - - // pay by credit card - cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15")); - } -} -``` -Output -``` -500 paid using Paypal. -500 paid with credit/debit card -``` - - - -#### Q. When do you use Flyweight pattern? -#### Q. What is difference between dependency injection and factory design pattern? -#### Q. Difference between Adapter and Decorator pattern? -#### Q. Difference between Adapter and Proxy Pattern? -#### Q. What is Template method pattern? -#### Q. When do you use Visitor design pattern? -#### Q. When do you use Composite design pattern? -#### Q. Difference between Abstract factory and Prototype design pattern? - - diff --git a/java-multiple-choice-questions-answers.md b/java-multiple-choice-questions-answers.md index 0865d44..33e86f6 100644 --- a/java-multiple-choice-questions-answers.md +++ b/java-multiple-choice-questions-answers.md @@ -41,6 +41,8 @@ D. int num1 = 0, num2 = 0; ``` A. double num1, int num2 = 0; ``` +**Explanation**: A. Option A does not compile because Java does not allow declaring different types as part of the same declaration. + ## Q. What is the output of following program? ```java public class Test { @@ -214,15 +216,6 @@ Output a : 2 J : 2 ``` -## Q. Which of the following declarations does not compile? -A. double num1, int num2 = 0; -B. int num1, num2; -C. int num1, num2 = 0; -D. int num1 = 0, num2 = 0; -``` -A. double num1, int num2 = 0; -``` -**Explanation**: A. Option A does not compile because Java does not allow declaring different types as part of the same declaration. ## Q. What is the output of the following? ```java @@ -461,10 +454,10 @@ B. 2 C. 3 D. 6 ``` -A. 1 +D. 6 ``` -**Explanation**: In ternary expressions, only one of the two right-most expressions are evaluated. Since `meal>6` is false, `––tip` is evaluated and `++tip` is skipped. The result is that `tip` is changed from 2 to 1. - +**Explanation**: In ternary expressions, only one of the two right-most expressions are evaluated. Since `meal>6` is false, `––tip` is evaluated and `++tip` is skipped. `tip` is changed from 2 to 1 and `total` becomes `meal + (1)` which means `5 + 1 = 6`. + ## Q. What is the output of the following application? ```java String john = "john"; diff --git a/java-programs.md b/java-programs.md index 96619d8..bc37276 100644 --- a/java-programs.md +++ b/java-programs.md @@ -1,7 +1,8 @@ # Java Programs ## Q. Write a function to find out duplicate words in a given string? -**Approach** + +**Approach:** 1. Define a string. 1. Convert the string into lowercase to make the comparison insensitive. @@ -42,14 +43,18 @@ public class DuplicateWord { } } ``` + Output -``` + +```java Duplicate words in a given string : big black ``` + ## Q. Find the missing number in an array? -**Approach** + +**Approach:** 1. Calculate `A = n (n+1)/2` where n is largest number in series 1…N. 1. Calculate B = Sum of all numbers in given series @@ -84,9 +89,55 @@ Output ↥ back to top -#### Q. Write a program to generate random numbers between the given range? +## Q. Write a program to generate random numbers between the given range? + +**Approach** +1. Get the Min and Max which are the specified range. +1. Call the nextInt() method of ThreadLocalRandom class (java.util.concurrent.ThreadLocalRandom) and specify the Min and Max value as the parameter as +`ThreadLocalRandom.current().nextInt(min, max + 1);` +1. Return the received random value + +```java +// Java program to generate a random integer +// within this specific range + +import java.util.concurrent.ThreadLocalRandom; + +class GFG { + + public static int getRandomValue(int Min, int Max) + { + + // Get and return the random integer + // within Min and Max + return ThreadLocalRandom + .current() + .nextInt(Min, Max + 1); + } + + // Driver code + public static void main(String[] args) + { -*ToDo* + int Min = 1, Max = 100; + + System.out.println("Random value between " + + Min + " and " + Max + ": " + + getRandomValue(Min, Max)); + } +} + +``` + +**Input** +``` +Input: Min = 1, Max = 10 +``` + +**Output** +``` +Random value between 1 and 100: 35 +``` ## Q. Write a java program to swap two string variables without using temp variable? **Approach** @@ -1674,6 +1725,194 @@ Path from vertex 0 to vertex 4 has minimum cost of 3 and the route is [ 0 4 ] ↥ back to top +## Q. How to display 10 random numbers using forEach()? + +```java +( new Random ()) + .ints () + .limit ( 10 ) + .forEach ( System . out :: println); +``` + + + +## Q. How can I display unique squares of numbers using the method map()? + +```java +Stream + .of ( 1 , 2 , 3 , 2 , 1 ) + .map (s -> s * s) + .distinct () + .collect ( Collectors . toList ()) + .forEach ( System . out :: println); +``` + + + +## Q. How to display the number of empty lines using the method filter()? + +```java +System.out.println ( + Stream + .of ( " Hello " , " " , " , " , " world " , " ! " ) + .filter ( String :: isEmpty) + .count ()); +``` + + + +## Q. How to display 10 random numbers in ascending order? + +```java +( new Random ()) + .ints () + .limit ( 10 ) + .sorted () + .forEach ( System . out :: println); +``` + + + +## Q. How to find the maximum number in a set? + +```java +Stream + .of ( 5 , 3 , 4 , 55 , 2 ) + .mapToInt (a -> a) + .max () + .getAsInt (); // 55 +``` + + + +## Q. How to find the minimum number in a set? + +```java +Stream + .of ( 5 , 3 , 4 , 55 , 2 ) + .mapToInt (a -> a) + .min () + .getAsInt (); // 2 +``` + + + +## Q. How to get the sum of all numbers in a set? + +```java +Stream + .of( 5 , 3 , 4 , 55 , 2 ) + .mapToInt() + .sum(); // 69 +``` + + + +## Q. How to get the average of all numbers? + +```java +Stream + .of ( 5 , 3 , 4 , 55 , 2 ) + .mapToInt (a -> a) + .average () + .getAsDouble (); // 13.8 +``` + + +## Q. How to get current date using Date Time API from Java 8? + +```java +LocalDate as.now(); +``` + + + +## Q. How to add 1 week, 1 month, 1 year, 10 years to the current date using the Date Time API? + +```java +LocalDate as.now ().plusWeeks ( 1 ); +LocalDate as.now ().plusMonths ( 1 ); +LocalDate as.now ().plusYears ( 1 ); +LocalDate as.now ().plus ( 1 , ChronoUnit.DECADES ); +``` + + + +## Q. How to get the next Tuesday using the Date Time API? + +```java +LocalDate as.now().with( TemporalAdjusters.next ( DayOfWeek.TUESDAY )); +``` + + + +## Q. How to get the current time accurate to milliseconds using the Date Time API? + +```java +new Date ().toInstant (); +``` + + + +## Q. How to get the second Saturday of the current month using the Date Time API? + +```java +LocalDate + .of ( LocalDate.Now ().GetYear (), LocalDate.Now ().GetMonth (), 1 ) + .with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SATURDAY )) + .with ( TemporalAdjusters.next ( DayOfWeek.SATURDAY )); +``` + + +## Q. How to get the current time in local time accurate to milliseconds using the Date Time API? + +```java +LocalDateTime.ofInstant ( new Date().toInstant(), ZoneId.systemDefault()); +``` + + + +## Q. How to sort a list of strings using a lambda expression? + +```java +public static List < String > sort ( List < String > list) { + Collections.sort(list, (a, b) -> a.compareTo(b)); + return list; +} +``` + + + #### Q. How to find if there is a sub array with sum equal to zero? #### Q. How to remove a given element from array in Java? #### Q. How to find trigonometric values of an angle in java? diff --git a/java-programs/BubbleSort.java b/java-programs/BubbleSort.java index 2f1ee8f..15b1d88 100644 --- a/java-programs/BubbleSort.java +++ b/java-programs/BubbleSort.java @@ -7,16 +7,22 @@ public class BubbleSort { public void bubbleSort(int[] arr) { + boolean swap; int n = arr.length; int tmp = 0; for (int i = 0; i < n ; i++) { - for (int j = 1; j < n-1; j++) { + swap = false; + for (int j = 1; j < n-i; j++) { if (arr[j-1] > arr[j]) { - tmp = arr[j - 1]; - arr[j-1] = arr[j]; - arr[j] = tmp; + tmp = arr[j]; + arr[j] = arr[j-1]; + arr[j-1] = tmp; + swap = true; } } + if (!swap){ + break; + } } } diff --git a/java-programs/DynamicProgramming/CoinChange.java b/java-programs/DynamicProgramming/CoinChange.java new file mode 100644 index 0000000..607b320 --- /dev/null +++ b/java-programs/DynamicProgramming/CoinChange.java @@ -0,0 +1,77 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class CoinChange { + + public static int coinChange(int[] coins, int amount) { + int n = coins.length; + int[][] dp = new int[n + 1][amount + 1]; + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= amount; j++) { + if (j == 0) { + dp[i][j] = 0; + } else if (i == 0) { + dp[i][j] = -1; + } else { + if (coins[i - 1] > j) { + dp[i][j] = dp[i - 1][j]; + } else { + int price = j; + int max = Integer.MIN_VALUE; + int count = 0; + while (price > 0) { + count++; + if (price >= coins[i - 1] && dp[i][price - coins[i - 1]] != -1) { + max = Math.max(max, count + dp[i][price - coins[i - 1]]); + } + + price -= coins[i - 1]; + } + + if (max == Integer.MIN_VALUE) { + if (price == 0) { + if (dp[i - 1][j] == -1) + dp[i][j] = count; + else + dp[i][j] = Math.min(dp[i - 1][j], count); + } else { + dp[i][j] = dp[i - 1][j]; + } + } else { + if (price == 0) { + if (dp[i - 1][j] == -1) + dp[i][j] = Math.min(max, count); + else + dp[i][j] = Math.min(dp[i - 1][j], Math.min(max, count)); + } else { + if (dp[i - 1][j] == -1) + dp[i][j] = max; + else + dp[i][j] = Math.min(dp[i - 1][j], max); + } + } + } + } + } + } + +// print(dp); + return dp[n][amount]; + } + + public static void print(int[][] dp) { + for (int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub +// [186,419,83,408] +// 6249 + int[] coins = {186,419,83,408}; + System.out.println(coinChange(coins, 6249)); + } + +} diff --git a/java-programs/DynamicProgramming/KnapSack.java b/java-programs/DynamicProgramming/KnapSack.java new file mode 100644 index 0000000..b6e65a1 --- /dev/null +++ b/java-programs/DynamicProgramming/KnapSack.java @@ -0,0 +1,69 @@ +package DynamicProgramming; + +import java.util.ArrayList; +import java.util.Arrays; + +public class KnapSack { + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] weight = { 7, 3, 4, 5 }; + int[] profit = { 42, 12, 40, 25 }; + int W = 10; + + System.out.println(solve(weight, profit, W, 0)); + System.out.println(dp(weight, profit, W)); + } + + public static int dp(int[] weight, int[] profit, int capacity) { + int n = weight.length; + int[][] dp = new int[n + 1][capacity + 1]; + + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= capacity; j++) { + if (i == 0 || j == 0) { + dp[i][j] = 0; + } else if (weight[i - 1] <= j) { + dp[i][j] = Math.max(dp[i - 1][j], profit[i - 1] + dp[i - 1][j - weight[i - 1]]); + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + + for (int i = 0; i <= n; i++) { + System.out.println(Arrays.toString(dp[i])); + } + + System.out.println(actual_knapsack_item(dp, capacity, n, weight)); + + return dp[n][capacity]; + } + + public static ArrayList actual_knapsack_item(int[][] dp, int capacity, int n, int[] weight) { + ArrayList items = new ArrayList<>(); + for (int i = n; i > 0 && capacity > 0; i--) { + if (dp[i][capacity] > dp[i - 1][capacity]) { + items.add(i); + capacity = capacity - weight[i - 1]; + } + } + + return items; + } + + public static int solve(int[] weight, int[] profit, int capacity, int index) { + if (index == weight.length) { + return 0; + } + + if (weight[index] <= capacity) { + return Math.max(profit[index] + solve(weight, profit, capacity - weight[index], index + 1), + solve(weight, profit, capacity, index + 1)); + } else { + return solve(weight, profit, capacity, index + 1); + } + + } + +} diff --git a/java-programs/DynamicProgramming/PrintingLCS.java b/java-programs/DynamicProgramming/PrintingLCS.java new file mode 100644 index 0000000..e017ee8 --- /dev/null +++ b/java-programs/DynamicProgramming/PrintingLCS.java @@ -0,0 +1,64 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class PrintingLCS { + + public static String commonLCS(String txt1, String txt2) { + String result = ""; + int n = txt1.length(); + int m = txt2.length(); + + int[][] dp = new int[n + 1][m + 1]; + for (int i = 0; i < n + 1; i++) { + for (int j = 0; j < m + 1; j++) { + if (i == 0 || j == 0) { + dp[i][j] = 0; + } else { + if (txt1.charAt(i - 1) == txt2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + } + + print(dp); + + if(dp[n][m] == 0) { + return result; + } + + int i = n; + int j = m; + + while(i > 0 && j > 0) { + if(dp[i][j] > dp[i - 1][j] && dp[i][j] > dp[i][j - 1]) { + result = txt1.charAt(i - 1) + result; + i--; + j--; + }else { + if(dp[i][j] == dp[i][j - 1]) { + j--; + }else { + i--; + } + } + } + + return result; + } + + public static void print(int[][] dp) { + for (int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(commonLCS("MZJAWXU","XMJYAUZ")); + } + +} diff --git a/java-programs/DynamicProgramming/editDistance.java b/java-programs/DynamicProgramming/editDistance.java new file mode 100644 index 0000000..e435a69 --- /dev/null +++ b/java-programs/DynamicProgramming/editDistance.java @@ -0,0 +1,30 @@ +package DynamicProgramming; + +public class editDistance { + + public static int eD(String s1, String s2, int n, int m) { + + if (m == 0) { + return n; + } + + if (n == 0) { + return m; + } + + if (s1.charAt(n - 1) == s2.charAt(m - 1)) { + return eD(s1, s2, n - 1, m - 1); + } else { + return 1 + Math.min(eD(s1, s2, m, n - 1), Math.min(eD(s1, s2, m - 1, n), eD(s1, s2, n - 1, m - 1))); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + // SATUR + // SU + + System.out.println(eD("SATURDAY", "SUNDAY", 8, 6)); + } + +} diff --git a/java-programs/DynamicProgramming/editDistanceOptimized.java b/java-programs/DynamicProgramming/editDistanceOptimized.java new file mode 100644 index 0000000..019cbf5 --- /dev/null +++ b/java-programs/DynamicProgramming/editDistanceOptimized.java @@ -0,0 +1,33 @@ +package DynamicProgramming; + +public class editDistanceOptimized { + + public static int eD(String s1, String s2, int n, int m) { + + int[][] dp = new int[n + 1][m + 1]; + + for (int i = 0; i < n + 1; i++) { + for (int j = 0; j < m + 1; j++) { + if (i == 0) { + dp[i][j] = j; + } else if (j == 0) { + dp[i][j] = i; + } else { + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1]; + } else { + dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); + } + } + } + } + + return dp[n][m]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(eD("SATURDAY", "SUNDAY", 8, 6)); + } + +} diff --git a/java-programs/DynamicProgramming/eggDroppingPuzzle.java b/java-programs/DynamicProgramming/eggDroppingPuzzle.java new file mode 100644 index 0000000..b53c3d5 --- /dev/null +++ b/java-programs/DynamicProgramming/eggDroppingPuzzle.java @@ -0,0 +1,63 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class eggDroppingPuzzle { + + public static int eggDrop(int e, int f) { + if (f == 0 || f == 1) { + return f; + } + + if (e == 1) { + return f; + } + + int res = Integer.MAX_VALUE; + for (int i = 1; i <= f; i++) { + res = Math.min(res, Math.max(eggDrop(e - 1, i - 1), eggDrop(e, f - i))); + } + + return res + 1; + } + + public static int optimize(int egg, int floor) { + int[][] dp = new int[egg + 1][floor + 1]; + + for(int i = 0; i <= egg; i++) { + for(int j = 0; j <= floor; j++) { + if(i == 0 || j == 0) { + dp[i][j] = 0; + }else if(i == 1) { + dp[i][j] = j; + }else if(j == 1) { + dp[i][j] = 1; + }else { + int res; + int min = Integer.MAX_VALUE; + for(int x = 1; x <= j; x++) { + res = Math.max(dp[i - 1][x - 1], dp[i][j - x]); + min = Math.min(min, res); + } + + dp[i][j] = min + 1; + } + } + } + + print(dp); + return dp[egg][floor]; + } + + public static void print(int[][] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.println(Arrays.toString(arr[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(optimize(3, 10)); + } + +} diff --git a/java-programs/DynamicProgramming/equalSumSubset.java b/java-programs/DynamicProgramming/equalSumSubset.java new file mode 100644 index 0000000..f9f0e1f --- /dev/null +++ b/java-programs/DynamicProgramming/equalSumSubset.java @@ -0,0 +1,58 @@ +package DynamicProgramming; + +import java.util.*; + +public class equalSumSubset { + + public static void generateAllSubsets(int[] arr, int index, ArrayList list, int n) { + + if (index == n) { + System.out.println(list); + return; + } + + list.add(arr[index]); + generateAllSubsets(arr, index + 1, list, n); + list.remove(list.size() - 1); + generateAllSubsets(arr, index + 1, list, n); + } + + public static void checkSum(int[] arr, int index, int n, int sum) { + if (index == n) { + System.out.println(sum); + return; + } + + checkSum(arr, index + 1, n, sum + arr[index]); + checkSum(arr, index + 1, n, sum); + } + + public static int dpApproach(int[] arr, int target, int n) { + int[][] dp = new int[n + 1][target + 1]; + dp[0][0] = 1; + + for(int i = 1; i <= n; i++) { + for(int j = 0; j <= target; j++) { + if(j == 0) { + dp[i][j] = 1; + }else { + if(j >= arr[i - 1]) { + dp[i][j] = (dp[i][j - arr[i - 1]] | dp[i - 1][j]); + }else { + dp[i][j] = dp[i - 1][j]; + } + } + } + } + + return dp[n][target]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] arr = { 1, 2, 3, 4 }; + generateAllSubsets(arr, 0, new ArrayList(), arr.length); + checkSum(arr, 0, arr.length, 0); + } + +} diff --git a/java-programs/DynamicProgramming/findPathExistence.java b/java-programs/DynamicProgramming/findPathExistence.java new file mode 100644 index 0000000..f2dcb6f --- /dev/null +++ b/java-programs/DynamicProgramming/findPathExistence.java @@ -0,0 +1,60 @@ +package DynamicProgramming; + +public class findPathExistence { + + public static boolean isPossible(int[][] grid, boolean[][] dp, int i, int j, int n) { + if (grid[i][j] == 2) + return true; + + if (i - 1 >= 0 && grid[i - 1][j] != 0 && !dp[i - 1][j]) { + dp[i - 1][j] = true; + if (isPossible(grid, dp, i - 1, j, n)) { + return true; + } + } + + if (i + 1 < n && grid[i + 1][j] != 0 && !dp[i + 1][j]) { + dp[i + 1][j] = true; + if (isPossible(grid, dp, i + 1, j, n)) { + return true; + } + } + + if (j + 1 < n && grid[i][j + 1] != 0 && !dp[i][j + 1]) { + dp[i][j + 1] = true; + if (isPossible(grid, dp, i, j + 1, n)) { + return true; + } + } + + if (j - 1 >= 0 && grid[i][j - 1] != 0 && !dp[i][j - 1]) { + dp[i][j - 1] = true; + if (isPossible(grid, dp, i, j - 1, n)) { + return true; + } + } + + return false; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[][] grid = { { 3, 0, 3, 0, 0 }, { 3, 0, 0, 0, 3 }, { 3, 3, 3, 3, 3 }, { 0, 2, 3, 0, 0 }, + { 3, 0, 0, 1, 3 } }; + int n = grid.length; + boolean flag = false; + + boolean[][] dp = new boolean[grid.length][grid.length]; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (grid[i][j] == 1) { + dp[i][j] = true; + flag = isPossible(grid, dp, i, j, n); + } + } + } + + System.out.println(flag); + } + +} diff --git a/java-programs/DynamicProgramming/getMinimumSquares.java b/java-programs/DynamicProgramming/getMinimumSquares.java new file mode 100644 index 0000000..0cb61b7 --- /dev/null +++ b/java-programs/DynamicProgramming/getMinimumSquares.java @@ -0,0 +1,41 @@ +package DynamicProgramming; + +public class getMinimumSquares { + +// public static int getMinSqr(int n) { +// if (n == 0) +// return 0; +// +// int res = Integer.MAX_VALUE; +// +// for (int i = 1; i * i <= n; i++) { +// res = Math.min(res, getMinSqr(n - i * i)); +// } +// +// return res + 1; +// } + + public static int dpGetMinSqr(int n) { + int[] dp = new int[n + 1]; + dp[0] = 0; + dp[1] = 1; // 1 * 1 + dp[2] = 2; // 1 * 1 + 1 * 1 + dp[3] = 3; // 1 * 1 + 1 * 1 + 1 * 1 + + for (int i = 4; i <= n; i++) { + dp[i] = i; + for (int j = 1; j * j <= i; j++) { + dp[i] = Math.min(dp[i], 1 + dp[i - j * j]); + } + } + + return dp[n]; + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(dpGetMinSqr(1365)); + } + +} diff --git a/java-programs/DynamicProgramming/integerPartition.java b/java-programs/DynamicProgramming/integerPartition.java new file mode 100644 index 0000000..61bc249 --- /dev/null +++ b/java-programs/DynamicProgramming/integerPartition.java @@ -0,0 +1,97 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class integerPartition { + + public static int pofN(int n) { + // number of ways n can be represented as a sum of 1 - n - 1 + int[][] dp = new int[n][n + 1]; + dp[0][0] = 1; + for (int i = 1; i < n; i++) { + for (int j = 0; j <= n; j++) { + if (i == 1 || j == 1) { + dp[i][j] = 1; + } else if (j == 0) { + dp[i][j] = 1; + } else { + if (i <= j) { + dp[i][j] = dp[i - 1][j] + dp[i][j - i]; + } else { + dp[i][j] = dp[i - 1][j]; + } + } + } + } + + for (int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + + return dp[n - 1][n]; + } + + public static long countStairs(int m) { + long[][] dp = new long[3][m + 1]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j <= m; j++) { + if (j == 0) { + dp[i][j] = 1; + } else if (i == 0) { + dp[i][j] = 0; + } else if (i == 1) { + dp[i][j] = 1; + } else { + if (i > j) { + dp[i][j] = dp[i - 1][j]; + } else { + dp[i][j] = dp[i - 1][j] + dp[i][j - i]; + } + } + } + } + + for (int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + + return dp[2][m]; + } + + public static int reachAGivenScore(int n) { + int[][] dp = new int[4][n + 1]; + int[] val = { 3, 5, 10 }; + + for (int i = 0; i < 3; i++) { + int x = val[i]; + for (int j = 0; j <= n; j++) { + if(j == 0) { + dp[i][j] = 1; + }else if(i == 0) { + dp[i][j] = 0; + }else { + if(x > j) { + dp[i][j] = dp[i - 1][j]; + }else { + System.out.println(x); + dp[i][j] = dp[i - 1][j] + dp[i][j - x]; + } + } + } + } + + for (int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + + return dp[3][n]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub +// System.out.println(pofN(4)); +// System.out.println(countStairs(1)); + System.out.println(reachAGivenScore(8)); + } + +} diff --git a/java-programs/DynamicProgramming/knapsack01.java b/java-programs/DynamicProgramming/knapsack01.java new file mode 100644 index 0000000..b5033f3 --- /dev/null +++ b/java-programs/DynamicProgramming/knapsack01.java @@ -0,0 +1,32 @@ +package DynamicProgramming; + +public class knapsack01 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] values = { 10, 40, 30, 50 }; + int[] weight = { 5, 4, 6, 3 }; + int W = 10; + + int[] values2 = { 60, 100, 120 }; + int[] weight2 = { 10, 20, 30 }; + int w2 = 50; + + System.out.println(getMaxValue(values, weight, 0, W, 0)); + System.out.println(getMaxValue(values2, weight2, 0, w2, 0)); + } + + public static int getMaxValue(int[] values, int[] weight, int index, int w, int val) { + // TODO Auto-generated method stub + if (index == values.length) + return val; + + if (w - weight[index] >= 0) { + return Math.max(getMaxValue(values, weight, index + 1, w - weight[index], val + values[index]), + getMaxValue(values, weight, index + 1, w, val)); + } else { + return getMaxValue(values, weight, index + 1, w, val); + } + } + +} diff --git a/java-programs/DynamicProgramming/largestNumberWithKSwaps.java b/java-programs/DynamicProgramming/largestNumberWithKSwaps.java new file mode 100644 index 0000000..3f17124 --- /dev/null +++ b/java-programs/DynamicProgramming/largestNumberWithKSwaps.java @@ -0,0 +1,36 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class largestNumberWithKSwaps { + + public static void Kswaps(char[] arr, int swaps) { + if (swaps == 0) { + System.out.println(Arrays.toString(arr)); + return; + } + + for(int i = 0; i < arr.length; i++) { + for(int j = i + 1; j < arr.length; j++) { + if(arr[j] > arr[i]) { + swap(arr, i, j); + Kswaps(arr, swaps - 1); + swap(arr, i, j); + } + } + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + char[] arr = { '1', '2', '3', '4', '5', '6', '7' }; + Kswaps(arr, 4); + } + + public static void swap(char[] arr, int i, int j) { + char temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + +} diff --git a/java-programs/DynamicProgramming/lcsReeatedKtimes.java b/java-programs/DynamicProgramming/lcsReeatedKtimes.java new file mode 100644 index 0000000..1b89184 --- /dev/null +++ b/java-programs/DynamicProgramming/lcsReeatedKtimes.java @@ -0,0 +1,56 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class lcsReeatedKtimes { + + public static String commonLCS(String txt1, String txt2) { + String result = ""; + int n = txt1.length(); + int m = txt2.length(); + + int[][] dp = new int[n + 1][m + 1]; + for (int i = 0; i < n + 1; i++) { + for (int j = 0; j < m + 1; j++) { + if (i == 0 || j == 0) { + dp[i][j] = 0; + } else { + if (txt1.charAt(i - 1) == txt2.charAt(j - 1) && i != j) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + } + + if(dp[n][m] == 0) { + return result; + } + + int i = n; + int j = m; + + while(i > 0 && j > 0) { + if(dp[i][j] > dp[i - 1][j] && dp[i][j] > dp[i][j - 1]) { + result = txt1.charAt(i - 1) + result; + i--; + j--; + }else { + if(dp[i][j] == dp[i][j - 1]) { + j--; + }else { + i--; + } + } + } + + return result; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(commonLCS("letsleetcode", "letsleetcode")); + } + +} diff --git a/java-programs/DynamicProgramming/longestPallindromicSubsequence.java b/java-programs/DynamicProgramming/longestPallindromicSubsequence.java new file mode 100644 index 0000000..fb08be9 --- /dev/null +++ b/java-programs/DynamicProgramming/longestPallindromicSubsequence.java @@ -0,0 +1,49 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class longestPallindromicSubsequence { + + public static int longestPalinSubseq(String S) { + // code here + int n = S.length(); + int[][] dp = new int[n][n]; + + + for (int gap = 0; gap < n; gap++) { + for (int i = 0, j = gap; j < n; i++, j++) { + if (i == j) { + dp[i][j] = 1; + } else if (j - i == 1) { + if (S.charAt(i) == S.charAt(j)) { + dp[i][j] = 2; + } else { + dp[i][j] = 1; + } + } else { + if (S.charAt(i) == S.charAt(j)) { + dp[i][j] = 2 + dp[i + 1][j - 1]; + } else { + dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]); + } + } + } + } + + print(dp); + + return dp[0][n - 1]; + } + + public static void print(int[][] arr) { + for (int i = 0; i < arr.length; i++) { + System.out.println(Arrays.toString(arr[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(longestPalinSubseq("geekssgeek")); + } + +} diff --git a/java-programs/DynamicProgramming/longestValidParanthesis.java b/java-programs/DynamicProgramming/longestValidParanthesis.java new file mode 100644 index 0000000..c8cc713 --- /dev/null +++ b/java-programs/DynamicProgramming/longestValidParanthesis.java @@ -0,0 +1,40 @@ +package DynamicProgramming; + +import java.util.Stack; + +public class longestValidParanthesis { + + public static int validParanthesis(String S) { + + Stack stc = new Stack<>(); + Stack st = new Stack<>(); + st.push(-1); + int max = 0; + + for(int i = 0; i < S.length(); i++) { + if(S.charAt(i) == '(') { + stc.push('('); + st.push(i); + }else { + if(!stc.isEmpty()) { + stc.pop(); + st.pop(); + max = Math.max(max, i - st.peek()); + }else { + st.push(i); + } + } + + System.out.println(stc); + System.out.println(st); + } + + return max; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(validParanthesis("))()(()")); + } + +} diff --git a/java-programs/DynamicProgramming/lpsString.java b/java-programs/DynamicProgramming/lpsString.java new file mode 100644 index 0000000..1164634 --- /dev/null +++ b/java-programs/DynamicProgramming/lpsString.java @@ -0,0 +1,52 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class lpsString { + + public static String longestPalindrome(String S){ + // code here + int n = S.length(); + if(n == 0 || n == 1){ + return S; + } + + int[][] dp = new int[n][n]; + String result = S.charAt(0)+""; + for(int diagonal = 0; diagonal < n; diagonal++){ + for(int i = 0, j = diagonal; j < n; j++, i++){ + if(i == j){ + dp[i][j] = 1; + }else if(j - i == 1){ + if(S.charAt(i) == S.charAt(j)){ + dp[i][j] = 1; + result = S.substring(i, j + 1); + } + }else{ + if(S.charAt(i) == S.charAt(j) && dp[i + 1][j - 1] == 1){ + dp[i][j] = 1; + if(j - i + 1 > result.length()){ + result = S.substring(i, j + 1); + } + } + } + } + } + + print(dp); + + return result; + } + + public static void print(int[][] arr) { + for (int i = 0; i < arr.length; i++) { + System.out.println(Arrays.toString(arr[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(longestPalindrome("aaaabbaa")); + } + +} diff --git a/java-programs/DynamicProgramming/maxPath.java b/java-programs/DynamicProgramming/maxPath.java new file mode 100644 index 0000000..fe6647e --- /dev/null +++ b/java-programs/DynamicProgramming/maxPath.java @@ -0,0 +1,53 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class maxPath { + + public static int maxPathSum(int[][] matrix, int i, int j, int n, int[][] dp) { + if (dp[i][j] == 0) { + + if (i == n - 1) { + return matrix[i][j]; + } + + int num1 = 0; + int num2 = 0; + int num3 = 0; + if (i + 1 < n) { + num1 = maxPathSum(matrix, i + 1, j, n, dp); + } + + if (i + 1 < n && j - 1 > -1) { + num2 = maxPathSum(matrix, i + 1, j - 1, n, dp); + } + + if (i + 1 < n && j + 1 < n) { + num3 = maxPathSum(matrix, i + 1, j + 1, n, dp); + } + + dp[i][j] = matrix[i][j] + Math.max(num1, Math.max(num2, num3)); + } + + return dp[i][j]; + } + + public static void print(int[][] dp) { + for(int i = 0; i < dp.length; i++) { + System.out.println(Arrays.toString(dp[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[][] matrix = { {2} }; + int[][] dp = new int[matrix.length][matrix.length]; + int ans = Integer.MIN_VALUE; + for (int i = 0; i < matrix.length; i++) { + ans = Math.max(ans, maxPathSum(matrix, 0, i, matrix.length, dp)); + } + + print(dp); + } + +} diff --git a/java-programs/DynamicProgramming/maxSumByRemovingOneEle.java b/java-programs/DynamicProgramming/maxSumByRemovingOneEle.java new file mode 100644 index 0000000..02ae8e2 --- /dev/null +++ b/java-programs/DynamicProgramming/maxSumByRemovingOneEle.java @@ -0,0 +1,50 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class maxSumByRemovingOneEle { + + public static int maxSum(int[] arr) { + int n = arr.length; + int[] arrl = new int[n]; + int[] arrr = new int[n]; + arrl[0] = arr[0]; + arrr[n - 1] = arr[n - 1]; + int suml = arr[0]; + int maxS = arr[0]; + int sumr = arr[n - 1]; + + for (int i = 1; i < n; i++) { + suml = Math.max(suml + arr[i], arr[i]); + sumr = Math.max(sumr + arr[n - 1 - i], arr[n - 1 - i]); + maxS = Math.max(maxS, suml); + arrl[i] = suml; + arrr[n - 1 - i] = sumr; + } + + System.out.println(Arrays.toString(arr)); + System.out.println(Arrays.toString(arrl)); + System.out.println(Arrays.toString(arrr)); + + int ans = maxS; + + for (int i = 0; i < n; i++) { + if (i == 0) { + ans = Math.max(ans, arrr[1]); + } else if (i == n - 1) { + ans = Math.max(ans, arrl[n - 2]); + } else { + ans = Math.max(ans, arrl[i - 1] + arrr[i + 1]); + } + } + + return ans; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] arr = { -2, -1, -1, 4, 5 }; + System.out.println(maxSum(arr)); + } + +} diff --git a/java-programs/DynamicProgramming/maximumCut.java b/java-programs/DynamicProgramming/maximumCut.java new file mode 100644 index 0000000..1804ffb --- /dev/null +++ b/java-programs/DynamicProgramming/maximumCut.java @@ -0,0 +1,106 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class maximumCut { + + public static int maximizeCut(int rodLength, int x, int y, int z) { + + if (rodLength == 0) + return 0; + + if (rodLength < 0) + return -1; + + int res; + + res = Math.max(maximizeCut(rodLength - x, x, y, z), + Math.max(maximizeCut(rodLength - y, x, y, z), maximizeCut(rodLength - z, x, y, z))); + + if (res < 0) + return -1; + else + return res + 1; + } + + public static int dpApproach(int rodLength, int a, int b, int c) { + int[] dp = new int[rodLength + 1]; + Arrays.fill(dp, -1); + + dp[0] = 0; + + for (int i = 1; i <= rodLength; i++) { + if (a <= i && dp[i - a] != -1) { + dp[i] = 1 + dp[i - a]; + } + + if (b <= i && dp[i - b] != -1) { + dp[i] = Math.max(1 + dp[i - b], dp[i]); + } + + if (c <= i && dp[i - c] != -1) { + dp[i] = Math.max(1 + dp[i - c], dp[i]); + } + } + + if(dp[rodLength] == -1) return 0; + return dp[rodLength]; + } + + public static int twApproach(int rodLength, int a, int b, int c) { + int[] dp = new int[rodLength + 1]; + Arrays.fill(dp, -1); + + dp[0] = 0; + + for (int i = 1; i <= rodLength; i++) { + int res = 0; + if (a <= i && dp[i - a] != -1) { + res += dp[i - a]; + } + + if (b <= i && dp[i - b] != -1) { + res += dp[i - b]; + } + + if (c <= i && dp[i - c] != -1) { + res += dp[i - c]; + } + + if(res != 0) dp[i] = res; + } + + if(dp[rodLength] == -1) return 0; + return dp[rodLength]; + } + + static long countWays(int n) + { + // add your code here + if(n == 1) return 1; + if(n == 2) return 2; + + long[] dp = new long[n + 1]; + dp[0] = 1; + dp[1] = 1; + dp[2] = 2; + + for(int i = 3; i <= n; i++){ + dp[i] = (dp[i - 1] + dp[i - 2] + dp[i - 3]) % 1000000007; + } + + return dp[n]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub +// System.out.println(maximizeCut(4, 2, 1, 1)); +// System.out.println(dpApproach(4, 2, 1, 1)); +// System.out.println(dpApproach(5, 5, 3, 2)); + System.out.println(dpApproach(20, 3, 5, 10)); + System.out.println(twApproach(20, 3, 5, 10)); + +// System.out.println(countWays(3)); + } + +} diff --git a/java-programs/DynamicProgramming/minimumCostPath.java b/java-programs/DynamicProgramming/minimumCostPath.java new file mode 100644 index 0000000..f2cff45 --- /dev/null +++ b/java-programs/DynamicProgramming/minimumCostPath.java @@ -0,0 +1,42 @@ +package DynamicProgramming; + +public class minimumCostPath { + +// public static int minimumPath(int[][] matrix, int i, int j, int up, int down, int left, int right) { +// +// if (i == down - 1 && j == right - 1) { +// return matrix[i][j]; +// } +// +// int num1 = Integer.MAX_VALUE; +// int num2 = Integer.MAX_VALUE; +// int num3 = Integer.MAX_VALUE; +// int num4 = Integer.MAX_VALUE; +// +// if (j - 1 > left) { +// num1 = minimumPath(matrix, i, j - 1, up, down, left, j - 1); +// } +// +// if (j + 1 < right) { +// num2 = minimumPath(matrix, i, j + 1, up, down, j + 1, right); +// } +// +// if (i - 1 > up) { +// num3 = minimumPath(matrix, i - 1, j, up, i - 1, left, right); +// } +// +// if (i + 1 < down) { +// num4 = minimumPath(matrix, i + 1, j, i + 1, down, left, right); +// } +// +// return matrix[i][j] + Math.min(Math.min(num1, num2), Math.max(num3, num4)); +// } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[][] grid = { { 9, 4, 9, 9 }, { 6, 7, 6, 4 }, { 8, 3, 3, 7 }, { 7, 4, 9, 10 } }; + int n = grid.length; +// System.out.println(minimumPath(grid, 0, 0, 0, n, 0, n)); + } + +} diff --git a/java-programs/DynamicProgramming/n_stairs.java b/java-programs/DynamicProgramming/n_stairs.java new file mode 100644 index 0000000..edf444a --- /dev/null +++ b/java-programs/DynamicProgramming/n_stairs.java @@ -0,0 +1,38 @@ +package DynamicProgramming; + +import java.util.*; + +public class n_stairs { + + public static int totalWays(int n) { + int[][] dp = new int[3][n + 1]; + for (int i = 0; i < 3; i++) { + for (int j = 0; j <= n; j++) { + if (j == 0 || i == 1) { + dp[i][j] = 1; + } else if (i == 0) { + dp[i][j] = 0; + } else if (j < i) { + dp[i][j] = dp[i][j - 1]; + } else { + dp[i][j] = dp[i][j - 1] + dp[i][j - i]; + } + } + } + + print(dp); + return dp[2][n]; + } + + public static void print(int[][] arr) { + for (int i = 0; i < arr.length; i++) { + System.out.println(Arrays.toString(arr[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + totalWays(4); + } + +} diff --git a/java-programs/DynamicProgramming/ncr.java b/java-programs/DynamicProgramming/ncr.java new file mode 100644 index 0000000..fb4863d --- /dev/null +++ b/java-programs/DynamicProgramming/ncr.java @@ -0,0 +1,61 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class ncr { + + public static int NcR(int n, int r) { + if (n == 1 || r == 0 || n == r) { + return 1; + } + + if (r == 1) { + return n; + } + + return NcR(n - 1, r) + NcR(n - 1, r - 1); + } + + public static int dpApproach(int n, int r) { + + if(r > n) return -1; + + if(n == r) return 1; + + if(r == 0) return n; + + int[][] dp = new int[n + 1][r + 1]; + + for (int i = 1; i <= n; i++) { + for (int j = 0; j <= r; j++) { + if (i >= j) { + if (j == 0) { + dp[i][j] = i; + } else if (i == j) { + dp[i][j] = 1; + } else if (j == 1) { + dp[i][j] = i; + } else { + dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - 1]) % 1000000007; + } + } + } + } + +// print(dp); + return dp[n][r]; + } + + public static void print(int[][] arr) { + for(int i = 0; i < arr.length; i++) { + System.out.println(Arrays.toString(arr[i])); + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub +// System.out.println(NcR(84, 56)); + System.out.println(dpApproach(84, 56)); + } + +} diff --git a/java-programs/DynamicProgramming/numberOfCoins.java b/java-programs/DynamicProgramming/numberOfCoins.java new file mode 100644 index 0000000..4d023ce --- /dev/null +++ b/java-programs/DynamicProgramming/numberOfCoins.java @@ -0,0 +1,43 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class numberOfCoins { + + public static int mincoins(int[] coins, int m, int v) { + int[] dp = new int[v + 1]; + dp[0] = 0; + + for (int i = 1; i <= v; i++) { + int min = Integer.MAX_VALUE; + for (int j = 0; j < m; j++) { + int value = i; + int count = 1; + if (coins[j] <= i) { + while (value > 0) { + if (value - coins[j] >= 0 && dp[value - coins[j]] != Integer.MAX_VALUE) { + min = Math.min(min, count + dp[value - coins[j]]); + } + + value = value - coins[j]; + count++; + } + } + } + + dp[i] = min; + } + + return (dp[v] == Integer.MAX_VALUE) ? -1 : dp[v]; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int v = 26; + int m = 5; + int coins[] = { 3, 7, 6, 11, 8 }; + + System.out.println(mincoins(coins, m, v)); + } + +} diff --git a/java-programs/DynamicProgramming/numberOfUniqueWays.java b/java-programs/DynamicProgramming/numberOfUniqueWays.java new file mode 100644 index 0000000..a7756ec --- /dev/null +++ b/java-programs/DynamicProgramming/numberOfUniqueWays.java @@ -0,0 +1,25 @@ +package DynamicProgramming; + +public class numberOfUniqueWays { + + public static int ways(int x, int y) { + + if(x > 0 && y > 0) + return ways(x - 1, y) + ways(x, y - 1); + else if(y > 0) + return ways(x, y - 1); + else if(x > 0) + return ways(x - 1, y); + else if(x == 0 || y == 0) + return 1; + else return 1; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int A = 3; + int B = 4; + System.out.println(ways(A - 1, B - 1)); + } + +} diff --git a/java-programs/DynamicProgramming/optimalGameStartegy.java b/java-programs/DynamicProgramming/optimalGameStartegy.java new file mode 100644 index 0000000..d8d8c9e --- /dev/null +++ b/java-programs/DynamicProgramming/optimalGameStartegy.java @@ -0,0 +1,27 @@ +package DynamicProgramming; + +public class optimalGameStartegy { + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] arr = { 2,6,3 }; + System.out.println(getMax(arr, 0, arr.length - 1)); + +// int[] arr2 = { 2, 3, 15, 7 }; +// System.out.println(getMax(arr2, 0, arr2.length)); + } + + public static int getMax(int[] arr, int i, int j) { + // TODO Auto-generated method stub + if (j - i == 1) { + return Math.max(arr[i], arr[j]); + } + + if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)) { + return Math.min(getMax(arr, i + 1, j), getMax(arr, i, j - 1)); + } else { + return Math.max(arr[i] + getMax(arr, i + 1, j), arr[j] + getMax(arr, i, j - 1)); + } + } + +} diff --git a/java-programs/DynamicProgramming/pallindromicPartition.java b/java-programs/DynamicProgramming/pallindromicPartition.java new file mode 100644 index 0000000..2c17d23 --- /dev/null +++ b/java-programs/DynamicProgramming/pallindromicPartition.java @@ -0,0 +1,60 @@ +package DynamicProgramming; + +import java.util.*; + +public class pallindromicPartition { + + public static int pp(String str) { + // code here + int n = str.length(); + int[][] dp = new int[n][n]; + + for (int diagonal = 0; diagonal < n; diagonal++) { + for (int i = 0, j = diagonal; j < n; i++, j++) { + if (i == j) { + dp[i][j] = 0; + } else if (j - i == 1) { + if (str.charAt(i) == str.charAt(j)) { + dp[i][j] = 0; + } else { + dp[i][j] = 1; + } + } else { + if (isPallindrome(str.substring(i, j + 1))) { + dp[i][j] = 0; + } else { + dp[i][j] = Integer.MAX_VALUE; + for (int k = i; k < j; k++) { + dp[i][j] = Math.min(dp[i][j], 1 + dp[i][k] + dp[k + 1][j]); +// System.out.println(dp[i][j]); + } + } + } + } + } + + return dp[0][n - 1]; + } + + static boolean isPallindrome(String s) { + int start = 0; + int end = s.length() - 1; + + while (start < end) { + if (s.charAt(start) != s.charAt(end)) { + return false; + } + + start++; + end--; + } + + return true; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + System.out.println(pp("geek")); + } + +} diff --git a/java-programs/DynamicProgramming/playerWithMaxScore.java b/java-programs/DynamicProgramming/playerWithMaxScore.java new file mode 100644 index 0000000..2c1429e --- /dev/null +++ b/java-programs/DynamicProgramming/playerWithMaxScore.java @@ -0,0 +1,54 @@ +package DynamicProgramming; + +import java.util.Arrays; + +public class playerWithMaxScore { + + public static int recursionMethod(int[] arr, int start, int end, boolean turn) { + + if (start == end) { + return arr[start]; + } else if (end - start == 1) { + if (turn) { + return Math.max(arr[start], arr[end]); + } else { + return Math.min(arr[start], arr[end]); + } + } + + if (turn) { + return Math.max(arr[start] + recursionMethod(arr, start + 1, end, false), + arr[end] + recursionMethod(arr, start, end - 1, false)); + } else { + return Math.min(recursionMethod(arr, start + 1, end, true), recursionMethod(arr, start, end - 1, true)); + } + } + + public static int dp(int[] arr, int len) { + int[][] dp = new int[len][len]; + for (int diagonal = 0; diagonal < len; diagonal = diagonal + 2) { + for (int i = 0, j = diagonal; j < len; i++, j++) { + if (i == j) { + dp[i][j] = arr[i]; + } else { + dp[i][j] = Math.max(arr[i] + Math.min(dp[i + 1][j - 1], dp[i + 2][j]), + arr[j] + Math.min(dp[i + 1][j - 1], dp[i][j - 2])); + } + } + } + + if(len % 2 == 0) { + return dp[0][len - 2]; + }else { + return dp[0][len - 1]; + } + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + int[] arr = { 20, 5, 4, 6, 8, 3 }; + System.out.println(recursionMethod(arr, 0, arr.length - 1, true)); + dp(arr, arr.length); + } + +} diff --git a/java-programs/DynamicProgramming/stepsByKnight.java b/java-programs/DynamicProgramming/stepsByKnight.java new file mode 100644 index 0000000..3baa0b4 --- /dev/null +++ b/java-programs/DynamicProgramming/stepsByKnight.java @@ -0,0 +1,140 @@ +package DynamicProgramming; + +import java.util.*; + +public class stepsByKnight { + + public static int minSteps(Pair kp, Pair tp, int n, boolean[][] dp) { + int count = 0; + Queue q = new LinkedList<>(); + if (equals(kp, tp)) + return count; + q.add(kp); + + while (!q.isEmpty()) { + int size = q.size(); + count++; + for (int i = 0; i < size; i++) { + Pair p = q.poll(); + int x = p.x; + int y = p.y; + + Pair newp = new Pair(x + 1, y - 2); + if (isValid(newp, n) && !dp[x + 1][y - 2]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x + 1][y - 2] = true; + } + } + + newp = new Pair(x + 1, y + 2); + if (isValid(newp, n) && !dp[x + 1][y + 2]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x + 1][y + 2] = true; + } + } + newp = new Pair(x - 1, y - 2); + if (isValid(newp, n) && !dp[x - 1][y - 2]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x - 1][y - 2] = true; + } + } + + newp = new Pair(x - 1, y + 2); + if (isValid(newp, n) && !dp[x - 1][y + 2]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x - 1][y + 2] = true; + } + } + + newp = new Pair(x - 2, y + 1); + if (isValid(newp, n) && !dp[x - 2][y + 1]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x - 2][y + 1] = true; + } + } + + newp = new Pair(x - 2, y - 1); + if (isValid(newp, n) && !dp[x - 2][y - 1]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x - 2][y - 1] = true; + } + } + + newp = new Pair(x + 2, y - 1); + if (isValid(newp, n) && !dp[x + 2][y - 1]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x + 2][y - 1] = true; + } + } + + newp = new Pair(x + 2, y + 1); + if (isValid(newp, n) && !dp[x + 2][y + 1]) { + if (equals(newp, tp)) { + return count; + } else { + q.add(newp); + dp[x + 2][y + 1] = true; + } + } + } + } + + return -1; + } + + public static boolean equals(Pair p1, Pair p2) { + if (p1.x == p2.x && p1.y == p2.y) + return true; + + return false; + } + + public static boolean isValid(Pair p, int n) { + if (p.x >= 0 && p.x < n && p.y >= 0 && p.y < n) { + return true; + } + + return false; + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + Pair kp = new Pair(3, 4); + Pair tp = new Pair(0, 0); + boolean[][] dp = new boolean[6][6]; + dp[3][4] = true; + System.out.println(minSteps(kp, tp, 6, dp)); + } + +} + +class Pair { + int x; + int y; + + Pair(int x, int y) { + this.x = x; + this.y = y; + } +} diff --git a/java8-questions.md b/java8-questions.md deleted file mode 100644 index 4fb84dc..0000000 --- a/java8-questions.md +++ /dev/null @@ -1,961 +0,0 @@ -# Java 8 Interview Questions and Answers - -## Q. What are the important features of Java 8 release? - -* Interface methods by default; -* Lambda expressions; -* Functional interfaces; -* References to methods and constructors; -* Repeatable annotations -* Annotations on data types; -* Reflection for method parameters; -* Stream API for working with collections; -* Parallel sorting of arrays; -* New API for working with dates and times; -* New JavaScript Nashorn Engine ; -* Added several new classes for thread safe operation; -* Added a new API for `Calendar`and `Locale`; -* Added support for Unicode 6.2.0 ; -* Added a standard class for working with Base64 ; -* Added support for unsigned arithmetic; -* Improved constructor `java.lang.String(byte[], *)` and method performance `java.lang.String.getBytes()`; -* A new implementation `AccessController.doPrivileged` that allows you to set a subset of privileges without having to check all * other access levels; -* Password-based algorithms have become more robust; -* Added support for SSL / TLS Server Name Indication (NSI) in JSSE Server ; -* Improved keystore (KeyStore); -* Added SHA-224 algorithm; -* Removed JDBC Bridge - ODBC; -* PermGen is removed , the method for storing meta-data of classes is changed; -* Ability to create profiles for the Java SE platform, which include not the entire platform, but some part of it; -* Tools - * Added utility `jjs` for using JavaScript Nashorn; - * The command `java` can run JavaFX applications; - * Added utility `jdeps` for analyzing .class files. - - - -## Q. Can you declare an interface method static? - -Java 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. - - - -## Q. What is a lambda? - - What is the structure and features of using a lambda expression? -A lambda is a set of instructions that can be separated into a separate variable and then repeatedly called in various places of the program. - -The basis of the lambda expression is the _lambda operator_ , which represents the arrow `->`. 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. - -The 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. - -```java -interface Operationable { - int calculate ( int x , int y ); -} - -public static void main ( String [] args) { - Operationable operation = (x, y) - > x + y; - int result = operation.calculate ( 10 , 20 ); - System.out.println (result); // 30 -} -``` - -In fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java. - -* _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. - -* _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method: - -```javascript -operation = ( int x, int y) - > x + y; -// When writing the lambda expression itself, the parameter type is allowed not to be specified: -(x, y) - > x + y; -// If the method does not accept any parameters, then empty brackets are written, for example: -() - > 30 + 20 ; -// If the method accepts only one parameter, then the brackets can be omitted: -n - > n * n; -``` -* Trailing lambda expressions are not required to return any value. -```java -interface Printable { - void print( String s ); -} - -public static void main ( String [] args) { - Printable printer = s - > System.out.println(s); - printer.print("Hello, world"); -} - -// _ 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 ' : - - -Operationable operation = ( int x, int y) - > { - if (y == 0 ) { - return 0 ; - } - else { - return x / y; - } -}; -``` -* Passing a lambda expression as a method parameter -```java -interface Condition { - boolean isAppropriate ( int n ); -} - -private static int sum ( int [] numbers, Condition condition) { - int result = 0 ; - for ( int i : numbers) { - if (condition.isAppropriate(i)) { - result + = i; - } - } - return result; -} - -public static void main ( String [] args) { - System.out.println(sum ( new int [] { 0 , 1 , 0 , 3 , 0 , 5 , 0 , 7 , 0 , 9 }, (n) - > n ! = 0 )); -} -``` - - - -## Q. What variables do lambda expressions have access to? - -Access to external scope variables from a lambda expression is very similar to access from anonymous objects. - -* immutable ( effectively final - not necessarily marked as final) local variables; -* class fields -* static variables. - -The default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression. - - - -## Q. How to sort a list of strings using a lambda expression? - -```java -public static List < String > sort ( List < String > list) { - Collections.sort(list, (a, b) -> a.compareTo(b)); - return list; -} -``` - - - -## Q. What is a method reference? - -If 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. -```java -private interface Measurable { - public int length ( String string ); -} - -public static void main ( String [] args) { - Measurable a = String::length; - System.out.println(a.length("abc")); -} -``` - -Method 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. - - - -## Q. What types of method references do you know? - -* on the static method; -* per instance method; -* to the constructor. - - - -## Q. Explain the expression `System.out::println`? - -The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. - - - -## Q. What is a Functional Interface? - -A **functional interface** is an interface that defines only one abstract method. - -To 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. - -An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. - - - -## Q. What is StringJoiner? - -The 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: -```java -StringJoiner joiner = new StringJoiner ( " . " , " Prefix- " , " -suffix " ); -for ( String s : " Hello the brave world " . split ( " " )) { - , joiner, . add (s); -} -System.out.println(joiner); // prefix-Hello.the.brave.world-suffix -``` - - - -## Q. What are `default`interface methods? - -Java 8 allows you to add non-abstract method implementations to an interface using the keyword default: -```java -interface Example { - int process ( int a ); - default void show () { - System.out.println("default show ()"); - } -} -``` -* 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. -* 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. -* The default method cannot override the class method `java.lang.Object`. -* They help implement interfaces without fear of disrupting other classes. -* Avoid creating utility classes, since all the necessary methods can be represented in the interfaces themselves. -* They give classes the freedom to choose the method to be redefined. -* One of the main reasons for introducing default methods is the ability of collections in Java 8 to use lambda expressions. - - - -## Q. How to call `default` interface method in a class that implements this interface? - -Using the keyword superalong with the interface name: -```java -interface Paper { - default void show () { - System.out.println(" default show ()"); - } -} - -class License implements Paper { - public void show () { - Paper.super.show(); - } -} -``` - - - -## Q. What is `static` interface method? - -Static interface methods are similar to default methods, except that there is no way to override them in classes that implement the interface. - -* Static methods in the interface are part of the interface without the ability to use them for objects of the implementation class -* Class methods `java.lang.Object`cannot be overridden as static -* Static methods in the interface are used to provide helper methods, for example, checking for null, sorting collections, etc. - - - -## Q. How to call `static` interface method? - -Using the interface name: -```java -interface Paper { - static void show () { - System.out.println( " static show () " ); - } -} - -class License { - public void showPaper () { - Paper.show (); - } -} -``` - - - -## Q. What is Optional -An 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`: -```java -Optional < String > optional = Optional . of ( " hello " ); - -optional.isPresent(); // true -optional.ifPresent(s -> System.out.println(s . length ())); // 5 -optional.get(); // "hello" -optional.orElse( " ops ... " ); // "hello" -``` - - - -## Q. What is Stream? - -An interface `java.util.Stream` is a sequence of elements on which various operations can be performed. - -Operations 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. - -A 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()`). - -Streams are created based on sources of some, for example, classes from `java.util.Collection`. - -Associative arrays (maps), for example `HashMap`, are not supported. - -Operations on streams can be performed both sequentially and in parallel. - -Streams cannot be reused. As soon as some final operation has been called, the flow is closed. - -In 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: - -* use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`; -* support additional end operations `sum()`, `average()`, `mapToObj()`. - - - -## Q. What are the ways to create a stream? - -* Using collection: -```java -Stream < String > fromCollection = Arrays.asList ( " x " , " y " , " z " ).stream (); -``` -* Using set of values: -```java -Stream < String > fromValues = Stream.of( " x " , " y " , " z " ); -``` -* Using Array -```java -Stream < String > fromArray = Arrays.stream( new String [] { " x " , " y " , " z " }); -``` -* Using file (each line in the file will be a separate element in the stream): -```java -Stream < String > fromFile = Files.lines( Paths.get(" input.txt ")); -``` -* From the line: -```java -IntStream fromString = " 0123456789 " . chars (); -``` -* With the help of `Stream.builder()`: -```java -Stream < String > fromBuilder = Stream.builder().add (" z ").add(" y ").add(" z ").build (); -``` -* Using `Stream.iterate()(infinite)`: -```java -Stream < Integer > fromIterate = Stream.iterate ( 1 , n - > n + 1 ); -``` -* Using `Stream.generate()(infinite)`: -```java -Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); -``` - - - -## Q. What is the difference between `Collection` and `Stream`? - -Collections 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. - - - -## Q. What is the method `collect()`for streams for? - -A method `collect()`is the final operation that is used to represent the result as a collection or some other data structure. - -`collect()`accepts an input that contains four stages: - -* **supplier** — initialization of the battery, -* **accumulator** — processing of each element, -* **combiner** — connection of two accumulators in parallel execution, -* **[finisher]** —a non-mandatory method of the last processing of the accumulator. - -In Java 8, the class `Collectors` implements several common collectors: - -* `toList()`, `toCollection()`, `toSet()`- present stream in the form of a list, collection or set; -* `toConcurrentMap()`, `toMap()`- allow you to convert the stream to `Map`; -* `averagingInt()`, `averagingDouble()`, `averagingLong()`- return the average value; -* `summingInt()`, `summingDouble()`, `summingLong()`- returns the sum; -* `summarizingInt()`, `summarizingDouble()`, `summarizingLong()`- return SummaryStatisticswith different values of the aggregate; -* `partitioningBy()`- divides the collection into two parts according to the condition and returns them as `Map`; -* `groupingBy()`- divides the collection into several parts and returns `Map>`; -* `mapping()`- Additional value conversions for complex Collectors. - -There is also the possibility of creating your own collector through `Collector.of()`: -```java -Collector < String , a List < String > , a List < String > > toList = Collector.of ( - ArrayList :: new , - List :: add, - (l1, l2) -> {l1 . addAll (l2); return l1; } -); -``` - - - -## Q. Why do streams use `forEach()`and `forEachOrdered()` methods? - -* `forEach()` applies a function to each stream object; ordering in parallel execution is not guaranteed; -* `forEachOrdered()` applies a function to each stream object while maintaining the order of the elements. - - - -## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream? - -The method `map()`is an intermediate operation, which transforms each element of the stream in a specified way. - -`mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`, returns the corresponding numerical stream (ie the stream of numerical primitives): -```java -Stream - .of ( " 12 " , " 22 " , " 4 " , " 444 " , " 123 " ) - .mapToInt ( Integer :: parseInt) - .toArray (); // [12, 22, 4, 444, 123] -``` - - - -## Q. What is the purpose of `filter()` method in streams? - -The method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition. - - - -## Q. What is the use of `limit()` method in streams? - -The method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements. - - - -## Q. What is the use of `sorted()` method in streams? - -The method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator. - -The order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation. - - - -## Q. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`? - -The 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. -```java -Stream - .of ( " Hello " , " world! " ) - .flatMap ((p) -> Arrays.stream (p . split ( " , " ))) - .toArray ( String [] :: new ); // ["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"] -``` -`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. - - - -## Q. Tell us about parallel processing in Java 8? - -Streams 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. - -You can also use the `parallelStream()`interface method to create a parallel stream from the collection `Collection`. - -To 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. - -Using, 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: -```java -collection - .stream () - .peek ( ... ) // operation is sequential - .parallel () - .map ( ... ) // the operation can be performed in parallel, - .sequential () - .reduce ( ... ) // operation is sequential again -``` -As 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()`. - -* Criteria that may affect performance in parallel streams: -* Data size - the more data, the more difficult it is to separate the data first, and then combine them. -* 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. -* 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. -* Operations with primitive types will be faster than with class objects. -* 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; -* 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()`: -```java -collection.parallelStream () - .sorted () - .unordered () - .collect ( Collectors . toList ()); -``` - - - -## Q. What are the final methods of working with streams you know? - -* `findFirst()` returns the first element -* `findAny()` returns any suitable item -* `collect()` presentation of results in the form of collections and other data structures -* `count()` returns the number of elements -* `anyMatch()`returns trueif the condition is satisfied for at least one element -* `noneMatch()`returns trueif the condition is not satisfied for any element -* `allMatch()`returns trueif the condition is satisfied for all elements -* `min()`returns the minimum element, using as a condition Comparator -* `max()`returns the maximum element, using as a condition Comparator -* `forEach()` applies a function to each object (order is not guaranteed in parallel execution) -* `forEachOrdered()` applies a function to each object while preserving the order of elements -* `toArray()` returns an array of values -* `reduce()`allows you to perform aggregate functions and return a single result. -* `sum()` returns the sum of all numbers -* `average()` returns the arithmetic mean of all numbers. - - - -## Q. What intermediate methods of working with streams do you know? - -* `filter()` filters records, returning only records matching the condition; -* `skip()` allows you to skip a certain number of elements at the beginning; -* `distinct()`returns a stream without duplicates (for a method `equals()`); -* `map()` converts each element; -* `peek()` returns the same stream, applying a function to each element; -* `limit()` allows you to limit the selection to a certain number of first elements; -* `sorted()`allows you to sort values ​​either in natural order or by setting `Comparator`; -* `mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`return stream numeric primitives; -* `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- similar to `map()`, but can create a single element more. - -For numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream. - - - -## Q. How to display 10 random numbers using forEach()? - -```java -( new Random ()) - .ints () - .limit ( 10 ) - .forEach ( System . out :: println); -``` - - - -## Q. How can I display unique squares of numbers using the method map()? - -```java -Stream - .of ( 1 , 2 , 3 , 2 , 1 ) - .map (s -> s * s) - .distinct () - .collect ( Collectors . toList ()) - .forEach ( System . out :: println); -``` - - - -## Q. How to display the number of empty lines using the method filter()? - -```java -System.out.println ( - Stream - .of ( " Hello " , " " , " , " , " world " , " ! " ) - .filter ( String :: isEmpty) - .count ()); -``` - - - -## Q. How to display 10 random numbers in ascending order? - -```java -( new Random ()) - .ints () - .limit ( 10 ) - .sorted () - .forEach ( System . out :: println); -``` - - - -## Q. How to find the maximum number in a set? - -```java -Stream - .of ( 5 , 3 , 4 , 55 , 2 ) - .mapToInt (a -> a) - .max () - .getAsInt (); // 55 -``` - - - -## Q. How to find the minimum number in a set? - -```java -Stream - .of ( 5 , 3 , 4 , 55 , 2 ) - .mapToInt (a -> a) - .min () - .getAsInt (); // 2 -``` - - - -## Q. How to get the sum of all numbers in a set? - -```java -Stream - .of( 5 , 3 , 4 , 55 , 2 ) - .mapToInt() - .sum(); // 69 -``` - - - -## Q. How to get the average of all numbers? - -```java -Stream - .of ( 5 , 3 , 4 , 55 , 2 ) - .mapToInt (a -> a) - .average () - .getAsDouble (); // 13.8 -``` -## Q. What additional methods for working with associative arrays (maps) appeared in Java 8? - -* `putIfAbsent()` adds a key-value pair only if the key was missing: -```java -map.putIfAbsent("a", "Aa"); -``` - -* `forEach()` accepts a function that performs an operation on each element: -```java -map.forEach((k, v) -> System.out.println(v)); -``` - -* `compute()` creates or updates the current value to the result of the calculation (it is possible to use the key and the current value): -```java -map.compute("a", (k, v) -> String.valueOf(k).concat(v)); //["a", "aAa"] -``` - -* `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): -```java -map.computeIfPresent("a", (k, v) -> k.concat(v)); -``` - -* `computeIfAbsent()` if the key is missing, creates it with the value that is calculated (it is possible to use the key): -```java -map.computeIfAbsent("a", k -> "A".concat(k)); //["a","Aa"] -``` - -* `getOrDefault()` if there is no key, returns the passed value by default: -```java -map.getOrDefault("a", "not found"); -``` - -* `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. -```java -map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] -``` - - - -## Q. What is LocalDateTime? - -`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. - - - -## Q. What is ZonedDateTime? - -`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. - - - -## Q. How to get current date using Date Time API from Java 8? - -```java -LocalDate as.now(); -``` - - - -## Q. How to add 1 week, 1 month, 1 year, 10 years to the current date using the Date Time API? - -```java -LocalDate as.now ().plusWeeks ( 1 ); -LocalDate as.now ().plusMonths ( 1 ); -LocalDate as.now ().plusYears ( 1 ); -LocalDate as.now ().plus ( 1 , ChronoUnit.DECADES ); -``` - - - -## Q. How to get the next Tuesday using the Date Time API? - -```java -LocalDate as.now().with( TemporalAdjusters.next ( DayOfWeek.TUESDAY )); -``` - - - -## Q. How to get the current time accurate to milliseconds using the Date Time API? - -```java -new Date ().toInstant (); -``` - - - -## Q. How to get the second Saturday of the current month using the Date Time API? - -```java -LocalDate - .of ( LocalDate.Now ().GetYear (), LocalDate.Now ().GetMonth (), 1 ) - .with ( TemporalAdjusters.nextOrSame ( DayOfWeek.SATURDAY )) - .with ( TemporalAdjusters.next ( DayOfWeek.SATURDAY )); -``` - - -## Q. How to get the current time in local time accurate to milliseconds using the Date Time API? - -```java -LocalDateTime.ofInstant ( new Date().toInstant(), ZoneId.systemDefault()); -``` - - - -## Q. How to determine repeatable annotation? - -To define a repeatable annotation, you must create a container annotation for the list of repeatable annotations and designate a repeatable meta annotation `@Repeatable`: - -```java -@interface Schedulers { - Scheduler [] value (); -} - -@Repeatable ( Schedulers . Class) - @interface Scheduler { - String birthday () default "Jan 8 2000"; - } -``` - - - -## Q. What is Nashorn? - -**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. - - - -## Q. What is jjs? - -`jjs` - This is a command line utility that allows you to execute JavaScript programs directly in the console. - - - -## Q. What class appeared in Java 8 for encoding / decoding data? - -`Base64`- a thread-safe class that implements a data encoder and decoder using a base64 encoding scheme according to RFC 4648 and RFC 2045 . - -Base64 contains 6 basic methods: - -`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 ; -`getMimeEncoder() / getMimeDecoder()`- returns a MIME encoder / decoder conforming to RFC 2045 . - - - -## Q. How to create a Base64 encoder and decoder? - -```java -// Encode -String b64 = Base64.getEncoder().encodeToString ( " input " . getBytes ( " utf-8 " )); // aW5wdXQ == -// Decode -new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // input -``` - - - -## Q. What are the functional interfaces `Function`, `DoubleFunction`, `IntFunction` and `LongFunction`? - -`Function`- 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`. - -Default methods can be used to build call chains ( `compose`, `andThen`). -```java -Function < String , Integer > toInteger = Integer :: valueOf; -Function < String , String > backToString = toInteger.andThen ( String :: valueOf); -backToString.apply("123"); // "123" -``` -* `DoubleFunction`- a function that receives input `Double` and returns an instance of the class at the output `R`; -* `IntFunction`- a function that receives input `Integer`and returns an instance of the class at the output `R`; -* `LongFunction`- a function that receives input `Long`and returns an instance of the class at the output `R`. - - - -## Q. What are the functional interfaces `UnaryOperator`, `DoubleUnaryOperator`, `IntUnaryOperator`and `LongUnaryOperator`? - -`UnaryOperator`(**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`: -```java -UnaryOperator < Integer > operator = x - > x * x; -System.out.println(operator.apply ( 5 )); // 25 -``` -* `DoubleUnaryOperator`- unary operator receiving input `Double`; -* `IntUnaryOperator`- unary operator receiving input `Integer`; -* `LongUnaryOperator`- unary operator receiving input `Long`. - - - -## Q. What are the functional interfaces `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`? - -`BinaryOperator`(**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`. -```java -BinaryOperator < Integer > operator = (a, b) -> a + b; -System.out.println(operator.apply ( 1 , 2 )); // 3 -``` -* `DoubleBinaryOperator`- binary operator receiving input Double; -* `IntBinaryOperator`- binary operator receiving input Integer; -* `LongBinaryOperator`- binary operator receiving input Long. - - - -## Q. What are the functional interfaces `Predicate`, `DoublePredicate`, `IntPredicateand` `LongPredicate`? - -`Predicate`(**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`. - -The interface contains a variety of methods by default, allow to build complex conditions ( `and`, `or`, `negate`). -```java -Predicate < String > predicate = (s) -> s.length () > 0 ; -predicate.test("foo"); // true -predicate.negate().test("foo"); // false -``` -* `DoublePredicate`- predicate receiving input `Double`; -* `IntPredicate`- predicate receiving input `Integer`; -* `LongPredicate`- predicate receiving input `Long`. - - - -## Q. What are the functional interfaces `Consumer`, `DoubleConsumer`, `IntConsumer`and `LongConsumer`? - -`Consumer`(**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. -```java -Consumer hello = (name) -> System.out.println( " Hello, " + name); -hello.accept( " world " ); -``` -* `DoubleConsumer`- the consumer receiving the input `Double`; -* `IntConsumer`- the consumer receiving the input `Integer`; -* `LongConsumer`- the consumer receiving the input `Long`. - - - -## Q. What are the functional interfaces `Supplier`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier`and `LongSupplier`? - -`Supplier`(**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`; -```java -Supplier < LocalDateTime > now = LocalDateTime::now; -now.get(); -``` -* `DoubleSupplier`- the supplier is returning `Double`; -* `IntSupplier`- the supplier is returning `Integer`; -* `LongSupplier`- the supplier is returning `Long`. - - - -#### Q. When do we go for Java 8 Stream API? -#### Q. Why do we need to use Java 8 Stream API in our projects? -#### Q. Explain Differences between Collection API and Stream API? -#### Q. What is Spliterator in Java SE 8? Differences between Iterator and Spliterator in Java SE 8? -#### Q. What is Optional in Java 8? What is the use of Optional? -#### Q. What is Type Inference? Is Type Inference available in older versions like Java 7 and Before 7 or it is available only in Java SE 8? -#### Q. What is differences between Functional Programming and Object-Oriented Programming? - - diff --git a/jsp-questions.md b/jsp-questions.md index d452be8..a029f7a 100644 --- a/jsp-questions.md +++ b/jsp-questions.md @@ -436,7 +436,33 @@ The jsp page, by default, always creates a session. Using a directive pagewith a ## Q. What is the difference between JSPWriter and PrintWriter? `PrintWriter` is the object responsible for recording the contents of the response to the request. `JspWriter` uses an object `PrintWriter` to buffer. When the buffer is full or flushed, it `JspWriter`uses the object `PrintWriter` to write the content in response. -#### Q. How to disable caching on back button of the browser? +## Q. How to disable caching on back button of the browser? +for this, once the session is invalidated, in your respective jsp page add following code snippet +```jsp +<% + response.setHeader("Cache-Control","no-cache, no-store, must-revalidate"); + response.setHeader("Pragma","no-cache"); + response.setHeader ("Expires", 0); + response.setDateHeader ("Expires", -1); + if(session.getAttribute("token")==null){ + response.sendRedirect(request.getContextPath() + "/login.jsp"); + } +%> +``` +_`token` can be any valid session attribute used for validation_ + +**Cache-Control** : HTTP 1.1 header filed holds directives (in requests and responses) that control caching in browsers and shared chaches eg. proxies , CDNs. +- no-cache : allows caches to store a response, but requires them to revalidate it before reuse. +- no-store : any caches of any kind (private or shared) should not store this request and corresponding response. +- must-revalidate: cache either revalidates the stored response with the origin server, or if that's not possible it generates a 504 (Gateway Timeout) response to prevent reuse of stale responses when they are disconnected from the origin server. + +**Pragma** : HTTP 1.0 header is an implementation-specific header that may have various effects along the request-response chain to prevent the client from caching the response. +- no-cache: Forces caches to submit the request to the origin server for validation before a cached copy is released. + +**Expires**: HTTP header contains the date/time after which the response is considered expired. +- Invalid expiration dates with value 0 represent a date in the past and mean that the resource is already expired. +- `setDateHeader()` used in case to prevent caching on proxy servers + #### Q. What are the different tags provided in JSTL? #### Q. How is JSP better than Servlet technology? #### Q. What are the differences between include directive and include action? @@ -452,4 +478,4 @@ The jsp page, by default, always creates a session. Using a directive pagewith a #### Q. Which containers use a FlowLayout as their default layout? #### Q. What are peerless components? #### Q. Is there is any difference between a Scrollbar and a ScrollPane? -#### Q. What is a lightweight and heavyweight component? \ No newline at end of file +#### Q. What is a lightweight and heavyweight component? diff --git a/multithreading-questions.md b/multithreading-questions.md index fdbb78b..62c8d7f 100644 --- a/multithreading-questions.md +++ b/multithreading-questions.md @@ -1,7 +1,7 @@ -# Multithreading Interview Questions and Answers +# Multithreading Interview Questions ## Q. What are the states in the lifecycle of a Thread? -A java thread can be in any of following thread states during it’s life cycle i.e. New, Runnable, Blocked, Waiting, Timed Waiting or Terminated. These are also called life cycle events of a thread in java. +A java thread can be in any of following thread states during it\'s life cycle i.e. New, Runnable, Blocked, Waiting, Timed Waiting or Terminated. These are also called life cycle events of a thread in java. * New * Runnable @@ -60,7 +60,7 @@ class MyThread implements Runnable { **Difference between Runnable vs Thread** -* Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go. +* Implementing Runnable is the preferred way to do it. Here, you’re not really specializing or modifying the thread\'s behavior. You’re just giving the thread something to run. That means composition is the better way to go. * Java only supports single inheritance, so you can only extend one class. * Instantiating an interface gives a cleaner separation between your code and the implementation of threads. * Implementing Runnable makes your class more flexible. If you extend Thread then the action you’re doing is always going to be in a thread. However, if you implement Runnable it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application. @@ -364,7 +364,7 @@ HiClass is calling HelloClass second() method ``` **Avoid deadlock** -**1. Avoid Nested Locks**: This is the most common reason for deadlocks, avoid locking another resource if you already hold one. It’s almost impossible to get deadlock situation if you are working with only one object lock. For example, here is the another implementation of run() method without nested lock and program runs successfully without deadlock situation. +**1. Avoid Nested Locks**: This is the most common reason for deadlocks, avoid locking another resource if you already hold one. It\'s almost impossible to get deadlock situation if you are working with only one object lock. For example, here is the another implementation of run() method without nested lock and program runs successfully without deadlock situation. ```java public void run() { String name = Thread.currentThread().getName(); @@ -383,9 +383,9 @@ public void run() { System.out.println(name + ' finished execution.'); } ``` -**2. Lock Only What is Required**: You should acquire lock only on the resources you have to work on, for example in above program I am locking the complete Object resource but if we are only interested in one of it’s fields, then we should lock only that specific field not complete object. +**2. Lock Only What is Required**: You should acquire lock only on the resources you have to work on, for example in above program I am locking the complete Object resource but if we are only interested in one of it\'s fields, then we should lock only that specific field not complete object. -**3. Avoid waiting indefinitely**: You can get deadlock if two threads are waiting for each other to finish indefinitely using thread join. If your thread has to wait for another thread to finish, it’s always best to use join with maximum time you want to wait for thread to finish. +**3. Avoid waiting indefinitely**: You can get deadlock if two threads are waiting for each other to finish indefinitely using thread join. If your thread has to wait for another thread to finish, it\'s always best to use join with maximum time you want to wait for thread to finish.
↥ back to top @@ -689,11 +689,11 @@ class Vector_demo { ↥ back to top
-## Q. What is Thread Group? Why it’s advised not to use it? +## Q. What is Thread Group? Why it\'s advised not to use it? ThreadGroup creates a group of threads. It offers a convenient way to manage groups of threads as a unit. This is particularly valuable in situation in which you want to suspend and resume a number of related threads. * The thread group form a tree in which every thread group except the initial thread group has a parent. -* A thread is allowed to access information about its own thread group but not to access information about its thread group’s parent thread group or any other thread group. +* A thread is allowed to access information about its own thread group but not to access information about its thread group\'s parent thread group or any other thread group. ```java // Java code illustrating Thread Group import java.lang.*; @@ -952,7 +952,7 @@ JNI global references: 116 * **Thread Priority**: Priority of the thread * **Thread ID**: Represents the unique ID of the Thread * **Thread Status**: Provides the current thread state, for example RUNNABLE, WAITING, BLOCKED. While analyzing deadlock look for the blocked threads and resources on which they are trying to acquire lock. -* **Thread callstack**: Provides the vital stack information for the thread. This is the place where we can see the locks obtained by Thread and if it’s waiting for any lock. +* **Thread callstack**: Provides the vital stack information for the thread. This is the place where we can see the locks obtained by Thread and if it\'s waiting for any lock. **Tools** @@ -1215,7 +1215,7 @@ lock.unlock(); **Difference between Lock Interface and synchronized keyword** * Having a timeout trying to get access to a `synchronized` block is not possible. Using `Lock.tryLock(long timeout, TimeUnit timeUnit)`, it is possible. -* The `synchronized` block must be fully contained within a single method. A Lock can have it’s calls to `lock()` and `unlock()` in separate methods. +* The `synchronized` block must be fully contained within a single method. A Lock can have it\'s calls to `lock()` and `unlock()` in separate methods. ```java import java.util.concurrent.TimeUnit; @@ -1384,7 +1384,7 @@ Output ↥ back to top -## Q. What is the Thread’s interrupt flag? How does it relate to the InterruptedException? +## Q. What is the Thread\'s interrupt flag? How does it relate to the InterruptedException? If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Example: **Interrupting a thread that stops working** @@ -1472,7 +1472,7 @@ Starvation can occur due to the following reasons: * Threads are blocked infinitely because a thread takes long time to execute some synchronized code (e.g. heavy I/O operations or infinite loop). -* A thread doesn’t get CPU’s time for execution because it has low priority as compared to other threads which have higher priority. +* A thread doesn’t get CPU\'s time for execution because it has low priority as compared to other threads which have higher priority. * Threads are waiting on a resource forever but they remain waiting forever because other threads are constantly notified instead of the hungry ones. @@ -1595,7 +1595,7 @@ try{ ## Q. What is Callable and Future in Java concurrency? -Future and FutureTask in Java allows to write asynchronous code. A Future interface provides methods **to check if the computation is complete, to wait for its completion and to retrieve the results of the computation**. The result is retrieved using Future’s get() method when the computation has completed, and it blocks until it is completed. We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously. +Future and FutureTask in Java allows to write asynchronous code. A Future interface provides methods **to check if the computation is complete, to wait for its completion and to retrieve the results of the computation**. The result is retrieved using Future\'s get() method when the computation has completed, and it blocks until it is completed. We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously. ```java import java.util.concurrent.Callable; @@ -2073,7 +2073,8 @@ The `wait()` is mainly used for shared resources, a thread notifies other waitin #### Q. What is SynchronousQueue in Java? #### Q. What is Exchanger in Java concurrency? #### Q. What is Busy Spinning? Why will you use Busy Spinning as wait strategy? +#### Q. What is Multithreading in java? \ No newline at end of file +