From 3e91ea1dda4c420f4d71e08b1419571a798cb300 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 27 Jul 2022 19:50:20 +0530 Subject: [PATCH 001/100] Update README.md --- README.md | 295 +++++++++++++++++++++++++++++++++++------------------- 1 file changed, 192 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index 2d05a5c..91168c7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,8 @@ -## Java, J2EE, JSP, Servlet, Hibernate Interview Questions +# Java, J2EE, JSP, Servlet, Hibernate Interview Questions *Click if you like the project. Pull Request are highly appreciated.* - -### Table of Contents +## Table of Contents * *[Java 8 Interview Questions](java8-questions.md)* * *[Multithreading Interview Questions](multithreading-questions.md)* @@ -20,6 +19,7 @@
## 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. **Types of Java Exceptions** @@ -33,8 +33,8 @@ The java.lang.Throwable class is the root class of Java Exception hierarchy whic Java Exception - Example: + ```java import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -84,18 +84,19 @@ public class CustomExceptionExample { } } ``` +
- ↥ back to top + ↥ back to top
## Q. ***What is the difference between aggregation and composition?*** Aggregation - **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 public class Organization { private List employees; @@ -109,6 +110,7 @@ public class Person { **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 public class Car { //final will make sure engine is initialized @@ -140,10 +142,11 @@ class Engine { *Note: "final" keyword is used in Composition to make sure child variable is initialized.*
- ↥ back to top + ↥ back to top
## Q. ***What is difference between Heap and Stack Memory in java?*** + **Java Heap Space** 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. @@ -172,28 +175,31 @@ As soon as method ends, the block becomes unused and become available for next m |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. ***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?*** + 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.
- ↥ 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. **Types of ClassLoader** @@ -205,27 +211,29 @@ The **Java ClassLoader** is a part of the Java Runtime Environment that dynamica **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.
- ↥ 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. **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. **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 Compiler
- ↥ back to top + ↥ back to top
## 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. For example credit card validator factory which returns a different validator for each card type. + ```java public ICardValidator GetCardValidator (string cardType) { @@ -241,15 +249,17 @@ public ICardValidator GetCardValidator (string cardType) } } ``` + 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.
- ↥ 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 @@ -258,10 +268,11 @@ Class inherits methods from the following classes in terms of HashMap * java.util.Map
- ↥ back to top + ↥ back to top
## 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 { @@ -289,17 +300,19 @@ class HybridCar extends Car { } ```
- ↥ back to top + ↥ back to top
## 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.
- ↥ back to top + ↥ back to top
## 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 { @@ -314,10 +327,11 @@ class TestClass { Class.forName (String className); ```
- ↥ back to top + ↥ back to top
## 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 @@ -339,10 +353,11 @@ public class MyRunnable implements Runnable { ```
- ↥ back to top + ↥ back to top
## 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 @@ -360,17 +375,19 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l **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.
- ↥ back to top + ↥ 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. @@ -463,10 +480,11 @@ Calling parameterized constructor of base Calling parameterized constructor of derived ```
- ↥ back to top + ↥ 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. ```java public class Test { @@ -486,19 +504,21 @@ 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.
- ↥ back to top + ↥ back to top
## 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 @@ -557,17 +577,19 @@ 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.
- ↥ back to top + ↥ back to top
## 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. **Virtual function with Interface** @@ -587,10 +609,11 @@ class ACMEBicycle implements Bicycle { } ```
- ↥ back to top + ↥ 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. ```java class SuperClass { @@ -615,10 +638,11 @@ 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. @@ -638,17 +662,19 @@ Subclass
- ↥ back to top + ↥ back to top
## 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.
- ↥ back to top + ↥ back to top
## 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 { @@ -670,10 +696,11 @@ public interface Test { * 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 + ↥ back to top
## 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 { @@ -693,10 +720,11 @@ public class TestFoo implements Foo { } ```
- ↥ back to top + ↥ 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 − * **InPutStream** − The InputStream is used to read data from a source. @@ -763,26 +791,29 @@ public class CopyFile { } ```
- ↥ back to top + ↥ 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. **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 + ↥ back to top
## 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. The assert statement is used with a Boolean expression and can be written in two different ways. @@ -804,17 +835,19 @@ public class Example { } ```
- ↥ back to top + ↥ 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. |Sl.No|Abstract Class |Interface | @@ -829,10 +862,11 @@ Abstract class and interface both are used to achieve abstraction where we can d | 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 + ↥ 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** @@ -874,10 +908,11 @@ Output 20 20 20 ```
- ↥ 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. There are 3 ways to get the instance of Class class. They are as follows: @@ -947,17 +982,19 @@ boolean Test ```
- ↥ back to top + ↥ 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. **Types of Java Constructors** @@ -1002,10 +1039,11 @@ public class Car } ```
- ↥ back to top + ↥ back to top
## 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 @@ -1041,10 +1079,11 @@ 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. ```java class Demo { @@ -1110,10 +1149,11 @@ class ABC extends XYZ { } ```
- ↥ 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.*; @@ -1126,10 +1166,11 @@ class StaticImportExample { } ```
- ↥ 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. **java.util.regex package** @@ -1159,10 +1200,11 @@ public class RegexExample { } ```
- ↥ 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 @@ -1183,10 +1225,11 @@ class ExternalProcessExample } ```
- ↥ 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. **BufferedInputStreamExample.java** @@ -1274,10 +1317,11 @@ Output This is an example of writing data to a file ```
- ↥ 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. ```java import java.io.File; @@ -1319,10 +1363,11 @@ public class FilePermissions { } ```
- ↥ 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). **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. @@ -1378,10 +1423,11 @@ public class Sample } ```
- ↥ back to top + ↥ back to top
## 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 import java.io.FileOutputStream; @@ -1454,11 +1500,12 @@ java.io.NotSerializableException: This class cannot be Serialized at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) ```
- ↥ back to top + ↥ back to top
## 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.| @@ -1468,10 +1515,11 @@ java.io.NotSerializableException: This class cannot be Serialized | 05.|Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. |
- ↥ back to top + ↥ back to top
## Q. ***What are the ways to instantiate the Class class?*** + **1. Using new keyword** ```java MyObject object = new MyObject(); @@ -1491,10 +1539,11 @@ ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); ```
- ↥ back to top + ↥ back to top
## 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 @@ -1516,10 +1565,11 @@ class Simple { } ```
- ↥ back to top + ↥ back to top
## 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. Example: Autoboxing @@ -1547,10 +1597,11 @@ class UnboxingExample1 { } ```
- ↥ back to top + ↥ back to top
## 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: **Main.java** @@ -1586,10 +1637,11 @@ Output 4 ```
- ↥ back to top + ↥ back to top
## 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. **Creating an Immutable Object** @@ -1612,10 +1664,11 @@ public class DateContainer { } ```
- ↥ back to top + ↥ back to top
## 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 @@ -1638,10 +1691,11 @@ class Apple { } ```
- ↥ back to top + ↥ back to top
## 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. | |DOM (Document Object Model) |Parser SAX (Simple API for XML) Parser | @@ -1653,10 +1707,11 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h |suitable |better suitable for smaller and efficient memory| SAX is suitable for larger XML doc|
- ↥ back to top + ↥ back to top
## 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. ```java String a = "abc"; @@ -1668,10 +1723,11 @@ String d = new String("abc"); System.out.println(c == d); // false ```
- ↥ back to top + ↥ 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** @@ -1696,10 +1752,11 @@ public final class Employee { } ```
- ↥ back to top + ↥ back to top
## 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. **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. @@ -1725,10 +1782,11 @@ public class BuilderTest{ } ```
- ↥ back to top + ↥ back to top
## 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. Some tools that do memory management to identifies useless objects or memeory leaks like: @@ -1765,18 +1823,20 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed * Through `finalize()` Methods * Calling `String.intern()` on Long String
- ↥ back to top + ↥ back to top
## 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.
- ↥ back to top + ↥ back to top
## 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.| @@ -1788,10 +1848,11 @@ Since String is immutable, its hashcode is cached at the time of creation and it |Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.|
- ↥ back to top + ↥ back to top
## 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 { @@ -1817,10 +1878,11 @@ class TestExceptionPropagation { } ```
- ↥ back to top + ↥ back to top
## 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. @@ -1828,10 +1890,11 @@ Some of the common main thread exception are as follows: * **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.
- ↥ back to top + ↥ back to top
## 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. **Throw Example** @@ -1880,10 +1943,11 @@ Output You shouldn't divide number by zero ```
- ↥ back to top + ↥ back to top
## Q. ***The difference between Serial and Parallel Garbage Collector?*** + **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. @@ -1895,10 +1959,11 @@ Turn on the `-XX:+UseSerialGC` JVM argument to use the serial 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.
- ↥ back to top + ↥ back to top
## 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. * Strong References @@ -1995,10 +2060,11 @@ public class Example } ```
- ↥ back to top + ↥ back to top
## 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:** @@ -2013,11 +2079,12 @@ They are replaced with actual values at compile time because compiler know their private final int x = 10; ```
- ↥ back to top + ↥ back to top
## 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: @@ -2053,20 +2120,22 @@ public class ClassLoaderTest { } ```
- ↥ back to top + ↥ back to top
-## Q. ***Why string is immutable in java?*** +## 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.
- ↥ back to top + ↥ back to top
-## Q. ***What is Java String Pool?*** +## 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. @@ -2090,19 +2159,21 @@ public class StringPool { } ```
- ↥ back to top + ↥ back to top
-## Q. ***How Garbage collector algorithm works?*** +## 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
- ↥ back to top + ↥ back to top
## 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. Syntax: @@ -2133,10 +2204,11 @@ class Main { } ```
- ↥ back to top + ↥ back to top
## 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: @@ -2228,11 +2300,12 @@ public class SerialExample { } ```
- ↥ back to top + ↥ back to top
## Q. ***What are the various ways to load a class in Java?*** + **a). Creating a reference**: ```java SomeClass someInstance = null; @@ -2253,11 +2326,12 @@ ClassLoader.getSystemClassLoader().loadClass("SomeClass"); Class.forName(String name, boolean initialize, ClassLoader loader); ```
- ↥ back to top + ↥ back to top
## 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. Example: @@ -2336,10 +2410,11 @@ Nodes of singly linked list: 10 20 30 40 ```
- ↥ back to top + ↥ back to top
-## Q. ***While overriding a method can you throw another exception or broader exception?*** +## 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. @@ -2367,10 +2442,11 @@ class B extends A { } ```
- ↥ back to top + ↥ back to top
-## Q. ***What is checked, unchecked exception and errors?*** +## Q. ***What is checked, unchecked exception and errors?*** + **1. Checked Exception**: @@ -2451,10 +2527,11 @@ Java Result: 1 Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc.
- ↥ back to top + ↥ back to top
## 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. @@ -2462,10 +2539,11 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. `NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time.
- ↥ back to top + ↥ back to top
## 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 @@ -2588,10 +2666,11 @@ public class MainClass { } ```
- ↥ back to top + ↥ back to top
## 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: @@ -2646,17 +2725,19 @@ Output Overriding Method ```
- ↥ back to top + ↥ back to top
-## 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?*** +## 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.
- ↥ back to top + ↥ back to top
## 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: @@ -2666,10 +2747,11 @@ 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.
- ↥ back to top + ↥ back to top
## 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 − @@ -2699,10 +2781,11 @@ public class MainClass { } ```
- ↥ back to top + ↥ back to top
## 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** @@ -2752,10 +2835,11 @@ Generic Class Example ! 100 ```
- ↥ back to top + ↥ back to top
## 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. @@ -2806,10 +2890,11 @@ StringBuilder: World StringBuffer: World ```
- ↥ back to top + ↥ back to top
## 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** @@ -2925,31 +3010,35 @@ public class MainClass { } ```
- ↥ back to top + ↥ back to top
-## Q. ***What code coverage tools are you using for your project?*** +## Q. ***What code coverage tools are you using for your project?*** + * Cobertura
- ↥ back to top + ↥ back to top
-## Q. ***Scenario of browser’s browsing history, where you need to store the browsing history, what data structure will you use.?*** +## Q. ***Scenario of browser’s browsing history, where you need to store the browsing history, what data structure will you use.?*** + * use `stack`
- ↥ back to top + ↥ back to top
## 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`
- ↥ back to top + ↥ 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. @@ -2968,7 +3057,7 @@ The Object class is the parent class of all the classes in java by default.
- ↥ back to top + ↥ back to top
#### Q. ***What is copyonwritearraylist in java?*** @@ -2983,7 +3072,7 @@ The Object class is the parent class of all the classes in java by default. *ToDo*
- ↥ back to top + ↥ back to top
From b3ceaf18575f3b7cd64580ff5998be79568dbb58 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 29 Jul 2022 15:46:19 +0530 Subject: [PATCH 002/100] Update README.md --- README.md | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/README.md b/README.md index 91168c7..5f9bbe1 100644 --- a/README.md +++ b/README.md @@ -2299,42 +2299,17 @@ public class SerialExample { } } ``` -
- ↥ back to top -
- -## Q. ***What are the various ways to load a class in Java?*** - - -**a). Creating a reference**: -```java -SomeClass someInstance = null; -``` - -**b). Using Class.forName(String)**: -```java - Class.forName("SomeClass"); -``` - -**c). Using SystemClassLoader()**: -```java -ClassLoader.getSystemClassLoader().loadClass("SomeClass"); -``` -**d). Using Overloaded Class.forName()**: -```java -Class.forName(String name, boolean initialize, ClassLoader loader); -```
↥ back to top
## 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. Example: + ```java public class SinglyLinkedList { // Represent a node of the singly linked list From 3428f17efd2898ed1be56a2885d3523049d87b4d Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 29 Jul 2022 15:56:35 +0530 Subject: [PATCH 003/100] Update README.md --- README.md | 107 +++++++----------------------------------------------- 1 file changed, 14 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 5f9bbe1..45966be 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Java, J2EE, JSP, Servlet, Hibernate Interview Questions +# Java Interview Questions *Click if you like the project. Pull Request are highly appreciated.* @@ -28,10 +28,13 @@ Exception is an error event that can happen during the execution of a program an **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. -**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. +**Hierarchy of Java Exception classes:** -Java Exception +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: @@ -91,8 +94,6 @@ public class CustomExceptionExample { ## Q. ***What is the difference between aggregation and composition?*** -Aggregation - **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 @@ -126,6 +127,10 @@ class Engine { } ``` +

+ Aggregation +

+ @@ -299,13 +304,6 @@ class HybridCar extends Car { //... } ``` -
- ↥ back to top -
- -## 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.
↥ back to top @@ -378,14 +376,6 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l ↥ 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. - -
- ↥ 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 – @@ -507,16 +497,6 @@ Cannot override the final method from Test. ↥ 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. - -
- ↥ back to top -
- ## Q. ***What is the difference between compile-time polymorphism and runtime polymorphism?*** There are two types of polymorphism in java: @@ -580,14 +560,6 @@ Overriding Method ↥ 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. - -
- ↥ back to top -
- ## 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. @@ -665,17 +637,10 @@ Subclass ↥ back to top -## 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. - -
- ↥ back to top -
- ## 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; @@ -683,6 +648,7 @@ public interface Test { 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 { @@ -790,13 +756,6 @@ public class CopyFile { } } ``` -
- ↥ 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 @@ -838,14 +797,6 @@ public class Example { ↥ 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 -
- ## 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. @@ -977,17 +928,11 @@ class Test { } ``` Output + ``` boolean Test ``` -
- ↥ 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 @@ -2988,30 +2933,6 @@ public class MainClass { ↥ back to top
-## Q. ***What code coverage tools are you using for your project?*** - -* Cobertura - -
- ↥ back to top -
- -## Q. ***Scenario of browser’s browsing history, where you need to store the browsing history, what data structure will you use.?*** - -* use `stack` - -
- ↥ back to top -
- -## 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` - -
- ↥ 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. From 65007ca84a8dcb8bce96a2e1b60c901969e2b6be Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 29 Jul 2022 16:06:10 +0530 Subject: [PATCH 004/100] Update README.md --- README.md | 169 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 121 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 45966be..654d062 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,19 @@ Exception is an error event that can happen during the execution of a program and disrupts its normal flow. -**Types of Java Exceptions** +**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. 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. **Hierarchy of Java Exception classes:** @@ -36,7 +44,7 @@ The java.lang.Throwable class is the root class of Java Exception hierarchy whic Exception in Java

-Example: +**Example:** ```java import java.io.FileInputStream; @@ -94,9 +102,11 @@ public class CustomExceptionExample { ## Q. ***What is the difference between aggregation and composition?*** -**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. +**1. Aggregation:** -Example: Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes +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 public class Organization { @@ -108,9 +118,11 @@ public class Person { } ``` -**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. 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. +**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 { @@ -152,13 +164,13 @@ class Engine { ## Q. ***What is difference between Heap and Stack Memory in java?*** -**Java Heap Space** +**1. Java Heap Space:** 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. 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. -**Java Stack Memory** +**2. Java Stack Memory:** Stack in java is a section of memory which contains methods, local variables and reference variables. Local variables are created in the stack. @@ -166,7 +178,7 @@ Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a 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. -**Difference** +**Difference:** |Parameter |Stack Memory |Heap Space | @@ -205,15 +217,21 @@ Java programs consists of classes, which contain platform-neutral bytecodes that ## 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. +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:** + +**a) Bootstrap Class Loader**: -**Types of ClassLoader** +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. -**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. +**b) Extensions Class Loader**: -**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. +It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` directory or any other directory as java.ext.dirs. -**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. +**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.
↥ back to top @@ -221,11 +239,17 @@ The **Java ClassLoader** is a part of the Java Runtime Environment that dynamica ## 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. +**1. 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. + +**2. 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. -**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. +**2. JRE**: -**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 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 Compiler @@ -279,6 +303,7 @@ Class inherits methods from the following classes in terms of HashMap ## 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 { @@ -294,7 +319,9 @@ class Main { } } ``` + A subclass is class which inherits a method or methods from a superclass. + ```java class Car { //... @@ -311,7 +338,10 @@ class HybridCar extends Car { ## 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. +**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. + ```java class TestClass { public static void main(String args[]) { @@ -320,22 +350,33 @@ class TestClass { } ``` -**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. +**2. 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); ``` + ## 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. +**1. 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. + +**2. 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; @@ -776,6 +817,7 @@ public class CopyFile { 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. The assert statement is used with a Boolean expression and can be written in two different ways. + ``` // First way assert expression; @@ -783,7 +825,9 @@ assert expression; // Second way assert expression1 : expression2; ``` -Example: + +**Example:** + ```java public class Example { public static void main(String[] args) { @@ -793,6 +837,7 @@ public class Example { } } ``` + @@ -839,7 +884,8 @@ The wrapper class in Java provides the mechanism to convert primitive into objec | 07. |float |Float| | 08. |double |Double| -Example: Primitive to Wrapper +**Example:** Primitive to Wrapper + ```java //Java program to convert primitive into objects //Autoboxing example of int to Integer @@ -942,12 +988,13 @@ Test 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** +**Types of Java Constructors:** * Default Constructor (or) no-arg Constructor * Parameterized Constructor -Example: Default Constructor (or) no-arg constructor +**Example:** Default Constructor (or) no-arg constructor + ```java public class Car { @@ -960,11 +1007,15 @@ public class Car } } ``` + Output -``` + +```java Default Constructor of Car class called ``` -Example: Parameterized Constructor + +**Example:** Parameterized Constructor + ```java public class Car { @@ -983,6 +1034,7 @@ public class Car } } ``` + @@ -1517,7 +1569,8 @@ class Simple { 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 +**Example:** Autoboxing + ```java class BoxingExample1 { public static void main(String args[]) { @@ -1530,7 +1583,8 @@ class BoxingExample1 { } ``` -Example: Unboxing +**Example:** Unboxing + ```java class UnboxingExample1 { public static void main(String args[]) { @@ -1616,7 +1670,8 @@ public class DateContainer { 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 +**Example:** Inheritance + ```java class Fruit { //... @@ -1625,7 +1680,9 @@ class Apple extends Fruit { //... } ``` -Example: Composition + +**Example:** Composition + ```java class Fruit { //... @@ -1706,7 +1763,8 @@ public final class Employee { **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: StringBuffer +**Example:** StringBuffer + ```java public class BufferTest{ public static void main(String[] args){ @@ -1716,7 +1774,9 @@ public class BufferTest{ } } ``` -Example: StringBuilder + +**Example:** StringBuilder + ```java public class BuilderTest{ public static void main(String[] args){ @@ -2122,12 +2182,15 @@ There are methods like System.gc() and Runtime.gc() wh 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. Syntax: + ```java public interface Interface_Name { } ``` -Example: + +**Example:** + ```java /** * Java program to illustrate Maker Interface @@ -2156,7 +2219,8 @@ class Main { 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: +**Example:** + ```java /** * Serialization and Deserialization @@ -2253,7 +2317,7 @@ public class SerialExample { 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 { @@ -2338,7 +2402,8 @@ Nodes of singly linked list: 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: +**Example:** + ```java class A { public void message() throws IOException {..} @@ -2373,7 +2438,8 @@ class B extends A { * 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. + +**Example:** **IOException, SQLException** etc. ```java import java.io.*; @@ -2423,7 +2489,8 @@ Output: First three lines of file “C:\assets\file.txt” * 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. + +**Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. ```java class Main { @@ -2443,7 +2510,7 @@ Java Result: 1 **3. Error**: -**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. +**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc.
@@ -2597,7 +2664,8 @@ 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 +**Example:** Static Polymorphism + ```java class SimpleCalculator { @@ -2622,7 +2690,9 @@ Output 30 60 ``` -Example: Runtime polymorphism + +**Example:** Runtime polymorphism + ```java class ABC { public void myMethod() { @@ -2678,7 +2748,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. -Example: +**Example:** + ```java public class EncapClass { private String name; @@ -2713,7 +2784,8 @@ public class MainClass { * **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. -Example: +**Example:** + ```java /** * A Simple Java program to show multiple @@ -2769,7 +2841,8 @@ The difference between `StringBuffer` and `StringBuilder` is that `StringBuffer` * 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: +**Example:** + ```java class StringExample { From 7f4345cbd7dd64c939cfdc5f9a5e054972e34fc4 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 17 Aug 2022 19:59:05 +0530 Subject: [PATCH 005/100] Update multithreading-questions.md --- multithreading-questions.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/multithreading-questions.md b/multithreading-questions.md index fdbb78b..92a5472 100644 --- a/multithreading-questions.md +++ b/multithreading-questions.md @@ -1,7 +1,7 @@ # Multithreading Interview Questions and Answers ## 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,6 +2073,7 @@ 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?
↥ back to top From 167cfd0d210865d646bcf8c38ad68940d5506c96 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 17 Aug 2022 19:59:46 +0530 Subject: [PATCH 006/100] Update README.md --- README.md | 175 +++++++++++++++++++++++++++--------------------------- 1 file changed, 89 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 654d062..b722b68 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@
-## Q. ***What are the types of Exceptions? Explain the hierarchy of Java Exception classes?*** +## 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. @@ -100,7 +100,7 @@ public class CustomExceptionExample { ↥ back to top
-## Q. ***What is the difference between aggregation and composition?*** +## Q. What is the difference between aggregation and composition? **1. Aggregation:** @@ -162,7 +162,7 @@ class Engine { ↥ back to top -## Q. ***What is difference between Heap and Stack Memory in java?*** +## Q. What is difference between Heap and Stack Memory in java? **1. Java Heap Space:** @@ -195,7 +195,7 @@ As soon as method ends, the block becomes unused and become available for next m ↥ back to top -## Q. ***What is JVM and is it platform independent?*** +## 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). @@ -205,7 +205,7 @@ The JVM is not platform independent. Java Virtual Machine (JVM) provides the env ↥ 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. @@ -215,7 +215,7 @@ Java programs consists of classes, which contain platform-neutral bytecodes that ↥ back to top -## Q. ***What is Classloader in Java? What are different types of classloaders?*** +## 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. @@ -237,7 +237,7 @@ It loads application specific classes from the CLASSPATH environment variable. I ↥ back to top -## Q. ***Java Compiler is stored in JDK, JRE or JVM?*** +## Q. Java Compiler is stored in JDK, JRE or JVM? **1. JDK**: @@ -257,7 +257,7 @@ Java Runtime Environment provides a platform to execute java programs. JRE consi ↥ back to top -## Q. ***What is the difference between factory and abstract factory pattern?*** +## 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. @@ -287,7 +287,7 @@ In Abstract Factory pattern an interface is responsible for creating a factory o ↥ back to top -## Q. ***What are the methods used to implement for key Object in HashMap?*** +## 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 @@ -300,7 +300,7 @@ Class inherits methods from the following classes in terms of HashMap ↥ back to top -## Q. ***What is difference between the Inner Class and Sub Class?*** +## 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. @@ -336,7 +336,7 @@ class HybridCar extends Car { ↥ back to top -## Q. ***Distinguish between static loading and dynamic class loading?*** +## Q. Distinguish between static loading and dynamic class loading? **1. Static Class Loading:** @@ -362,7 +362,7 @@ Class.forName (String className); ↥ back to top -## Q. ***What is the difference between transient and volatile variable in Java?*** +## Q. What is the difference between transient and volatile variable in Java? **1. Transient:** @@ -395,7 +395,7 @@ public class MyRunnable implements Runnable { ↥ 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: @@ -417,7 +417,7 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l ↥ back to top -## Q. ***How can constructor chaining be done using this keyword?*** +## 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 – @@ -514,7 +514,7 @@ Calling parameterized constructor of derived ↥ back to top -## Q. ***Can you declare the main method as final?*** +## 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. ```java @@ -538,7 +538,7 @@ Cannot override the final method from Test. ↥ back to top -## Q. ***What is the difference between compile-time polymorphism and runtime 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 @@ -601,7 +601,7 @@ Overriding Method ↥ back to top -## Q. ***Can you have virtual functions 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. @@ -625,7 +625,7 @@ class ACMEBicycle implements Bicycle { ↥ back to top -## Q. ***What is covariant return type?*** +## 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. ```java @@ -654,7 +654,7 @@ Subclass ↥ back to top -## Q. ***What is the difference between abstraction and encapsulation?*** +## 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. @@ -678,7 +678,7 @@ Subclass ↥ back to top -## Q. ***Can we use private or protected member variables in an interface?*** +## 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 @@ -706,7 +706,7 @@ public interface Test { ↥ back to top -## Q. ***When can an object reference be cast to a Java interface reference?*** +## 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 @@ -730,7 +730,7 @@ public class TestFoo implements Foo { ↥ back to top -## Q. ***Give the hierarchy of InputStream and OutputStream classes?*** +## 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 − @@ -802,7 +802,7 @@ public class CopyFile { ↥ back to top -## Q. ***What is the purpose of the Runtime class and System class?*** +## 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. @@ -812,7 +812,7 @@ public class CopyFile { ↥ back to top -## Q. ***What are assertions in Java?*** +## 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. @@ -842,7 +842,7 @@ public class Example { ↥ back to top -## Q. ***What is the difference between abstract class and interface?*** +## 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. @@ -861,7 +861,7 @@ Abstract class and interface both are used to achieve abstraction where we can d ↥ back to top -## Q. ***What are Wrapper classes?*** +## Q. What are Wrapper classes? The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. @@ -908,7 +908,7 @@ Output ↥ back to top -## Q. ***What is Java Reflection API?*** +## 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. @@ -984,7 +984,7 @@ Test ↥ back to top -## Q. ***How many types of constructors are used in Java?*** +## 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. @@ -1039,7 +1039,7 @@ public class Car ↥ 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. @@ -1079,7 +1079,7 @@ overridden method is static ↥ back to top -## Q. ***What is the final variable, final class, and final blank variable?*** +## 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. ```java @@ -1149,7 +1149,7 @@ class ABC extends XYZ { ↥ back to top -## Q. ***What is the static import?*** +## 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 @@ -1166,7 +1166,7 @@ class StaticImportExample { ↥ back to top -## Q. ***Name some classes present in java.util.regex package?*** +## 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. @@ -1200,7 +1200,7 @@ public class RegexExample { ↥ back to top -## Q. ***How will you invoke any external process in Java?*** +## 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 @@ -1225,7 +1225,7 @@ class ExternalProcessExample ↥ back to top -## Q. ***What is the purpose of using BufferedInputStream and BufferedOutputStream classes?*** +## 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. @@ -1317,7 +1317,7 @@ This is an example of writing data to a file ↥ back to top -## Q. ***How to set the Permissions to a file in Java?*** +## 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. ```java @@ -1363,7 +1363,7 @@ public class FilePermissions { ↥ back to top -## Q. ***In Java, How many ways you can take input from the console?*** +## 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). @@ -1423,7 +1423,7 @@ public class Sample ↥ back to top -## Q. ***How can you avoid serialization in child class if the base class is implementing the Serializable interface?*** +## 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 @@ -1500,7 +1500,7 @@ java.io.NotSerializableException: This class cannot be Serialized ↥ back to top -## Q. ***What is the difference between Serializable and Externalizable interface?*** +## Q. What is the difference between Serializable and Externalizable interface? |Sl.No |SERIALIZABLE | EXTERNALIZABLE | @@ -1515,7 +1515,7 @@ java.io.NotSerializableException: This class cannot be Serialized ↥ back to top -## Q. ***What are the ways to instantiate the Class class?*** +## Q. What are the ways to instantiate the Class class? **1. Using new keyword** ```java @@ -1539,7 +1539,7 @@ MyObject object = (MyObject) inStream.readObject(); ↥ back to top -## Q. ***What is the purpose of using javap?*** +## 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. @@ -1565,7 +1565,7 @@ class Simple { ↥ back to top -## Q. ***What are autoboxing and unboxing? When does it occur?*** +## 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. @@ -1599,7 +1599,7 @@ class UnboxingExample1 { ↥ back to top -## Q. ***What is a native method?*** +## 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: @@ -1639,7 +1639,7 @@ Output ↥ back to top -## Q. ***What is immutable object? Can you write immutable object?*** +## 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. @@ -1666,7 +1666,7 @@ public class DateContainer { ↥ back to top -## Q. ***The difference between Inheritance and Composition?*** +## 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"**. @@ -1696,7 +1696,7 @@ class Apple { ↥ back to top -## Q. ***The difference between DOM and SAX parser in Java?*** +## 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. @@ -1712,7 +1712,7 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h ↥ back to top -## Q. ***What is the difference between creating String as new() and literal?*** +## 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. ```java @@ -1728,7 +1728,7 @@ System.out.println(c == d); // false ↥ back to top -## Q. ***How can we create an immutable class in Java?*** +## 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. @@ -1757,7 +1757,7 @@ public final class Employee { ↥ back to top -## Q. ***What is difference between String, StringBuffer and StringBuilder?*** +## 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. @@ -1790,9 +1790,9 @@ public class BuilderTest{ ↥ back to top -## Q. ***What is a Memory Leak? How can a memory leak appear in garbage collected language?*** +## Q. What is a Memory Leak? -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. +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: @@ -1831,7 +1831,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ↥ back to top -## Q. ***Why String is popular HashMap key in Java?*** +## 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. @@ -1839,7 +1839,7 @@ Since String is immutable, its hashcode is cached at the time of creation and it ↥ back to top -## Q. ***What is difference between Error and Exception?*** +## Q. What is difference between Error and Exception? |BASIS FOR COMPARISON |ERROR |EXCEPTION | @@ -1856,7 +1856,7 @@ Since String is immutable, its hashcode is cached at the time of creation and it ↥ back to top -## Q. ***Explain about Exception Propagation?*** +## 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 @@ -1886,7 +1886,7 @@ class TestExceptionPropagation { ↥ back to top -## Q. ***What are different scenarios causing "Exception in thread main"?*** +## 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. @@ -1898,7 +1898,7 @@ Some of the common main thread exception are as follows: ↥ back to top -## Q. ***What are the differences between throw and throws?*** +## 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. @@ -1951,7 +1951,7 @@ You shouldn't divide number by zero ↥ back to top -## Q. ***The difference between Serial and Parallel Garbage Collector?*** +## Q. The difference between Serial and Parallel Garbage Collector? **Serial Garbage Collector** @@ -1967,7 +1967,7 @@ Parallel garbage collector is also called as throughput collector. It is the def ↥ back to top -## Q. ***What is difference between WeakReference and SoftReference in Java?*** +## 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. @@ -2068,7 +2068,7 @@ public class Example ↥ back to top -## Q. ***What is a compile time constant in Java? What is the risk of using it?*** +## 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. @@ -2087,7 +2087,7 @@ private final int x = 10; ↥ back to top -## Q. ***How bootstrap class loader works in java?*** +## 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. @@ -2128,7 +2128,7 @@ public class ClassLoaderTest { ↥ back to top -## Q. ***Why string is immutable in java?*** +## 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. @@ -2139,7 +2139,7 @@ Since string is immutable it can safely share between many threads and avoid any ↥ back to top -## Q. ***What is Java String Pool?*** +## 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. @@ -2167,7 +2167,7 @@ public class StringPool { ↥ back to top -## Q. ***How Garbage collector algorithm works?*** +## 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. @@ -2177,7 +2177,7 @@ There are methods like System.gc() and Runtime.gc() wh ↥ back to top -## Q. ***How to create marker interface?*** +## 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. @@ -2215,7 +2215,7 @@ class Main { ↥ back to top -## Q. ***How serialization works in java?*** +## 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. @@ -2313,7 +2313,7 @@ public class SerialExample { ↥ back to top -## 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. @@ -2397,7 +2397,7 @@ Nodes of singly linked list: ↥ back to top -## Q. ***While overriding a method can you throw another exception or broader exception?*** +## 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. @@ -2430,7 +2430,7 @@ class B extends A { ↥ back to top -## Q. ***What is checked, unchecked exception and errors?*** +## Q. What is checked, unchecked exception and errors? **1. Checked Exception**: @@ -2517,7 +2517,7 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ↥ back to top -## Q. ***What is difference between ClassNotFoundException and NoClassDefFoundError?*** +## 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. @@ -2529,7 +2529,7 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ↥ back to top -## Q. ***What do we mean by weak reference?*** +## 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. @@ -2656,7 +2656,7 @@ public class MainClass { ↥ back to top -## Q. ***What do you mean Run time Polymorphism?*** +## 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: @@ -2718,7 +2718,7 @@ Overriding Method ↥ back to top -## 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?*** +## 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. @@ -2726,7 +2726,7 @@ If the subclass constructor does not specify which superclass constructor to inv ↥ back to top -## Q. ***What are the different types of JDBC Driver?*** +## 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: @@ -2740,7 +2740,7 @@ There are 4 types of JDBC drivers: ↥ back to top -## Q. ***How Encapsulation concept implemented in JAVA?*** +## 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`. @@ -2775,7 +2775,7 @@ public class MainClass { ↥ back to top -## Q. ***Do you know Generics? How did you used in your coding?*** +## 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. @@ -2830,7 +2830,7 @@ Generic Class Example ! ↥ back to top -## Q. ***What is difference between String, StringBuilder and StringBuffer?*** +## 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. @@ -2886,7 +2886,7 @@ StringBuffer: World ↥ back to top -## Q. ***How can we create a object of a class without using new operator?*** +## 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** @@ -3006,7 +3006,7 @@ public class MainClass { ↥ back to top -## Q. ***What are methods of Object Class?*** +## Q. What are methods of Object Class? The Object class is the parent class of all the classes in java by default. @@ -3029,15 +3029,18 @@ The Object class is the parent class of all the classes in java by default. ↥ back to top -#### 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?*** +#### 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? +#### Q. What is a copy constructor in Java? +#### Q. What are the different access specifiers available in java? +#### Q. *ToDo*
From 4828d981d8ee301bbd49d63832d9ec022aaf7b3e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 17 Aug 2022 20:01:57 +0530 Subject: [PATCH 007/100] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b722b68..1bd69ba 100644 --- a/README.md +++ b/README.md @@ -3040,7 +3040,8 @@ The Object class is the parent class of all the classes in java by default. #### Q. What is differences between External Iteration and Internal Iteration? #### Q. What is a copy constructor in Java? #### Q. What are the different access specifiers available in java? -#### Q. +#### Q. What is runtime polymorphism in java? + *ToDo*
From 5feb0619ce1fbd8f7f409a4111c4dfd030c67d67 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 10:15:12 +0530 Subject: [PATCH 008/100] Update README.md --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1bd69ba..f762df0 100644 --- a/README.md +++ b/README.md @@ -26,17 +26,21 @@ Exception is an error event that can happen during the execution of a program an **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. +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. +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. -**Hierarchy of Java Exception classes:** + + +## 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. From 5402359f27193fcf1534e982cf2a25b7c57c9370 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 10:15:53 +0530 Subject: [PATCH 009/100] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index f762df0..d224837 100644 --- a/README.md +++ b/README.md @@ -22,8 +22,6 @@ Exception is an error event that can happen during the execution of a program and disrupts its normal flow. -**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. From 279d9728da66302ac19ab8e620353ab2b807a89a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 10:31:12 +0530 Subject: [PATCH 010/100] Update README.md --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d224837..629b1bb 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErro ## 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. +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 @@ -49,6 +49,9 @@ The java.lang.Throwable class is the root class of Java Exception hierarchy whic **Example:** ```java +/** + * Exception classes + */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -111,6 +114,9 @@ We call aggregation those relationships whose **objects have an independent life **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; } @@ -127,6 +133,9 @@ We use the term composition to refer to relationships whose objects **don’t ha **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; From 9dfb86d3fbf3d4bf8a7b32e1a7e4378b0df85011 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 10:44:29 +0530 Subject: [PATCH 011/100] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 629b1bb..2341948 100644 --- a/README.md +++ b/README.md @@ -226,21 +226,21 @@ Java programs consists of classes, which contain platform-neutral bytecodes that ↥ back to top

-## Q. What is Classloader in Java? What are different types of classloaders? +## 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:** -**a) Bootstrap Class Loader**: +**1. 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. -**b) Extensions Class Loader**: +**2. 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. -**c) System Class Loader**: +**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. From 6d9c80c94cbfa00e21b9823a27d63c1b9943f896 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:12:24 +0530 Subject: [PATCH 012/100] Update README.md --- README.md | 95 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 70 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 2341948..fbf2a17 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,7 @@ class Engine { **1. Java Heap Space:** -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. +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. 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. @@ -208,7 +208,7 @@ As soon as method ends, the block becomes unused and become available for next m ## 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). +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. @@ -528,6 +528,7 @@ Calling parameterized constructor of derived ## 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. + ```java public class Test { public final static void main(String[] args) throws Exception { @@ -552,12 +553,14 @@ Cannot override the final method from Test. ## 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 -**Example of static Polymorphism** +1. Static Polymorphism also known as compile time polymorphism +2. Dynamic Polymorphism also known as runtime polymorphism + +**Example of 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. + ```java class SimpleCalculator { @@ -577,15 +580,16 @@ public class Demo System.out.println(obj.add(10, 20, 30)); } } + +// Output: +// 30 +// 60 ``` -Output: -``` -30 -60 -``` -**Runtime Polymorphism (or Dynamic polymorphism)** + +**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 { @@ -616,7 +620,8 @@ Overriding Method 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. -**Virtual function with Interface** +**Virtual function with Interface:** + ```java /** * The function applyBrakes() is virtual because @@ -638,7 +643,8 @@ class ACMEBicycle implements Bicycle { ## 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. +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. + ```java class SuperClass { SuperClass get() { @@ -702,6 +708,7 @@ public interface Test { ``` 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; @@ -720,6 +727,7 @@ public interface Test { ## 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(); @@ -929,11 +937,12 @@ There are 3 ways to get the instance of Class class. They are as follows: * getClass() method of Object class * the .class syntax -**1. forName() method of Class class** +**1. forName() method of Class class:** * 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{} @@ -948,9 +957,11 @@ Output ``` Simple ``` -**2. getClass() method of Object class** + +**2. getClass() method of Object class:** 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{} @@ -970,9 +981,10 @@ Output ``` Simple ``` -**3. The .class syntax** +**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 Test { public static void main(String args[]) { @@ -1093,6 +1105,7 @@ overridden method is static ## 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. + ```java class Demo { @@ -1115,6 +1128,7 @@ Exception in thread "main" java.lang.Error: Unresolved compilation problem: at beginnersbook.com.Demo.main(Details.java:10) ``` **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`). + ```java class Demo { //Blank final variable @@ -1138,6 +1152,7 @@ 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. + ```java class XYZ { final void demo() { @@ -1163,6 +1178,7 @@ class ABC extends XYZ { ## 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 { @@ -1214,6 +1230,7 @@ public class RegexExample { ## 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 { @@ -1241,6 +1258,7 @@ class ExternalProcessExample `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. **BufferedInputStreamExample.java** + ```java import java.io.BufferedInputStream; import java.io.File; @@ -1285,6 +1303,7 @@ Output This is an example of reading data from file ``` **BufferedOutputStreamExample.java** + ```java import java.io.BufferedOutputStream; import java.io.File; @@ -1331,6 +1350,7 @@ 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. + ```java import java.io.File; import java.io.IOException; @@ -1379,6 +1399,7 @@ public class FilePermissions { In Java, there are three different ways for reading input from the user in the command line environment(console). **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; @@ -1399,6 +1420,7 @@ public class Test } ``` **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. + ```java import java.util.Scanner; @@ -1419,7 +1441,9 @@ class GetInputFromUser } } ``` -**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()). + +**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 public class Sample { @@ -1437,6 +1461,7 @@ public class Sample ## 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 import java.io.FileOutputStream; import java.io.IOException; @@ -1517,9 +1542,9 @@ java.io.NotSerializableException: This class cannot be Serialized |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.| +| 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.| +| 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. |
@@ -1529,23 +1554,31 @@ java.io.NotSerializableException: This class cannot be Serialized ## 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()** + ```java MyObject anotherObject = new MyObject(); MyObject object = (MyObject) anotherObject.clone(); ``` + **4. Using object deserialization** + ```java ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); ``` + @@ -1615,6 +1648,7 @@ class UnboxingExample1 { 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: **Main.java** + ```java public class Main { public native int intMethod(int i); @@ -1624,7 +1658,9 @@ public class Main { } } ``` + **Main.c** + ```c #include #include "Main.h" @@ -1635,6 +1671,7 @@ JNIEXPORT jint JNICALL Java_Main_intMethod( } ``` **Compile and run** + ``` javac Main.java javah -jni Main @@ -1642,7 +1679,9 @@ gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \ -I${JAVA_HOME}/include/linux Main.c java -Djava.library.path=. Main ``` + Output + ``` 4 ``` @@ -1725,7 +1764,8 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h ## 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. +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. + ```java String a = "abc"; String b = "abc"; @@ -2142,7 +2182,7 @@ public class ClassLoaderTest { ## 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. +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. @@ -2182,7 +2222,7 @@ public class StringPool { 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 +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
↥ back to top @@ -2550,13 +2590,15 @@ In Java there are four types of references differentiated on the way by which th 1. Phantom 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. +**2. Weak Reference**: 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 @@ -2593,6 +2635,7 @@ 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 @@ -2629,6 +2672,7 @@ 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 @@ -3013,6 +3057,7 @@ public class MainClass { } } ``` + @@ -3028,8 +3073,8 @@ The Object class is the parent class of all the classes in java by default.
- - + + From 910ecadbaa2fd2fe007e716ddf980919fe131218 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:13:39 +0530 Subject: [PATCH 013/100] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fbf2a17..aef1d93 100644 --- a/README.md +++ b/README.md @@ -183,9 +183,9 @@ Garbage Collection runs on the heap memory to free the memory used by objects th **2. Java Stack Memory:** -Stack in java is a section of memory which contains methods, local variables and reference variables. Local variables are created in the stack. +Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. -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. +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. 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. From 599b8d0715bd9e5b0a78d40fb3b4a46c96af0323 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:27:54 +0530 Subject: [PATCH 014/100] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index aef1d93..cc70a8c 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ public class Person { **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. +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. @@ -179,7 +179,7 @@ class Engine { 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. -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. +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. **2. Java Stack Memory:** @@ -1785,8 +1785,8 @@ Immutable class means that once an object is created, we cannot change its conte **Rules to create immutable classes** -* 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) +* 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) @@ -1884,7 +1884,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ## 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. +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.
↥ back to top @@ -1942,7 +1942,7 @@ class TestExceptionPropagation { 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.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.
From 902a30ba0100183648e602d5c2b3277c92d970bc Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:32:25 +0530 Subject: [PATCH 015/100] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cc70a8c..0ae6caf 100644 --- a/README.md +++ b/README.md @@ -262,7 +262,9 @@ JVM is responsible for converting Byte code to the machine specific code. JVM is 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 Compiler +

+ Java Compiler +

↥ back to top From f867f4621f0c7bdc980012916a57b28f6f333c5b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:35:58 +0530 Subject: [PATCH 016/100] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0ae6caf..124d5d7 100644 --- a/README.md +++ b/README.md @@ -274,9 +274,12 @@ Java Runtime Environment provides a platform to execute java programs. JRE consi 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. -For example credit card validator factory which returns a different validator for each card type. +**Example:** credit card validator factory which returns a different validator for each card type. ```java +/** + * Abstract Factory Pattern + */ public ICardValidator GetCardValidator (string cardType) { switch (cardType.ToLower()) From 45abdc770866a6c4e73725fb21a00e0c7c8856f0 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:39:15 +0530 Subject: [PATCH 017/100] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 124d5d7..70826b4 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,7 @@ In Abstract Factory pattern an interface is responsible for creating a factory o ## 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 * java.util.AbstractMap From b45c3cadc92572a8a68ae7c514d2f45dd966d359 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:53:37 +0530 Subject: [PATCH 018/100] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 70826b4..fdd2619 100644 --- a/README.md +++ b/README.md @@ -322,6 +322,9 @@ Class inherits methods from the following classes in terms of HashMap 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 +/** + * Inner Class + */ class Outer { class Inner { public void show() { @@ -340,6 +343,9 @@ class Main { A subclass is class which inherits a method or methods from a superclass. ```java +/** + * Sub Class + */ class Car { //... } From ab0e0d4621e12133be40a6279def70868850075c Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:56:13 +0530 Subject: [PATCH 019/100] Update README.md --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index fdd2619..73633e1 100644 --- a/README.md +++ b/README.md @@ -321,6 +321,8 @@ Class inherits methods from the following classes in terms of HashMap 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 @@ -342,6 +344,8 @@ class Main { A subclass is class which inherits a method or methods from a superclass. +**Example:** + ```java /** * Sub Class @@ -365,7 +369,12 @@ class HybridCar extends Car { 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:** + ```java +/** + * Static Class Loading + */ class TestClass { public static void main(String args[]) { TestClass tc = new TestClass(); @@ -377,7 +386,12 @@ class TestClass { Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. +**Example:** + ```java +/** + * Dynamic Class Loading + */ Class.forName (String className); ``` From f65ae446f211abb1bd5ea2b5d46c6d04317ac959 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 19:57:44 +0530 Subject: [PATCH 020/100] Update README.md --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 73633e1..61636e6 100644 --- a/README.md +++ b/README.md @@ -405,7 +405,12 @@ Class.forName (String className); 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:** + ```java +/** + * Transient + */ public transient int limit = 55; // will not persist public int b; // will persist ``` @@ -414,7 +419,12 @@ public int b; // will persist 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. +**Example:** + ```java +/** + * Volatile + */ public class MyRunnable implements Runnable { private volatile boolean active; public void run() { From 4a3de2b169cbbe8b751b4798ca28f856f83a4159 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 20:00:50 +0530 Subject: [PATCH 021/100] Update README.md --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 61636e6..0f78d81 100644 --- a/README.md +++ b/README.md @@ -453,11 +453,16 @@ 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.
From 2c7e82046a75d920d4440d78687b18260b053b27 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 20:09:00 +0530 Subject: [PATCH 022/100] Update README.md --- README.md | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0f78d81..866c1ae 100644 --- a/README.md +++ b/README.md @@ -477,8 +477,10 @@ Java constructor chaining is a method of calling one constructor with the help o * **From base class**: By using `super()` keyword to call a constructor from the base class. ```java -// Java program to illustrate Constructor Chaining -// within same class Using this() keyword +/** + * Constructor Chaining + * within same class Using this() keyword + */ class Temp { // default constructor 1 @@ -508,15 +510,20 @@ class Temp } } ``` + Ouput: -``` + +```java 30 10 The Default constructor ``` + ```java -// Java program to illustrate Constructor Chaining to -// other class using super() keyword +/** + * Constructor Chaining to + * other class using super() keyword + */ class Base { String name; @@ -557,11 +564,14 @@ class Derived extends Base } } ``` + Output: -``` + +```java Calling parameterized constructor of base Calling parameterized constructor of derived ``` + From 71aeef1a30081a349d72dc004d4a1e5e02973029 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 20:29:25 +0530 Subject: [PATCH 023/100] Update README.md --- README.md | 90 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 866c1ae..2226dd7 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,11 @@ Calling parameterized constructor of derived ## 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. +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 { @@ -593,10 +597,13 @@ class Child extends Test { } } ``` + Output -``` + +```java Cannot override the final method from Test. ``` + @@ -605,64 +612,81 @@ Cannot override the final method from Test. 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 +1. Static Polymorphism also known as Compile time polymorphism +2. Runtime polymorphism also known as Dynamic Polymorphism -**Example of static 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 -class SimpleCalculator -{ +/** + * Static Polymorphism + */ +class SimpleCalculator { int add(int a, int b) { - return a + b; + return a + b; } - int add(int a, int b, int c) { - return a + b + c; + + 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)); - } +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 +Output + +```java +30 +60 ``` -**Runtime Polymorphism (or Dynamic polymorphism):** +**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. +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 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(); - } + public void myMethod() { + System.out.println("Overriding Method"); + } + + public static void main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } } ``` + Output: -``` + +```java Overriding Method ``` + From 694858285afb1d8a9eefaad1d13ecc9f0dc34016 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 20:35:13 +0530 Subject: [PATCH 024/100] Update README.md --- README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2226dd7..bf1ffda 100644 --- a/README.md +++ b/README.md @@ -695,23 +695,24 @@ Overriding Method 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. -**Virtual function with Interface:** +**Example:** Virtual function with Interface ```java /** -* The function applyBrakes() is virtual because -* functions in interfaces are designed to be overridden. -**/ -interface Bicycle { - void applyBrakes(); -} + * The function applyBrakes() is virtual because + * functions in interfaces are designed to be overridden. + **/ +interface Bicycle { + void applyBrakes(); +} class ACMEBicycle implements Bicycle { - public void applyBrakes(){ //Here we implement applyBrakes() - System.out.println("Brakes applied"); //function + public void applyBrakes() { // Here we implement applyBrakes() + System.out.println("Brakes applied"); // function } } ``` + From d82c46bb7363df84f1c071797f067468b8ec9809 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Tue, 20 Sep 2022 20:38:07 +0530 Subject: [PATCH 025/100] Update README.md --- README.md | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index bf1ffda..94664a2 100644 --- a/README.md +++ b/README.md @@ -721,28 +721,38 @@ class ACMEBicycle implements Bicycle { 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; - } + 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(); - } + Tester get() { + System.out.println("SubClass"); + return this; + } + + public static void main(String[] args) { + SuperClass tester = new Tester(); + tester.get(); + } } ``` + Output: -``` + +```java Subclass ``` + From cda5d8792dbb81a3d7de1ccbcd6580a38e3fae80 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 05:14:55 +0530 Subject: [PATCH 026/100] Update README.md --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 94664a2..d52f1f5 100644 --- a/README.md +++ b/README.md @@ -693,7 +693,7 @@ Overriding Method ## 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. +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. **Example:** Virtual function with Interface @@ -759,9 +759,11 @@ Subclass ## 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. +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:**
AggregationComposition
Aggregation is a weak Association.Composition is a strong Association.
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 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).
From 62ac57b06a891bf6f49e307ab3ddc2736fd24ee5 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 05:20:08 +0530 Subject: [PATCH 027/100] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d52f1f5..ac98996 100644 --- a/README.md +++ b/README.md @@ -804,8 +804,9 @@ public interface Test { 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** + +* 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**
From 252f97d36cc03957276636517e7af54826f70b51 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 05:35:03 +0530 Subject: [PATCH 028/100] Update README.md --- README.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ac98996..26e0391 100644 --- a/README.md +++ b/README.md @@ -815,25 +815,29 @@ public interface Test { ## 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 +An interface reference can point to any object of a class that implements this interface ```java -interface Foo { - void display(); +/** + * Interface + */ +interface MyInterface { + void display(); } -public class TestFoo implements Foo { +public class TestInterface implements MyInterface { void display() { - System.out.println("Hello World"); + System.out.println("Hello World"); } public static void main(String[] args) { - Foo foo = new TestFoo(); - foo.display(); + MyInterface myInterface = new TestInterface(); + MyInterface.display(); } } -``` +``` + From c979bb3124c1061166cc03cb174906baa433734c Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 05:40:25 +0530 Subject: [PATCH 029/100] Update README.md --- README.md | 101 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 58 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 26e0391..a597ac8 100644 --- a/README.md +++ b/README.md @@ -849,64 +849,79 @@ 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. -**Byte Streams** +**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; + 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(); - } - } - } + 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(); + } + } + } } ``` -**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. + +**2. 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. + +**Example:** ```java +/** + * Character Streams + */ import java.io.*; + public class CopyFile { - public static void main(String args[]) throws IOException { - FileReader in = null; - FileWriter out = null; + 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(); - } - } - } + 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(); + } + } + } } ``` From b685ad7c869190c64b385d70b6fdc56e84c1f0e5 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 05:43:34 +0530 Subject: [PATCH 030/100] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a597ac8..04bea39 100644 --- a/README.md +++ b/README.md @@ -889,7 +889,7 @@ public class CopyFile { **2. 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. +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:** From b4a7d5e2759b41898be4ae53567e87e9b1774190 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:04:18 +0530 Subject: [PATCH 031/100] Update README.md --- README.md | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 04bea39..6517175 100644 --- a/README.md +++ b/README.md @@ -931,9 +931,41 @@ public class CopyFile { ## 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. +**1. Runtime Class:** -**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. +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(); + } + } +} +``` + +**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 From 8df1a9a748b59e1e3152f55d3661758bb3cc412d Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:08:27 +0530 Subject: [PATCH 032/100] Update README.md --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 6517175..5f8e7ff 100644 --- a/README.md +++ b/README.md @@ -973,11 +973,13 @@ The purpose of the System class is to provide access to system resources. It con ## 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. +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. The assert statement is used with a Boolean expression and can be written in two different ways. -``` +```java // First way assert expression; @@ -988,12 +990,15 @@ assert expression1 : expression2; **Example:** ```java +/** + * 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); - } + public static void main(String[] args) { + int age = 14; + assert age <= 18 : "Cannot Vote"; + System.out.println("The voter's age is " + age); + } } ``` From 94d517cec0f2cd0e15df0aff6d5cb662ee86be32 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:13:03 +0530 Subject: [PATCH 033/100] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5f8e7ff..2c373dd 100644 --- a/README.md +++ b/README.md @@ -1008,18 +1008,18 @@ public class Example { ## 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. - -|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.| +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.| +|The abstract keyword is used to declare abstract class.|The interface keyword is used to declare interface.| +|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.|
↥ back to top From 839824f62b27933074ecaf8b592197ae60622911 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:17:11 +0530 Subject: [PATCH 034/100] Update README.md --- README.md | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2c373dd..743931c 100644 --- a/README.md +++ b/README.md @@ -1013,7 +1013,7 @@ Abstract class and interface both are used to achieve abstraction where we can d |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 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.| |The abstract keyword is used to declare abstract class.|The interface keyword is used to declare interface.| @@ -1836,15 +1836,15 @@ Output ## 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. +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** +**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. +* Don\'t allow subclasses to override methods. ```java public class DateContainer { @@ -1928,7 +1928,7 @@ System.out.println(c == d); // false 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** +**Rules to create immutable classes:** * 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) @@ -2085,9 +2085,13 @@ class TestExceptionPropagation { ## 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.
@@ -2098,7 +2102,8 @@ Some of the common main thread exception are as follows: **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. -**Throw Example** +**Throw Example:** + ```java public class ThrowExample { void checkAge(int age) { @@ -2114,14 +2119,18 @@ public class ThrowExample { } } ``` + 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) ``` -**Throws Example** + +**Throws Example:** + ```java public class ThrowsExample { int division(int a, int b) throws ArithmeticException { @@ -2139,10 +2148,13 @@ public class ThrowsExample { } } ``` + Output + +```java +You shouldn\'t divide number by zero ``` -You shouldn't divide number by zero -``` + @@ -2739,7 +2751,7 @@ In Java there are four types of references differentiated on the way by which th ```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. +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. 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. @@ -2980,7 +2992,7 @@ public class MainClass { `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-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. From 3fa81dd7134cf9a330df882dfcdd2f5776897457 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:19:07 +0530 Subject: [PATCH 035/100] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 743931c..bf399b3 100644 --- a/README.md +++ b/README.md @@ -1016,7 +1016,6 @@ Abstract class and interface both are used to achieve abstraction where we can d |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.| -|The abstract keyword is used to declare abstract class.|The interface keyword is used to declare interface.| |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.| From e74c7b7a3f27544f803a4da403388d9f467add63 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 06:24:28 +0530 Subject: [PATCH 036/100] Update README.md --- README.md | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index bf399b3..66aebaf 100644 --- a/README.md +++ b/README.md @@ -1028,12 +1028,16 @@ Abstract class and interface both are used to achieve abstraction where we can d The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. -**Use of Wrapper classes in Java** +**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 | @@ -1050,23 +1054,27 @@ The wrapper class in Java provides the mechanism to convert primitive into objec **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); - } -} +/** + * 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 ``` + From e0fb9aed25b0dc0c5464cd164438c155175f630b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:17:35 +0530 Subject: [PATCH 037/100] Update README.md --- README.md | 76 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 66aebaf..0918a80 100644 --- a/README.md +++ b/README.md @@ -1081,63 +1081,80 @@ Output ## 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. +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. They are as follows: +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 of Class class:** +**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 -class Simple{} - -class Test { - public static void main(String args[]) { - Class c = Class.forName("Simple"); - System.out.println(c.getName()); - } -} +/** + * 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 of Object class:** +**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 -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); - } -} +/** + * 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. +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; @@ -1148,9 +1165,10 @@ class Test { } } ``` + Output -``` +```java boolean Test ``` From 6008da016b177d45afa0cad943b9b4d9cf7d892e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:18:38 +0530 Subject: [PATCH 038/100] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0918a80..dd33e74 100644 --- a/README.md +++ b/README.md @@ -1081,9 +1081,9 @@ Output ## 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. +Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at **runtime**. -There are 3 ways to get the instance of Class class. +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 From 354f73ca4e9efaf7e22eed14a11c4b3d9d70c0b1 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:30:41 +0530 Subject: [PATCH 039/100] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd33e74..b987d5a 100644 --- a/README.md +++ b/README.md @@ -3276,9 +3276,9 @@ The Object class is the parent class of all the classes in java by default. #### 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? -#### Q. What is a copy constructor in Java? #### Q. What are the different access specifiers available in java? #### Q. What is runtime polymorphism in java? +#### Q. What is a private constructor? *ToDo* From 030979338406b55a1eb2328458e0553e85d722cd Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:35:18 +0530 Subject: [PATCH 040/100] Update README.md --- README.md | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index b987d5a..aac596e 100644 --- a/README.md +++ b/README.md @@ -1189,14 +1189,17 @@ In Java, a constructor is a block of codes similar to the method. It is called w **Example:** Default Constructor (or) no-arg constructor ```java -public class Car -{ +/** + * Default Constructor + */ +public class Car { Car() { - System.out.println("Default Constructor of Car class called"); + System.out.println("Default Constructor of Car class called"); } + public static void main(String args[]) { - //Calling the default constructor - Car c = new Car(); + // Calling the default constructor + Car c = new Car(); } } ``` @@ -1210,20 +1213,24 @@ Default Constructor of Car class called **Example:** Parameterized Constructor ```java -public class Car -{ +/** + * Parameterized Constructor + */ +public class Car { String carColor; + Car(String carColor) { this.carColor = carColor; } - - public void disp() { - System.out.println("Color of the Car is : "+carColor); + + public void display() { + System.out.println("Color of the Car is : " + carColor); } + public static void main(String args[]) { - //Calling the parameterized constructor + // Calling the parameterized constructor Car c = new Car("Blue"); - c.disp(); + c.display(); } } ``` From 8b4d41f1fd54153c3f616ddb151885695b5f72b2 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:44:38 +0530 Subject: [PATCH 041/100] Update README.md --- README.md | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index aac596e..a51e739 100644 --- a/README.md +++ b/README.md @@ -1243,31 +1243,39 @@ public class Car { 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 ```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() ^ @@ -1275,6 +1283,7 @@ overridden method is static 1 error ``` + From e2994e56834d86b84f1b656206084cc20af89c2a Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 08:45:03 +0530 Subject: [PATCH 042/100] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a51e739..6758bed 100644 --- a/README.md +++ b/README.md @@ -1251,6 +1251,8 @@ There are a few restrictions imposed on a static method * 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 From 91564dc45ef4a7f1c1fa09f204d91bfc187bb0ad Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 09:34:03 +0530 Subject: [PATCH 043/100] Update README.md --- README.md | 120 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 76 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 6758bed..7fc8afc 100644 --- a/README.md +++ b/README.md @@ -1292,73 +1292,105 @@ overridden method is static ## 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. +**1. Final Variable:** + +Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. + +**Example:** ```java -class Demo { +/** + * 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(); - } + final int MAX_VALUE = 99; + + void myMethod() { + MAX_VALUE = 101; + } + + public static void main(String args[]) { + Demo obj = new Demo(); + obj.myMethod(); + } } ``` + Output -``` + +```java 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) ``` -**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`). + +**2. 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` ). + +**Example:** ```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(); - } +/** + * Blank final variable + */ +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(); + } } ``` + Output -``` + +```java 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. + +**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 -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(); - } +/** + * Final Method + */ +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(); + } } ``` + From 0801c16fba451b68910b3a4544e9c4e266abdf7c Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 09:37:58 +0530 Subject: [PATCH 044/100] Update README.md --- README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7fc8afc..1d97bd4 100644 --- a/README.md +++ b/README.md @@ -1400,15 +1400,20 @@ class ABC extends XYZ { 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.*; +/** + * 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"); - } -} + public static void main(String args[]) { + out.println("Hello");// Now no need of System.out + out.println("Java"); + } +} ``` + From f93ce98c3ac95dde9c52fa3a46270ff73712518f Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 09:41:10 +0530 Subject: [PATCH 045/100] Update README.md --- README.md | 45 ++++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 1d97bd4..4fbafd1 100644 --- a/README.md +++ b/README.md @@ -1420,34 +1420,41 @@ class StaticImportExample { ## 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. +The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. -**java.util.regex package** +**Regular Expression Package:** * 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); - } -} +/** + * Regular Expression + */ +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); + } +} ``` + From 1003d458c160eede265391eedee987cdbfea7468 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 09:53:31 +0530 Subject: [PATCH 046/100] Update README.md --- README.md | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 4fbafd1..64c7b8c 100644 --- a/README.md +++ b/README.md @@ -1437,20 +1437,13 @@ The Java Regex or Regular Expression is an API to define a pattern for searching */ import java.util.regex.*; -public class RegexExample { +public class Index { 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(); + // Pattern, String + boolean b = Pattern.matches(".s", "as"); - // 3rd way - boolean b3 = Pattern.matches(".s", "as"); - - System.out.println(b + " " + b2 + " " + b3); + System.out.println("Match: " + b); } } ``` From 505f4ab0fe812962c38aab06585812582e945845 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 10:03:48 +0530 Subject: [PATCH 047/100] Update README.md --- README.md | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 64c7b8c..958f6bf 100644 --- a/README.md +++ b/README.md @@ -1454,16 +1454,21 @@ public class Index { ## Q. How will you invoke any external process in Java? -We can invoke the external process in Java using **exec()** method of **Runtime Class**. +In java, external process can be invoked using **exec()** method of **Runtime Class**. + +**Example:** ```java -class ExternalProcessExample -{ +/** + * exec() + */ +import java.io.IOException; + +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"; + String command = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; // Running the above command Runtime run = Runtime.getRuntime(); @@ -1471,9 +1476,10 @@ class ExternalProcessExample } catch (IOException e) { e.printStackTrace(); } - } -} + } +} ``` + From 025207610cda48f43b7052e740a6ad948afd91e9 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 10:08:30 +0530 Subject: [PATCH 048/100] Update README.md --- README.md | 128 +++++++++++++++++++++++++++++------------------------- 1 file changed, 70 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index 958f6bf..781dc44 100644 --- a/README.md +++ b/README.md @@ -1488,9 +1488,12 @@ class ExternalProcessExample { `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. -**BufferedInputStreamExample.java** +**Example:** ```java +/** + * BufferedInputStream + */ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -1498,44 +1501,50 @@ 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; + 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(); - } - } - } + 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 ``` -**BufferedOutputStreamExample.java** + +**Example:** ```java +/** + * BufferedOutputStream + */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; @@ -1543,37 +1552,40 @@ 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(); - } - } - } + 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 -``` + +Output + +```java This is an example of writing data to a file ``` + From d8833580f0831de9e6237a5c172927b1fcc94a14 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 10:12:45 +0530 Subject: [PATCH 049/100] Update README.md --- README.md | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 781dc44..ba340f4 100644 --- a/README.md +++ b/README.md @@ -1592,9 +1592,14 @@ 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. +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; @@ -1607,32 +1612,36 @@ 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 + + // 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 + + // using PosixFilePermission to set file permissions 777 Set perms = new HashSet(); - //add owners permission + + // add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); - //add group permissions + + // add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); - //add others permissions + + // 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); } } ``` + From 9d5cc3e4f29cb31ba1c8ebaf758edd1757372b59 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 10:43:59 +0530 Subject: [PATCH 050/100] Update README.md --- README.md | 108 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 61 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index ba340f4..ec8180f 100644 --- a/README.md +++ b/README.md @@ -1631,7 +1631,7 @@ public class FilePermissions { 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); @@ -1648,64 +1648,78 @@ public class FilePermissions { ## 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). +In Java, there are three different ways for reading input from the user in the command line environment ( console ). + +**1. Using Buffered Reader Class:** -**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. +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); - } -} +/** + * Buffered Reader Class + */ +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); + } +} ``` -**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. + +**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. ```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); - } -} +/** + * 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); + } +} ``` -**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()). +**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 -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); - } +/** + * 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); + } } ``` + From e00136ac596f284402c2bdd3db2b047f1fbd58c4 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 10:47:22 +0530 Subject: [PATCH 051/100] Update README.md --- README.md | 64 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index ec8180f..3a950ba 100644 --- a/README.md +++ b/README.md @@ -1726,9 +1726,12 @@ public class Sample { ## 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. +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; @@ -1738,52 +1741,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) @@ -1798,6 +1803,7 @@ java.io.NotSerializableException: This class cannot be Serialized at java.io.ObjectOutputStream.writeObject(Unknown Source) at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) ``` + From 435d28ede9b5566c8a43cb0ab463140c251df3ec Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:41:24 +0530 Subject: [PATCH 052/100] Update README.md --- README.md | 90 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 52 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 3a950ba..1783fc6 100644 --- a/README.md +++ b/README.md @@ -1811,13 +1811,13 @@ java.io.NotSerializableException: This class cannot be Serialized ## 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. |
↥ back to top @@ -1825,26 +1825,26 @@ java.io.NotSerializableException: This class cannot be Serialized ## Q. What are the ways to instantiate the Class class? -**1. Using new keyword** +**1. Using new keyword:** ```java MyObject object = new MyObject(); ``` -**2. Using Class.forName()** +**2. Using Class.forName():** ```java MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); ``` -**3. Using clone()** +**3. Using clone():** ```java MyObject anotherObject = new MyObject(); MyObject object = (MyObject) anotherObject.clone(); ``` -**4. Using object deserialization** +**4. Using object deserialization:** ```java ObjectInputStream inStream = new ObjectInputStream(anInputStream ); @@ -1857,60 +1857,74 @@ MyObject object = (MyObject) inStream.readObject(); ## 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. +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 -class Simple { - public static void main(String args[]) { - System.out.println("Hello World"); - } -} -``` + /** + * 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[]); } ``` + -## Q. What are autoboxing and unboxing? When does it occur? +## Q. What are autoboxing and unboxing? 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 -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); - } -} +/** + * 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); + } +} ``` -**Example:** Unboxing +**Example:** Unboxing ```java -class UnboxingExample1 { - public static void main(String args[]) { - Integer i = new Integer(50); - int a = i; - - System.out.println(a); - } -} +/** + * Unboxing + */ +class UnboxingExample { + public static void main(String args[]) { + Integer i = new Integer(50); + int a = i; + + System.out.println(a); + } +} ``` + From 176d3b777950cb0bbb0bc5dc5efdc531ebc7d349 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:44:11 +0530 Subject: [PATCH 053/100] Update README.md --- README.md | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 1783fc6..63cecf2 100644 --- a/README.md +++ b/README.md @@ -1933,19 +1933,20 @@ class UnboxingExample { 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: -**Main.java** +**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)); - } + public native int intMethod(int i); + + public static void main(String[] args) { + System.loadLibrary("Main"); + System.out.println(new Main().intMethod(2)); + } } ``` -**Main.c** +**Main.c:** ```c #include @@ -1956,9 +1957,10 @@ JNIEXPORT jint JNICALL Java_Main_intMethod( return i * i; } ``` -**Compile and run** -``` +**Compile and Run:** + +```java javac Main.java javah -jni Main gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \ @@ -1968,9 +1970,10 @@ java -Djava.library.path=. Main Output -``` +```java 4 ``` + From 67b9bdd5aa8cc333183e680554a3c3d5e3280f64 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:46:31 +0530 Subject: [PATCH 054/100] Update README.md --- README.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 63cecf2..ae31518 100644 --- a/README.md +++ b/README.md @@ -1978,7 +1978,7 @@ Output ↥ back to top
-## Q. What is immutable object? Can you write immutable object? +## 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. @@ -1991,16 +1991,22 @@ Immutable objects are objects that don\'t change. A Java immutable object must h * 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()); - } + private final Date date; + + public DateContainer() { + this.date = new Date(); + } + + public Date getDate() { + return new Date(date.getTime()); + } } ``` + From ecf7526676d4cac7592418c989b516d775912a0b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:49:24 +0530 Subject: [PATCH 055/100] Update README.md --- README.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ae31518..492d04e 100644 --- a/README.md +++ b/README.md @@ -2015,28 +2015,37 @@ public class DateContainer { 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 +**Example:** Inheritance ```java +/** + * Inheritance + */ class Fruit { - //... + // ... } + class Apple extends Fruit { - //... + // ... } ``` -**Example:** Composition +**Example:** Composition ```java +/** + * Composition + */ class Fruit { - //... + // ... } + class Apple { - private Fruit fruit = new Fruit(); - //... + private Fruit fruit = new Fruit(); + // ... } ``` + From a14f619ec094435b5e09bbb491be6c1dd3c73233 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:53:37 +0530 Subject: [PATCH 056/100] Update README.md --- README.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 492d04e..b447420 100644 --- a/README.md +++ b/README.md @@ -2052,7 +2052,7 @@ class Apple { ## 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. +DOM and SAX parser are extensively used to read and parse XML file in java and have their own set of advantage and disadvantage. | |DOM (Document Object Model) |Parser SAX (Simple API for XML) Parser | |-----------------|--------------------------------|--------------------------------------------------| @@ -2068,17 +2068,26 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h ## 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. +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 ``` + From 79e749ad562086f168fdcec064cec2117343bc01 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:55:36 +0530 Subject: [PATCH 057/100] Update README.md --- README.md | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b447420..e896473 100644 --- a/README.md +++ b/README.md @@ -2094,29 +2094,34 @@ System.out.println(c == d); // false ## 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. +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 (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) +* 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) +* No setters ( To not have the option to change the value of the instance variable ) ```java -public final class Employee { +/** + * Immutable Class + */ +public final class Employee { - final String pancardNumber; - - public Employee(String pancardNumber) { - this.pancardNumber = pancardNumber; - } - public String getPancardNumber() { - return pancardNumber; - } -} + final String pancardNumber; + + public Employee(String pancardNumber) { + this.pancardNumber = pancardNumber; + } + + public String getPancardNumber() { + return pancardNumber; + } +} ``` + From a8fa2a1b79003d7aff199f4892a6397039ab3092 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 19:57:21 +0530 Subject: [PATCH 058/100] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e896473..fe79229 100644 --- a/README.md +++ b/README.md @@ -2094,15 +2094,15 @@ System.out.println(c == d); // false ## 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. +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 (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 ) +* 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 ( To not have the option to change the value of the instance variable ) +* No setters ```java /** From 1dcb22f4548a8ebb54609e20e9a9e9109a14b16e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 20:02:03 +0530 Subject: [PATCH 059/100] Update README.md --- README.md | 47 +++++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index fe79229..4cf5b11 100644 --- a/README.md +++ b/README.md @@ -2128,33 +2128,44 @@ public final class Employee { ## 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. +**1. Mutability Difference:** -**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. +`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. -**Example:** StringBuffer +**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 -public class BufferTest{ - public static void main(String[] args){ - StringBuffer buffer=new StringBuffer("Hello"); - buffer.append(" World"); - System.out.println(buffer); - } -} +/** + * StringBuffer + */ +public class BufferTest { + public static void main(String[] args) { + StringBuffer buffer = new StringBuffer("Hello"); + buffer.append(" World"); + System.out.println(buffer); + } +} ``` -**Example:** StringBuilder +**Example:** ```java -public class BuilderTest{ - public static void main(String[] args){ - StringBuilder builder=new StringBuilder("Hello"); - builder.append(" World"); - System.out.println(builder); - } -} +/** + * StringBuilder + */ +public class BuilderTest { + public static void main(String[] args) { + StringBuilder builder = new StringBuilder("Hello"); + builder.append(" World"); + System.out.println(builder); + } +} ``` + From b17bd7b0df0464f574fa5559593fed55fcf1f149 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 20:13:04 +0530 Subject: [PATCH 060/100] Update README.md --- README.md | 98 ++++--------------------------------------------------- 1 file changed, 7 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index 4cf5b11..797a78c 100644 --- a/README.md +++ b/README.md @@ -2923,29 +2923,15 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ## 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 - -**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() { @@ -2970,84 +2956,14 @@ 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 - } -} +Weak Reference Example! +Weak Reference Example! ``` + From d1a9844d13b896772a28c8377023465082daf3c4 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 21 Sep 2022 20:22:37 +0530 Subject: [PATCH 061/100] Update README.md --- README.md | 159 +++++++++++++++++++++++++++--------------------------- 1 file changed, 80 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index 797a78c..dd6cafd 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ *Click if you like the project. Pull Request are highly appreciated.* -## Table of Contents +## Related Interview Questions * *[Java 8 Interview Questions](java8-questions.md)* * *[Multithreading Interview Questions](multithreading-questions.md)* @@ -15,6 +15,7 @@ * *[Servlets Interview Questions](servlets-questions.md)* * *[Java Design Pattern Questions](java-design-pattern-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* +* *[Spring Interview Questions](https://github.com/learning-zone/spring-interview-questions)*
@@ -35,7 +36,7 @@ The classes which inherit **RuntimeException** are known as unchecked exceptions Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. ## Q. Explain hierarchy of Java Exception classes? @@ -102,7 +103,7 @@ public class CustomExceptionExample { ``` ## Q. What is the difference between aggregation and composition? @@ -170,7 +171,7 @@ class Engine { *Note: "final" keyword is used in Composition to make sure child variable is initialized.* ## Q. What is difference between Heap and Stack Memory in java? @@ -203,7 +204,7 @@ As soon as method ends, the block becomes unused and become available for next m |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 | ## Q. What is JVM and is it platform independent? @@ -213,7 +214,7 @@ Java Virtual Machine (JVM) is a specification that provides runtime environment 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. ## Q. What is JIT compiler in Java? @@ -223,7 +224,7 @@ The Just-In-Time (JIT) compiler is a component of the runtime environment that i 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. ## Q. What is Classloader in Java? @@ -245,7 +246,7 @@ It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` di It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options. ## Q. Java Compiler is stored in JDK, JRE or JVM? @@ -267,7 +268,7 @@ Java Runtime Environment provides a platform to execute java programs. JRE consi

## Q. What is the difference between factory and abstract factory pattern? @@ -300,7 +301,7 @@ Abstract Factory patterns work around a super-factory which creates other factor 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. What are the methods used to implement for key Object in HashMap? @@ -314,7 +315,7 @@ Class inherits methods from the following classes in terms of HashMap * java.util.Map ## Q. What is difference between the Inner Class and Sub Class? @@ -360,7 +361,7 @@ class HybridCar extends Car { ``` ## Q. Distinguish between static loading and dynamic class loading? @@ -396,7 +397,7 @@ Class.forName (String className); ``` ## Q. What is the difference between transient and volatile variable in Java? @@ -439,7 +440,7 @@ public class MyRunnable implements Runnable { ``` ## Q. How many types of memory areas are allocated by JVM? @@ -466,7 +467,7 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l **6. Native Method Stack**: It contains all the native methods used in the application. ## Q. How can constructor chaining be done using this keyword? @@ -573,7 +574,7 @@ Calling parameterized constructor of derived ``` ## Q. Can you declare the main method as final? @@ -605,7 +606,7 @@ Cannot override the final method from Test. ``` ## Q. What is the difference between compile-time polymorphism and runtime polymorphism? @@ -688,7 +689,7 @@ Overriding Method ``` ## Q. Can you have virtual functions in Java? @@ -714,7 +715,7 @@ class ACMEBicycle implements Bicycle { ``` ## Q. What is covariant return type? @@ -754,7 +755,7 @@ Subclass ``` ## Q. What is the difference between abstraction and encapsulation? @@ -780,7 +781,7 @@ Abstraction is about hiding unwanted details while giving out most essential det
AbstractionEncapsulation
- ↥ back to top + ↥ back to top
## Q. Can we use private or protected member variables in an interface? @@ -810,7 +811,7 @@ public interface Test { * 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 + ↥ back to top
## Q. When can an object reference be cast to a Java interface reference? @@ -839,7 +840,7 @@ public class TestInterface implements MyInterface { ```
- ↥ back to top + ↥ back to top
## Q. Give the hierarchy of InputStream and OutputStream classes? @@ -926,7 +927,7 @@ public class CopyFile { ```
- ↥ back to top + ↥ back to top
## Q. What is the purpose of the Runtime class and System class? @@ -968,7 +969,7 @@ public class RuntimeTest 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 + ↥ back to top
## Q. What are assertions in Java? @@ -1003,7 +1004,7 @@ public class Example { ```
- ↥ back to top + ↥ back to top
## Q. What is the difference between abstract class and interface? @@ -1021,7 +1022,7 @@ Abstract class and interface both are used to achieve abstraction where we can d |A Java abstract class can have class members like private, protected, etc.|Members of a Java interface are public by default.|
- ↥ back to top + ↥ back to top
## Q. What are Wrapper classes? @@ -1076,7 +1077,7 @@ Output ```
- ↥ back to top + ↥ back to top
## Q. What is Java Reflection API? @@ -1174,7 +1175,7 @@ Test ```
- ↥ back to top + ↥ back to top
## Q. How many types of constructors are used in Java? @@ -1236,7 +1237,7 @@ public class Car { ```
- ↥ back to top + ↥ back to top
## Q. What are the restrictions that are applied to the Java static methods? @@ -1287,7 +1288,7 @@ overridden method is static ```
- ↥ back to top + ↥ back to top
## Q. What is the final variable, final class, and final blank variable? @@ -1392,7 +1393,7 @@ class ABC extends XYZ { ```
- ↥ back to top + ↥ back to top
## Q. What is the static import? @@ -1415,7 +1416,7 @@ class StaticImportExample { ```
- ↥ back to top + ↥ back to top
## Q. Name some classes present in java.util.regex package? @@ -1449,7 +1450,7 @@ public class Index { ```
- ↥ back to top + ↥ back to top
## Q. How will you invoke any external process in Java? @@ -1481,7 +1482,7 @@ class ExternalProcessExample { ```
- ↥ back to top + ↥ back to top
## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? @@ -1587,7 +1588,7 @@ This is an example of writing data to a file ```
- ↥ back to top + ↥ back to top
## Q. How to set the Permissions to a file in Java? @@ -1643,7 +1644,7 @@ public class FilePermissions { ```
- ↥ back to top + ↥ back to top
## Q. In Java, How many ways you can take input from the console? @@ -1721,7 +1722,7 @@ public class Sample { ```
- ↥ back to top + ↥ back to top
## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface? @@ -1805,7 +1806,7 @@ java.io.NotSerializableException: This class cannot be Serialized ```
- ↥ back to top + ↥ back to top
## Q. What is the difference between Serializable and Externalizable interface? @@ -1820,7 +1821,7 @@ java.io.NotSerializableException: This class cannot be Serialized |Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. |
- ↥ back to top + ↥ back to top
## Q. What are the ways to instantiate the Class class? @@ -1852,7 +1853,7 @@ MyObject object = (MyObject) inStream.readObject(); ```
- ↥ back to top + ↥ back to top
## Q. What is the purpose of using javap? @@ -1885,7 +1886,7 @@ class Simple { ```
- ↥ back to top + ↥ back to top
## Q. What are autoboxing and unboxing? @@ -1926,7 +1927,7 @@ class UnboxingExample { ```
- ↥ back to top + ↥ back to top
## Q. What is a native method? @@ -1975,7 +1976,7 @@ Output ```
- ↥ back to top + ↥ back to top
## Q. What is immutable object? @@ -2008,7 +2009,7 @@ public class DateContainer { ```
- ↥ back to top + ↥ back to top
## Q. The difference between Inheritance and Composition? @@ -2047,7 +2048,7 @@ class Apple { ```
- ↥ back to top + ↥ back to top
## Q. The difference between DOM and SAX parser in Java? @@ -2063,7 +2064,7 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h |suitable |better suitable for smaller and efficient memory| SAX is suitable for larger XML doc|
- ↥ back to top + ↥ back to top
## Q. What is the difference between creating String as new() and literal? @@ -2089,7 +2090,7 @@ System.out.println(c == d); // false ```
- ↥ back to top + ↥ back to top
## Q. How can we create an immutable class in Java? @@ -2123,7 +2124,7 @@ public final class Employee { ```
- ↥ back to top + ↥ back to top
## Q. What is difference between String, StringBuffer and StringBuilder? @@ -2167,7 +2168,7 @@ public class BuilderTest { ```
- ↥ back to top + ↥ back to top
## Q. What is a Memory Leak? @@ -2208,7 +2209,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed * Through `finalize()` Methods * Calling `String.intern()` on Long String
- ↥ back to top + ↥ back to top
## Q. Why String is popular HashMap key in Java? @@ -2216,7 +2217,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed 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.
- ↥ back to top + ↥ back to top
## Q. What is difference between Error and Exception? @@ -2233,7 +2234,7 @@ Since String is immutable, its hashcode is cached at the time of creation and it |Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.|
- ↥ back to top + ↥ back to top
## Q. Explain about Exception Propagation? @@ -2263,7 +2264,7 @@ class TestExceptionPropagation { } ```
- ↥ back to top + ↥ back to top
## Q. What are different scenarios causing "Exception in thread main"? @@ -2279,7 +2280,7 @@ Some of the common main thread exception are as follows: * **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.
- ↥ back to top + ↥ back to top
## Q. What are the differences between throw and throws? @@ -2340,7 +2341,7 @@ You shouldn\'t divide number by zero ```
- ↥ back to top + ↥ back to top
## Q. The difference between Serial and Parallel Garbage Collector? @@ -2356,7 +2357,7 @@ Turn on the `-XX:+UseSerialGC` JVM argument to use the serial 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.
- ↥ back to top + ↥ back to top
## Q. What is difference between WeakReference and SoftReference in Java? @@ -2457,7 +2458,7 @@ public class Example } ```
- ↥ back to top + ↥ back to top
## Q. What is a compile time constant in Java? What is the risk of using it? @@ -2476,7 +2477,7 @@ They are replaced with actual values at compile time because compiler know their private final int x = 10; ```
- ↥ back to top + ↥ back to top
## Q. How bootstrap class loader works in java? @@ -2517,7 +2518,7 @@ public class ClassLoaderTest { } ```
- ↥ back to top + ↥ back to top
## Q. Why string is immutable in java? @@ -2528,7 +2529,7 @@ The string is Immutable in Java because String objects are cached in String pool Since string is immutable it can safely share between many threads and avoid any synchronization issues in java.
- ↥ back to top + ↥ back to top
## Q. What is Java String Pool? @@ -2556,7 +2557,7 @@ public class StringPool { } ```
- ↥ back to top + ↥ back to top
## Q. How Garbage collector algorithm works? @@ -2566,7 +2567,7 @@ Garbage collection works on **Mark** and **Sweep** algorithm. In Mark phase it d 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
- ↥ back to top + ↥ back to top
## Q. How to create marker interface? @@ -2604,7 +2605,7 @@ class Main { } ```
- ↥ back to top + ↥ back to top
## Q. How serialization works in java? @@ -2702,7 +2703,7 @@ public class SerialExample { ```
- ↥ back to top + ↥ back to top
## Q. Java Program to Implement Singly Linked List? @@ -2786,7 +2787,7 @@ Nodes of singly linked list: 10 20 30 40 ```
- ↥ back to top + ↥ back to top
## Q. While overriding a method can you throw another exception or broader exception? @@ -2819,7 +2820,7 @@ class B extends A { } ```
- ↥ back to top + ↥ back to top
## Q. What is checked, unchecked exception and errors? @@ -2906,7 +2907,7 @@ Java Result: 1 Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc.
- ↥ back to top + ↥ back to top
## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? @@ -2918,7 +2919,7 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. `NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time.
- ↥ back to top + ↥ back to top
## Q. What do we mean by weak reference? @@ -2965,7 +2966,7 @@ Weak Reference Example! ```
- ↥ back to top + ↥ back to top
## Q. What do you mean Run time Polymorphism? @@ -3027,7 +3028,7 @@ Output Overriding Method ```
- ↥ back to top + ↥ back to top
## 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? @@ -3035,7 +3036,7 @@ Overriding Method 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.
- ↥ back to top + ↥ back to top
## Q. What are the different types of JDBC Driver? @@ -3049,7 +3050,7 @@ 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.
- ↥ back to top + ↥ back to top
## Q. How Encapsulation concept implemented in JAVA? @@ -3084,7 +3085,7 @@ public class MainClass { } ```
- ↥ back to top + ↥ back to top
## Q. Do you know Generics? How did you used in your coding? @@ -3139,7 +3140,7 @@ Generic Class Example ! 100 ```
- ↥ back to top + ↥ back to top
## Q. What is difference between String, StringBuilder and StringBuffer? @@ -3195,7 +3196,7 @@ StringBuilder: World StringBuffer: World ```
- ↥ back to top + ↥ back to top
## Q. How can we create a object of a class without using new operator? @@ -3316,7 +3317,7 @@ public class MainClass { ```
- ↥ back to top + ↥ back to top
## Q. What are methods of Object Class? @@ -3339,7 +3340,7 @@ The Object class is the parent class of all the classes in java by default.
- ↥ back to top + ↥ back to top
#### Q. What is copyonwritearraylist in java? @@ -3358,7 +3359,7 @@ The Object class is the parent class of all the classes in java by default. *ToDo*
- ↥ back to top + ↥ back to top
From b04ed4b8d05fb46135cf73a76c8528e54985653c Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 10:34:17 +0530 Subject: [PATCH 062/100] Delete hibernate-questions.md --- hibernate-questions.md | 1854 ---------------------------------------- 1 file changed, 1854 deletions(-) delete mode 100644 hibernate-questions.md 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? - - From 4bee9b1fe10aa4f1527382d2e4960c784b3e5775 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 10:34:27 +0530 Subject: [PATCH 063/100] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd6cafd..2d83a70 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,6 @@ * *[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)* * *[Java Programs](java-programs.md)* * *[Java String Methods](java-string-methods.md)* @@ -16,6 +15,7 @@ * *[Java Design Pattern Questions](java-design-pattern-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* * *[Spring Interview Questions](https://github.com/learning-zone/spring-interview-questions)* +* *[Hibernate Interview Questions](https://github.com/learning-zone/hibernate-interview-questions)*
From 07749452d1cde85b79d18b3dcccb902bec13af7e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 10:42:20 +0530 Subject: [PATCH 064/100] Delete java-design-pattern-questions.md --- java-design-pattern-questions.md | 608 ------------------------------- 1 file changed, 608 deletions(-) delete mode 100644 java-design-pattern-questions.md 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? - - From 525b7a49da0e08d0cdf13c9def6945bafe3671ce Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 10:42:33 +0530 Subject: [PATCH 065/100] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d83a70..6fd5d73 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,10 @@ * *[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)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* * *[Spring Interview Questions](https://github.com/learning-zone/spring-interview-questions)* * *[Hibernate Interview Questions](https://github.com/learning-zone/hibernate-interview-questions)* +* *[Java Design Pattern Questions](https://github.com/learning-zone/java-design-patterns)*
From 31677ab81afaf4403cb9193c0dcecb6bc3f63a83 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 12:31:42 +0530 Subject: [PATCH 066/100] Update README.md --- README.md | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 6fd5d73..4d4934c 100644 --- a/README.md +++ b/README.md @@ -2182,25 +2182,31 @@ Some tools that do memory management to identifies useless objects or memeory le * JProbe * IBM Tivoli +**Example:** + ```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"); - } -} +/** + * Memory Leaks + */ +import java.util.Vector; + +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"); + } +} ``` + Output -``` + +```java Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ``` -**Types of Memory Leaks in Java** +**Types of Memory Leaks in Java:** * Memory Leak through static Fields * Unclosed Resources/connections @@ -2208,6 +2214,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed * Inner Classes that Reference Outer Classes * Through `finalize()` Methods * Calling `String.intern()` on Long String + From 32132ac7d6c1d13b3b2e8081ad3040ff4a8850ca Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 12:46:00 +0530 Subject: [PATCH 067/100] Update README.md --- README.md | 56 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 4d4934c..1a7758e 100644 --- a/README.md +++ b/README.md @@ -2219,14 +2219,6 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ↥ back to top -## 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 is difference between Error and Exception? @@ -2247,29 +2239,39 @@ Since String is immutable, its hashcode is cached at the time of creation and it ## 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 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..."); - } -} + 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(); + } +} ``` + From 5d46b29e6a3b1adaaf227f9e4ee71a49481e96c0 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 14:25:58 +0530 Subject: [PATCH 068/100] Update README.md --- README.md | 63 ++++++++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 1a7758e..749b383 100644 --- a/README.md +++ b/README.md @@ -2296,21 +2296,25 @@ Some of the common main thread exception are as follows: **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. -**Throw Example:** +**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"); - } +/** + * 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"); + } } ``` @@ -2323,23 +2327,26 @@ at Example1.checkAge(Example1.java:4) at Example1.main(Example1.java:10) ``` -**Throws Example:** +**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"); - } - } +/** + * 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"); + } + } } ``` From 08876493d4243a076db884159e5b11359be72fb7 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 14:28:10 +0530 Subject: [PATCH 069/100] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 749b383..66eb7fb 100644 --- a/README.md +++ b/README.md @@ -2362,13 +2362,13 @@ You shouldn\'t divide number by zero ## Q. The difference between Serial and Parallel Garbage Collector? -**Serial Garbage Collector** +**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. -**Parallel 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. From 4dbd2da9fba8798379d7bd761adf1b3525ec9587 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 14:50:26 +0530 Subject: [PATCH 070/100] Update README.md --- README.md | 143 +++++++++++++++++++++--------------------------------- 1 file changed, 56 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 66eb7fb..ce8e220 100644 --- a/README.md +++ b/README.md @@ -2378,101 +2378,70 @@ Parallel garbage collector is also called as throughput collector. It is the def ## 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. +**1. Weak References:** -* Strong References -* Weak References -* Soft References -* Phantom References +Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. -**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(); -``` +/** + * Weak Reference + */ +import java.lang.ref.WeakReference; -**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"); - } -} - -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(); - } -} -``` +class MainClass { + public void message() { + System.out.println("Weak References Example"); + } +} -**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"); - } -} - -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(); - } -} +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(); + } +} ``` -**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. + +**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 -//Java Code to illustrate Weak reference -import java.lang.ref.*; -class MainClass -{ - public void message() { - System.out.println("Phantom References Example"); - } -} - -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(); - } -} +/** + * Soft Reference + */ +import java.lang.ref.SoftReference; + +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. + SoftReference softref = new SoftReference(g); + g = null; + g = softref.get(); + g.message(); + } +} ``` + From bacf53eceb2d12be6f95b27ea5c829c0b743e737 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 14:51:55 +0530 Subject: [PATCH 071/100] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ce8e220..7cc3088 100644 --- a/README.md +++ b/README.md @@ -2422,7 +2422,7 @@ import java.lang.ref.SoftReference; class MainClass { public void message() { - System.out.println("Weak References Example"); + System.out.println("Soft References Example"); } } @@ -2432,7 +2432,7 @@ public class Example { MainClass g = new MainClass(); g.message(); - // Creating Weak Reference to MainClass-type object to which 'g' + // Creating Soft Reference to MainClass-type object to which 'g' // is also pointing. SoftReference softref = new SoftReference(g); g = null; From 2ac3fd06b4f476ecf0ffb92788ed8d27eb50ec77 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 14:55:36 +0530 Subject: [PATCH 072/100] Update README.md --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7cc3088..1083b51 100644 --- a/README.md +++ b/README.md @@ -2446,21 +2446,23 @@ public class Example { ↥ back to top -## Q. What is a compile time constant in Java? What is the risk of using it? +## Q. What is a compile time constant in Java? 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 +* Declared final +* Primitive or String +* Initialized within declaration +* Initialized with constant 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. + ```java private final int x = 10; ``` + From 092d10fed96ca14cf6e8794b5c89dab6f9bb0301 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 16:44:32 +0530 Subject: [PATCH 073/100] Update README.md --- README.md | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 1083b51..b6891da 100644 --- a/README.md +++ b/README.md @@ -2469,41 +2469,37 @@ private final int x = 10; ## 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: -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 -**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. -**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. +**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 +/** + * ClassLoader + */ import java.util.logging.Level; import java.util.logging.Logger; -/** - * Java program to demonstrate How ClassLoader works in Java - * - **/ - public class ClassLoaderTest { - + public static void main(String args[]) { - try { - //printing ClassLoader of this class - System.out.println("ClassLoader : "+ ClassLoaderTest.class.getClassLoader()); + 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()); + // 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); } } } ``` + From 68843842decb4453a7ef32118554f9c78c818cb3 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 17:02:28 +0530 Subject: [PATCH 074/100] Update README.md --- README.md | 49 ++++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index b6891da..8cb57b0 100644 --- a/README.md +++ b/README.md @@ -2505,9 +2505,8 @@ public class ClassLoaderTest { ## 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. +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. @@ -2516,7 +2515,6 @@ Since string is immutable it can safely share between many threads and avoid any ## 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. @@ -2524,30 +2522,30 @@ When we use double quotes to create a String, it first looks for String with the ```java /** -* Java program to illustrate String Pool -* -**/ + * 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 + + System.out.println("s1 == s2 :" + (s1 == s2)); // true + System.out.println("s1 == s3 :" + (s1 == s3)); // false } } ``` + ## 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 +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
↥ back to top @@ -2555,9 +2553,9 @@ There are methods like System.gc() and Runtime.gc() wh ## 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. +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: +**Syntax:** ```java public interface Interface_Name { @@ -2569,24 +2567,25 @@ public interface Interface_Name { ```java /** -* Java program to illustrate Maker Interface -* -**/ -interface Marker { } + * Maker Interface + */ +interface Marker { +} -class A implements Marker { - //do some task +class MakerExample implements Marker { + // do some task } class Main { - public static void main(String[] args) { - A obj = new A(); - if (obj instanceOf Marker){ - // do some task - } - } + public static void main(String[] args) { + MakerExample obj = new MakerExample(); + if (obj instanceOf Marker) { + // do some task + } + } } ``` + From 09b8e72d5cc3343da99c8c5ab6137089cbc39873 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 22 Sep 2022 17:07:33 +0530 Subject: [PATCH 075/100] Update README.md --- README.md | 152 ++++++++++++++++++++++++++---------------------------- 1 file changed, 73 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index 8cb57b0..f4ce663 100644 --- a/README.md +++ b/README.md @@ -2598,89 +2598,83 @@ Serialization is a mechanism of converting the state of an object into a byte st ```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; +* 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 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(); - 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(); + + "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"); - } - } + + "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"); + } + } } ``` From baf2493d0b031aeade8c2e0611457e3c403d4d0d Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Fri, 23 Sep 2022 15:48:26 +0530 Subject: [PATCH 076/100] Collections Interview Questions --- assets/collection.png | Bin 140922 -> 53894 bytes collections-questions.md | 160 ++++++++++++++++++++------------------- 2 files changed, 84 insertions(+), 76 deletions(-) diff --git a/assets/collection.png b/assets/collection.png index 73617230014004ec39f490d8fde07be5b2fbb40d..663721d128a0fea437f3a3c72d51385deb836cc4 100644 GIT binary patch literal 53894 zcmeFZXH-<%+9p~GijozP46;FjO3oQU$w@%6ppr#$js+;7NKm5W97RxaE`or7Q zk#kWLsqS3tv(I;Wbl=hUc8`01_5M>E*IIMU`OY^!?=#nX4K;Zpd}@3c3`V4=@JJH| zyFvnkU2eK|75s}t`deuj%pa!s=%Kd9#Kswc!?UH7JIBQhpBTjGnH*jcFb-(ESZgO` zvBP_F`X}+=GpWH)&GMWLnSwu~;8V_>rOVD6^t9>zpNWevvvgz|;fYbvUvHMIH#%6! zW-NxiVYo~dIppH+e2?Fb`K@fAqjTd# z@%Hwoa4;pIk+98F074CXmgMPDb zisM4Rn%Do=9xwca3%hHqF*dByJsMW+caT3NQs)kzxbv7&&9ozRxY6ANX^1Jtky>3_ zn_zwngQb_6GhdQcOyqWQu^WGPL%><>XM_i`Yu(N&(Qoc?f)+J(R;|~rY;Z><$Jc@0 z6nNNZmAJ{#$Oky${!|itWRosSJ&a>CYZ)_L&Ixc88%P5U> zb5%T=J;C;251Ims^U&LyM%0f7wsXLCYTs^_^}opr-aHa;c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z@&#sWQkS`C+(no6Wfb3N#_mtU)Ve?N zd?5ou3tnnC;1vR`g~IG%AI)PBG{o$N-ly2Se;Me@l$XiMkBJvP@$a1!zb0Mk04QwlG(u|V5qXIk`U?o2qK$4a7l5-RR1LL~V0@0vM z!lpSXw0UTVdv@@I>ekJ-KmJ{#6_B?O=id0G1*@APGtx4OI67Rla3-6=on80n!|Fr* zt@>J#5FpW5=+bw)P(5sJX$5Vre*B}1%B1;d+`Q>Zh`YF+mU}FiDRzN6Bmg|qDEJ!& ztIi3e-DZV>29nbfM%9Gp?w3g9i$IW(H$ABtZ-sX_=xmsS3C=SJCfqb9gX~JWLL>fF z6umqC>cST|(`OFT^&ok{`i0|jTH2MOF4;!Wq{#qj8@i@Alj5oAz7a>7w7eIA?WMYRVq6jlDa}gj7z2Uia*UaAZkP?aInERLeowLXr za3Jy;W`dK;oYb?>dP0I;^pp9Xb*En-C(r%7=8@_3TuTo*WN+`wx87kz9No$g;bO_Sm;@2v;z@=}K0mdaHXNjcn_zkl1r;@hP>>~j z*pwoU(%}H;6a-SeIeTY2wEH7FE3evsI@Cze8r*3NsVv9Nw{FfdTuK~8a3KIA@W1VC z>pWoPNT2QvmO22z0(S;t8>e-$zjy#NMUfrc%9ML7dliq$$A*$O;V6fG+KFVWY*FKV z9b`#@7Lv-P>!i2q-tm^aac^Gp3vx)D6*$MhQpbSF&4Pp9>%UBWh3@}n=W;j7MwVR|e|i1?O9DUo@Q(zM Wc+BXYWIXvF;J9LnG^sRlj`| ## 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** @@ -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? + From e8df17f0dd202d16298a14d7924943b7876a3690 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Thu, 13 Oct 2022 08:18:46 +0530 Subject: [PATCH 077/100] Update multithreading-questions.md --- multithreading-questions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/multithreading-questions.md b/multithreading-questions.md index 92a5472..62c8d7f 100644 --- a/multithreading-questions.md +++ b/multithreading-questions.md @@ -1,4 +1,4 @@ -# 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. @@ -2077,4 +2077,4 @@ The `wait()` is mainly used for shared resources, a thread notifies other waitin \ No newline at end of file + From f5069e8685c962050a8e82083b5818ee1097b97d Mon Sep 17 00:00:00 2001 From: shreeram09 Date: Thu, 10 Nov 2022 19:49:14 +0530 Subject: [PATCH 078/100] updated: answered few questions in top readme --- README.md | 290 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 290 insertions(+) diff --git a/README.md b/README.md index f4ce663..3429aba 100644 --- a/README.md +++ b/README.md @@ -3320,18 +3320,308 @@ The Object class is the parent class of all the classes in java by default. #### 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 + } +``` + #### 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? +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*. + #### 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? + #### Q. What are the different access specifiers available in java? +* 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. +```java + ... /* 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 */ + ... +``` + #### 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. +**/ +``` #### 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 + } +} +``` *ToDo*
From 011e2a6b9f914927849e9b038b7eeacca4c0a85e Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 19:43:13 +0530 Subject: [PATCH 079/100] Update README.md --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3429aba..62debd9 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,20 @@ -# Java Interview Questions +# Java Basics *Click if you like the project. Pull Request are highly appreciated.* -## Related Interview Questions +## Related Topics -* *[Java 8 Interview Questions](java8-questions.md)* -* *[Multithreading Interview Questions](multithreading-questions.md)* -* *[Collections Interview Questions](collections-questions.md)* -* *[JDBC Interview Questions](JDBC-questions.md)* +* *[Java 8](java8-questions.md)* +* *[Multithreading](multithreading-questions.md)* +* *[Collections](collections-questions.md)* +* *[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)* +* *[JSP](jsp-questions.md)* +* *[Servlets](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* -* *[Spring Interview Questions](https://github.com/learning-zone/spring-interview-questions)* -* *[Hibernate Interview Questions](https://github.com/learning-zone/hibernate-interview-questions)* +* *[Spring](https://github.com/learning-zone/spring-interview-questions)* +* *[Hibernate](https://github.com/learning-zone/hibernate-interview-questions)* * *[Java Design Pattern Questions](https://github.com/learning-zone/java-design-patterns)*
From 6c5b56935b19cb9efc2bf09a7a444884dfb9ad98 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sat, 12 Nov 2022 20:43:46 +0530 Subject: [PATCH 080/100] Update README.md --- README.md | 172 +++++++++++++++++++++++++++--------------------------- 1 file changed, 86 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 62debd9..e64c0b8 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,18 @@ ## Related Topics -* *[Java 8](java8-questions.md)* -* *[Multithreading](multithreading-questions.md)* -* *[Collections](collections-questions.md)* -* *[JDBC](JDBC-questions.md)* +* *[Java 8 Basics](java8-questions.md)* +* *[Multithreading Basics](multithreading-questions.md)* +* *[Collections Basics](collections-questions.md)* +* *[JDBC Basics](JDBC-questions.md)* * *[Java Programs](java-programs.md)* * *[Java String Methods](java-string-methods.md)* -* *[JSP](jsp-questions.md)* -* *[Servlets](servlets-questions.md)* +* *[JSP Basics](jsp-questions.md)* +* *[Servlets Basics](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* -* *[Spring](https://github.com/learning-zone/spring-interview-questions)* -* *[Hibernate](https://github.com/learning-zone/hibernate-interview-questions)* -* *[Java Design Pattern Questions](https://github.com/learning-zone/java-design-patterns)* +* *[Spring Basics](https://github.com/learning-zone/spring-basics)* +* *[Hibernate Basics](https://github.com/learning-zone/hibernate-basics)* +* *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)*
@@ -36,7 +36,7 @@ The classes which inherit **RuntimeException** are known as unchecked exceptions Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. ## Q. Explain hierarchy of Java Exception classes? @@ -103,7 +103,7 @@ public class CustomExceptionExample { ``` ## Q. What is the difference between aggregation and composition? @@ -171,7 +171,7 @@ class Engine { *Note: "final" keyword is used in Composition to make sure child variable is initialized.* ## Q. What is difference between Heap and Stack Memory in java? @@ -204,7 +204,7 @@ As soon as method ends, the block becomes unused and become available for next m |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 | ## Q. What is JVM and is it platform independent? @@ -214,7 +214,7 @@ Java Virtual Machine (JVM) is a specification that provides runtime environment 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. ## Q. What is JIT compiler in Java? @@ -224,7 +224,7 @@ The Just-In-Time (JIT) compiler is a component of the runtime environment that i 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. ## Q. What is Classloader in Java? @@ -246,7 +246,7 @@ It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` di It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options. ## Q. Java Compiler is stored in JDK, JRE or JVM? @@ -268,7 +268,7 @@ Java Runtime Environment provides a platform to execute java programs. JRE consi

## Q. What is the difference between factory and abstract factory pattern? @@ -301,7 +301,7 @@ Abstract Factory patterns work around a super-factory which creates other factor 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. What are the methods used to implement for key Object in HashMap? @@ -315,7 +315,7 @@ Class inherits methods from the following classes in terms of HashMap * java.util.Map ## Q. What is difference between the Inner Class and Sub Class? @@ -361,7 +361,7 @@ class HybridCar extends Car { ``` ## Q. Distinguish between static loading and dynamic class loading? @@ -397,7 +397,7 @@ Class.forName (String className); ``` ## Q. What is the difference between transient and volatile variable in Java? @@ -440,7 +440,7 @@ public class MyRunnable implements Runnable { ``` ## Q. How many types of memory areas are allocated by JVM? @@ -467,7 +467,7 @@ JVM is a program which takes Java bytecode and converts the byte code (line by l **6. Native Method Stack**: It contains all the native methods used in the application. ## Q. How can constructor chaining be done using this keyword? @@ -574,7 +574,7 @@ Calling parameterized constructor of derived ``` ## Q. Can you declare the main method as final? @@ -606,7 +606,7 @@ Cannot override the final method from Test. ``` ## Q. What is the difference between compile-time polymorphism and runtime polymorphism? @@ -689,7 +689,7 @@ Overriding Method ``` ## Q. Can you have virtual functions in Java? @@ -715,7 +715,7 @@ class ACMEBicycle implements Bicycle { ``` ## Q. What is covariant return type? @@ -755,7 +755,7 @@ Subclass ``` ## Q. What is the difference between abstraction and encapsulation? @@ -781,7 +781,7 @@ Abstraction is about hiding unwanted details while giving out most essential det
## Q. Can we use private or protected member variables in an interface? @@ -811,7 +811,7 @@ public interface Test { * 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? @@ -840,7 +840,7 @@ public class TestInterface implements MyInterface { ``` ## Q. Give the hierarchy of InputStream and OutputStream classes? @@ -927,7 +927,7 @@ public class CopyFile { ``` ## Q. What is the purpose of the Runtime class and System class? @@ -969,7 +969,7 @@ public class RuntimeTest 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. ## Q. What are assertions in Java? @@ -1004,7 +1004,7 @@ public class Example { ``` ## Q. What is the difference between abstract class and interface? @@ -1022,7 +1022,7 @@ Abstract class and interface both are used to achieve abstraction where we can d |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? @@ -1077,7 +1077,7 @@ Output ``` ## Q. What is Java Reflection API? @@ -1175,7 +1175,7 @@ Test ``` ## Q. How many types of constructors are used in Java? @@ -1237,7 +1237,7 @@ public class Car { ``` ## Q. What are the restrictions that are applied to the Java static methods? @@ -1288,7 +1288,7 @@ overridden method is static ``` ## Q. What is the final variable, final class, and final blank variable? @@ -1393,7 +1393,7 @@ class ABC extends XYZ { ``` ## Q. What is the static import? @@ -1416,7 +1416,7 @@ class StaticImportExample { ``` ## Q. Name some classes present in java.util.regex package? @@ -1450,7 +1450,7 @@ public class Index { ``` ## Q. How will you invoke any external process in Java? @@ -1482,7 +1482,7 @@ class ExternalProcessExample { ``` ## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? @@ -1588,7 +1588,7 @@ This is an example of writing data to a file ``` ## Q. How to set the Permissions to a file in Java? @@ -1644,7 +1644,7 @@ public class FilePermissions { ``` ## Q. In Java, How many ways you can take input from the console? @@ -1722,7 +1722,7 @@ public class Sample { ``` ## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface? @@ -1806,7 +1806,7 @@ java.io.NotSerializableException: This class cannot be Serialized ``` ## Q. What is the difference between Serializable and Externalizable interface? @@ -1821,7 +1821,7 @@ java.io.NotSerializableException: This class cannot be Serialized |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? @@ -1853,7 +1853,7 @@ MyObject object = (MyObject) inStream.readObject(); ``` ## Q. What is the purpose of using javap? @@ -1886,7 +1886,7 @@ class Simple { ``` ## Q. What are autoboxing and unboxing? @@ -1927,7 +1927,7 @@ class UnboxingExample { ``` ## Q. What is a native method? @@ -1976,7 +1976,7 @@ Output ``` ## Q. What is immutable object? @@ -2009,7 +2009,7 @@ public class DateContainer { ``` ## Q. The difference between Inheritance and Composition? @@ -2048,7 +2048,7 @@ class Apple { ``` ## Q. The difference between DOM and SAX parser in Java? @@ -2064,7 +2064,7 @@ DOM and SAX parser are extensively used to read and parse XML file in java and h |suitable |better suitable for smaller and efficient memory| SAX is suitable for larger XML doc| ## Q. What is the difference between creating String as new() and literal? @@ -2090,7 +2090,7 @@ System.out.println(c == d); // false ``` ## Q. How can we create an immutable class in Java? @@ -2124,7 +2124,7 @@ public final class Employee { ``` ## Q. What is difference between String, StringBuffer and StringBuilder? @@ -2168,7 +2168,7 @@ public class BuilderTest { ``` ## Q. What is a Memory Leak? @@ -2216,7 +2216,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed * Calling `String.intern()` on Long String ## Q. What is difference between Error and Exception? @@ -2233,7 +2233,7 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed |Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.| ## Q. Explain about Exception Propagation? @@ -2273,7 +2273,7 @@ class TestExceptionPropagation { ``` ## Q. What are different scenarios causing "Exception in thread main"? @@ -2289,7 +2289,7 @@ Some of the common main thread exception are as follows: * **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? @@ -2357,7 +2357,7 @@ You shouldn\'t divide number by zero ``` ## Q. The difference between Serial and Parallel Garbage Collector? @@ -2373,7 +2373,7 @@ Turn on the `-XX:+UseSerialGC` JVM argument to use the serial 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. What is difference between WeakReference and SoftReference in Java? @@ -2443,7 +2443,7 @@ public class Example { ``` ## Q. What is a compile time constant in Java? @@ -2464,7 +2464,7 @@ private final int x = 10; ``` ## Q. How bootstrap class loader works in java? @@ -2501,7 +2501,7 @@ public class ClassLoaderTest { ``` ## Q. Why string is immutable in java? @@ -2511,7 +2511,7 @@ The string is Immutable in Java because String objects are cached in String pool Since string is immutable it can safely share between many threads and avoid any synchronization issues in java. ## Q. What is Java String Pool? @@ -2538,7 +2538,7 @@ public class StringPool { ``` ## Q. How Garbage collector algorithm works? @@ -2548,7 +2548,7 @@ Garbage collection works on **Mark** and **Sweep** algorithm. In Mark phase it d 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. How to create marker interface? @@ -2587,7 +2587,7 @@ class Main { ``` ## Q. How serialization works in java? @@ -2679,7 +2679,7 @@ public class SerialExample { ``` ## Q. Java Program to Implement Singly Linked List? @@ -2763,7 +2763,7 @@ Nodes of singly linked list: 10 20 30 40 ``` ## Q. While overriding a method can you throw another exception or broader exception? @@ -2796,7 +2796,7 @@ class B extends A { } ``` ## Q. What is checked, unchecked exception and errors? @@ -2883,7 +2883,7 @@ Java Result: 1 Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? @@ -2895,7 +2895,7 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. `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? @@ -2942,7 +2942,7 @@ Weak Reference Example! ``` ## Q. What do you mean Run time Polymorphism? @@ -3004,7 +3004,7 @@ 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? @@ -3012,7 +3012,7 @@ Overriding Method 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. ## Q. What are the different types of JDBC Driver? @@ -3026,7 +3026,7 @@ 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? @@ -3061,7 +3061,7 @@ public class MainClass { } ``` ## Q. Do you know Generics? How did you used in your coding? @@ -3116,7 +3116,7 @@ Generic Class Example ! 100 ``` ## Q. What is difference between String, StringBuilder and StringBuffer? @@ -3172,7 +3172,7 @@ StringBuilder: World StringBuffer: World ``` ## Q. How can we create a object of a class without using new operator? @@ -3293,7 +3293,7 @@ public class MainClass { ``` ## Q. What are methods of Object Class? @@ -3316,7 +3316,7 @@ The Object class is the parent class of all the classes in java by default. #### Q. What is copyonwritearraylist in java? @@ -3625,7 +3625,7 @@ class Visitor{ *ToDo* From 80507376e6c69b3cdce346db77e21f89663ec71b Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 13 Nov 2022 17:35:54 +0530 Subject: [PATCH 081/100] Update README.md --- README.md | 981 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 937 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index e64c0b8..bb1895e 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,10 @@ *Click if you like the project. Pull Request are highly appreciated.* +
+ ## Related Topics -* *[Java 8 Basics](java8-questions.md)* * *[Multithreading Basics](multithreading-questions.md)* * *[Collections Basics](collections-questions.md)* * *[JDBC Basics](JDBC-questions.md)* @@ -192,7 +193,6 @@ As soon as method ends, the block becomes unused and become available for next m **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| @@ -221,7 +221,7 @@ The JVM is not platform independent. Java Virtual Machine (JVM) provides the env 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 @@ -253,7 +253,7 @@ It loads application specific classes from the CLASSPATH environment variable. I **1. 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. +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**: @@ -454,13 +454,13 @@ 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. +**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. +**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. @@ -1811,7 +1811,6 @@ java.io.NotSerializableException: This class cannot be Serialized ## Q. What is the difference between Serializable and 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.| @@ -2221,7 +2220,6 @@ Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ## 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.| @@ -2684,7 +2682,7 @@ public class SerialExample { ## 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:** @@ -2757,17 +2755,19 @@ 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. @@ -2795,12 +2795,12 @@ class B extends A { } } ``` + ## Q. What is checked, unchecked exception and errors? - **1. Checked Exception**: @@ -2825,14 +2825,18 @@ class Main { } } ``` + 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.*; @@ -2848,7 +2852,9 @@ class Main { } } ``` + output: + ```java Output: First three lines of file “C:\assets\file.txt” ``` @@ -2870,7 +2876,9 @@ class Main { } } ``` + Output: + ```java Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) @@ -2879,7 +2887,7 @@ Java Result: 1 **3. Error**: -**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. +**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc.
@@ -2947,7 +2955,7 @@ Weak Reference Example! ## 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. +`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 @@ -2974,8 +2982,10 @@ public class MainClass } } ``` + Output -``` + +```java 30 60 ``` @@ -2999,16 +3009,19 @@ public class XYZ extends ABC { } } ``` + Output -``` + +```java 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.
@@ -3017,7 +3030,7 @@ If the subclass constructor does not specify which superclass constructor to inv ## Q. What are the different types of JDBC Driver? -JDBC Driver is a software component that enables java application to interact with the database. +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. @@ -3033,7 +3046,8 @@ There are 4 types of JDBC drivers: 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 − +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. @@ -3060,6 +3074,7 @@ public class MainClass { } } ``` + @@ -3068,7 +3083,8 @@ public class MainClass { `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** +**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. @@ -3110,11 +3126,14 @@ class MainClass { } } ``` + Output: -``` + +```java Generic Class Example ! 100 ``` + @@ -3125,7 +3144,8 @@ String is `immutable`, if you try to alter their values, another object gets cre 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**: +**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. @@ -3165,12 +3185,15 @@ class StringExample { } } ``` + Output -``` + +```java String: Hello StringBuilder: World StringBuffer: World ``` + @@ -3178,7 +3201,8 @@ StringBuffer: World ## 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** + +* **Using new Keyword:** ```java class ObjectCreationExample{ @@ -3190,8 +3214,8 @@ public class MainClass { ObjectCreationExample obj = new ObjectCreationExample(); } } - ``` + * **Using New Instance (Reflection)** ```java @@ -3224,9 +3248,9 @@ class MainClass { } } } - ``` -* **Using Clone** + +* **Using Clone:** ```java class CreateObjectWithClone implements Cloneable { @@ -3258,6 +3282,7 @@ class MainClass { } } ``` + * **Using ClassLoader** ```java @@ -3319,7 +3344,8 @@ The Object class is the parent class of all the classes in java by default. ↥ back to top
-#### Q. What is copyonwritearraylist in java? +## 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. @@ -3329,10 +3355,12 @@ The Object class is the parent class of all the classes in java by default. * 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. + - We don\'t want to synchronize the thread access programatically. + ```java import java.util.concurrent.CopyOnWriteArrayList; CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(); @@ -3366,16 +3394,18 @@ The Object class is the parent class of all the classes in java by default. } ``` -#### 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. 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**. +`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 { @@ -3443,7 +3473,8 @@ public class ClientTestProgram { } } ``` -Let's refactor the code to make "good" design using **LSP**? + +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. @@ -3451,6 +3482,7 @@ Let's refactor the code to make "good" design using **LSP**? - so client program can substitute `DivMediaPlayer` or `VlcMediaPlayer` for their super class `VideoMediaPlayer` lets reimplement the refactored code + ```java public class MediaPlayer { @@ -3488,20 +3520,23 @@ public class WinampMediaPlayer extends MediaPlayer {} } } ``` + 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*. -#### 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? + + +## Q. What are the different access specifiers available in java? -#### Q. What are the different access specifiers available in java? * 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. + ```java ... /* data member variables */ String firstName="Pradeep"; /* default scope */ @@ -3525,10 +3560,16 @@ that satisefies *Liskov's substitution principle*. ... ``` -#### Q. What is runtime polymorphism in java? + + +## 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; @@ -3568,10 +3609,17 @@ 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. **/ ``` -#### Q. What is a private constructor? + + + +## 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 { @@ -3622,10 +3670,855 @@ class Visitor{ } } ``` -*ToDo* +## 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. 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 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? +#### 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? +#### 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? + + From 3e6910441ce4722bc67160bc9e2bcdda83347408 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 13 Nov 2022 17:36:04 +0530 Subject: [PATCH 082/100] Delete java8-questions.md --- java8-questions.md | 961 --------------------------------------------- 1 file changed, 961 deletions(-) delete mode 100644 java8-questions.md 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? - - From e6d2bb597531068cc1b96fbfd1a4c3562fc4545f Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 13 Nov 2022 17:36:15 +0530 Subject: [PATCH 083/100] Update java-programs.md --- java-programs.md | 186 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 183 insertions(+), 3 deletions(-) diff --git a/java-programs.md b/java-programs.md index 3f8e41f..4faab21 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 @@ -1720,6 +1725,181 @@ 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 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? From b0f57710fc0397ebceeabdbce868c2d791656f29 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 13 Nov 2022 17:37:14 +0530 Subject: [PATCH 084/100] Update README.md --- README.md | 86 +++++++++++++++++++++++++++---------------------------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index bb1895e..815729b 100644 --- a/README.md +++ b/README.md @@ -3708,7 +3708,7 @@ class Visitor{ * Added utility `jdeps` for analyzing .class files. ## Q. Can you declare an interface method static? @@ -3716,7 +3716,7 @@ class Visitor{ 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? @@ -3804,7 +3804,7 @@ public static void main ( String [] args) { ``` ## Q. What variables do lambda expressions have access to? @@ -3818,7 +3818,7 @@ Access to external scope variables from a lambda expression is very similar to a 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? @@ -3831,7 +3831,7 @@ public static List < String > sort ( List < String > list) { ``` ## Q. What is a method reference? @@ -3852,7 +3852,7 @@ public static void main ( String [] args) { 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? @@ -3862,7 +3862,7 @@ Method references are potentially more efficient than using lambda expressions. * to the constructor. ## Q. Explain the expression `System.out::println`? @@ -3870,7 +3870,7 @@ Method references are potentially more efficient than using lambda expressions. The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. ## Q. What is a Functional Interface? @@ -3882,7 +3882,7 @@ To accurately determine the interface as functional, an annotation has been adde An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. ## Q. What is StringJoiner? @@ -3898,7 +3898,7 @@ System.out.println(joiner); // prefix-Hello.the.brave.world-suffix ``` ## Q. What are `default`interface methods? @@ -3923,7 +3923,7 @@ interface Example { * 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? @@ -3945,7 +3945,7 @@ class License implements Paper { ``` ## Q. What is `static` interface method? @@ -3957,7 +3957,7 @@ Static interface methods are similar to default methods, except that there is no * 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? @@ -3979,7 +3979,7 @@ class License { ``` ## Q. What is Optional @@ -3996,7 +3996,7 @@ optional.orElse( " ops ... " ); // "hello" ``` ## Q. What is Stream? @@ -4021,7 +4021,7 @@ In addition to the universal object, there are special types of streams to work * support additional end operations `sum()`, `average()`, `mapToObj()`. ## Q. What are the ways to create a stream? @@ -4075,7 +4075,7 @@ Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); ``` ## Q. What is the difference between `Collection` and `Stream`? @@ -4083,7 +4083,7 @@ Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); 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? @@ -4119,7 +4119,7 @@ Collector < String , a List < String > , a List < String > > toList = Collector ``` ## Q. Why do streams use `forEach()`and `forEachOrdered()` methods? @@ -4128,7 +4128,7 @@ Collector < String , a List < String > , a List < String > > toList = Collector * `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? @@ -4144,7 +4144,7 @@ Stream ``` ## Q. What is the purpose of `filter()` method in streams? @@ -4152,7 +4152,7 @@ Stream 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? @@ -4160,7 +4160,7 @@ The method `filter()` is an intermediate operation receiving a predicate that fi 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? @@ -4170,7 +4170,7 @@ The method `sorted()`is an intermediate operation, which allows you to sort the 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()`? @@ -4187,7 +4187,7 @@ Stream `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. ## Q. Tell us about parallel processing in Java 8? @@ -4228,7 +4228,7 @@ collection.parallelStream () ``` ## Q. What are the final methods of working with streams you know? @@ -4250,7 +4250,7 @@ collection.parallelStream () * `average()` returns the arithmetic mean of all numbers. ## Q. What intermediate methods of working with streams do you know? @@ -4268,7 +4268,7 @@ collection.parallelStream () For numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream. ## Q. What additional methods for working with associative arrays (maps) appeared in Java 8? @@ -4316,7 +4316,7 @@ map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] ``` ## Q. What is LocalDateTime? @@ -4324,7 +4324,7 @@ map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] `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? @@ -4332,7 +4332,7 @@ map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] `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 determine repeatable annotation? @@ -4351,7 +4351,7 @@ To define a repeatable annotation, you must create a container annotation for th ``` ## Q. What is Nashorn? @@ -4359,7 +4359,7 @@ To define a repeatable annotation, you must create a container annotation for th **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? @@ -4367,7 +4367,7 @@ To define a repeatable annotation, you must create a container annotation for th `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? @@ -4380,7 +4380,7 @@ Base64 contains 6 basic methods: `getMimeEncoder() / getMimeDecoder()`- returns a MIME encoder / decoder conforming to RFC 2045 . ## Q. How to create a Base64 encoder and decoder? @@ -4393,7 +4393,7 @@ new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // inp ``` ## Q. What are the functional interfaces `Function`, `DoubleFunction`, `IntFunction` and `LongFunction`? @@ -4413,7 +4413,7 @@ backToString.apply("123"); // "123" * `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`? @@ -4430,7 +4430,7 @@ System.out.println(operator.apply ( 5 )); // 25 * `LongUnaryOperator`- unary operator receiving input `Long`. ## Q. What are the functional interfaces `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`? @@ -4447,7 +4447,7 @@ System.out.println(operator.apply ( 1 , 2 )); // 3 * `LongBinaryOperator`- binary operator receiving input Long. ## Q. What are the functional interfaces `Predicate`, `DoublePredicate`, `IntPredicateand` `LongPredicate`? @@ -4467,7 +4467,7 @@ predicate.negate().test("foo"); // false * `LongPredicate`- predicate receiving input `Long`. ## Q. What are the functional interfaces `Consumer`, `DoubleConsumer`, `IntConsumer`and `LongConsumer`? @@ -4484,7 +4484,7 @@ hello.accept( " world " ); * `LongConsumer`- the consumer receiving the input `Long`. ## Q. What are the functional interfaces `Supplier`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier`and `LongSupplier`? @@ -4501,7 +4501,7 @@ now.get(); * `LongSupplier`- the supplier is returning `Long`. #### Q. When do we go for Java 8 Stream API? @@ -4520,5 +4520,5 @@ now.get(); #### Q. What is the difference between @Before and @BeforeClass annotation? From 12b34c1049e9905e8f0a92ce0ea6d25bd797e4ea Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 13:02:24 +0530 Subject: [PATCH 085/100] Update java-programs.md --- java-programs.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/java-programs.md b/java-programs.md index 4faab21..bc37276 100644 --- a/java-programs.md +++ b/java-programs.md @@ -1900,6 +1900,19 @@ LocalDateTime.ofInstant ( new Date().toInstant(), ZoneId.systemDefault()); ↥ back to top
+## 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? From 8579d51d9458995d75744f5dae7db2be181b641c Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 13:02:36 +0530 Subject: [PATCH 086/100] Update README.md --- README.md | 4747 +++++++++++++++++++++++++++-------------------------- 1 file changed, 2408 insertions(+), 2339 deletions(-) diff --git a/README.md b/README.md index 815729b..387675e 100644 --- a/README.md +++ b/README.md @@ -20,193 +20,194 @@
-## 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**: +## Table of Contents + +* [Introduction](#-1-introduction) +* [Java Architecture](#-2-java-architecture) +* [Java Data Types](#-3-java-data-types) +* [Java Methods](#-4-java-methods) +* [Java Classes](#-5-java-classes) +* [Java Constructors](#-6-java-constructors) +* [Java Array](#-7-java-array) +* [Java Strings](#-8-java-strings) +* [Java Reflection](#-9-java-reflection) +* [Java Streams](#-10-java-streams) +* [Java Regular Expressions](#-11-java-regular-expressions) +* [Java File Handling](#-12-java-file-handling) +* [Java Exceptions](#-13-java-exceptions) +* [Java Inheritance](#-14-java-inheritance) +* [Java Method Overriding](#-15-java-method-overriding) +* [Java Polymorphism](#-16-java-polymorphism) +* [Java Abstraction](#-17-java-abstraction) +* [Java Interfaces](#-18-java-interfaces) +* [Java Encapsulation](#-19-java-encapsulation) +* [Miscellaneous](#-20-react-miscellaneous) -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**: +## # 1. INTRODUCTION -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**: +## Q. What are the important features of Java 8 release? -Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. +* 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. Explain hierarchy of Java Exception classes? +## Q. In Java, How many ways you can take input from the console? -The **java.lang.Throwable** class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. +In Java, there are three different ways for reading input from the user in the command line environment ( console ). -

- Exception in Java -

+**1. Using Buffered Reader Class:** -**Example:** +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 /** - * Exception classes + * Buffered Reader Class */ -import java.io.FileInputStream; -import java.io.FileNotFoundException; +import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStream; - -public class CustomExceptionExample { +import java.io.InputStreamReader; - public static void main(String[] args) throws MyException { - try { - processFile("file.txt"); - } catch (MyException e) { - processErrorCodes(e); - } - } +public class Test { + public static void main(String[] args) throws IOException { + // Enter data using BufferReader + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); - 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(); - } - } + // Reading data using readLine + String name = reader.readLine(); - 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"); - } - } - } + // Printing the read line + System.out.println(name); + } } ``` - - -## 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. +**2. Using Scanner Class:** -**Example:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes +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. ```java /** - * Aggregation + * Scanner Class */ -public class Organization { - private List employees; -} +import java.util.Scanner; -public class Person { - private String name; -} -``` +class GetInputFromUser { + public static void main(String args[]) { + // Using Scanner for Getting Input from User + Scanner in = new Scanner(System.in); -**2. Composition:** + String s = in.nextLine(); + System.out.println("You entered string " + s); -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. + int a = in.nextInt(); + System.out.println("You entered integer " + a); -**Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. + 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() ). ```java /** - * Composition + * Console Class */ -public class Car { - //final will make sure engine is initialized - private final Engine engine; - - public Car(){ - engine = new Engine(); +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); } } - -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. What is difference between Heap and Stack Memory in java? - -**1. Java Heap Space:** +## Q. What is the purpose of using javap? -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. +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. -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. + ```java + /** + * Java Disassembler + */ +class Simple { + public static void main(String args[]) { + System.out.println("Hello World"); + } +} +``` -**2. Java Stack Memory:** +```cmd +cmd> javap Simple.class +``` -Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. +Output -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. +```java +Compiled from ".java" +class Simple { + Simple(); + public static void main(java.lang.String[]); +} +``` -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. + -**Difference:** +## Q. Explain the expression `System.out::println`? -|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 | +The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. +## # 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). @@ -271,129 +272,104 @@ Java Runtime Environment provides a platform to execute java programs. JRE consi ↥ back to top
-## Q. What is the difference between factory and abstract factory pattern? +## Q. What is difference between Heap and Stack Memory in java? -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. +**1. Java Heap Space:** -**Example:** credit card validator factory which returns a different validator for each card type. +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. -```java -/** - * 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. +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. -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. +**2. Java Stack Memory:** - +Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. -## Q. What are the methods used to implement for key Object in HashMap? +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. -**1. equals()** and **2. hashcode()** +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. -Class inherits methods from the following classes in terms of HashMap +**Difference:** -* java.util.AbstractMap -* java.util.Object -* java.util.Map +|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 | -## Q. What is difference between the Inner Class and Sub Class? +## Q. How many types of memory areas are allocated by JVM? -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. +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: -**Example:** +* Loading of code +* Verification of code +* Executing the code +* It provide run-time environment to the users -```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(); - } -} -``` +**Types of Memory areas allocated by the JVM:** -A subclass is class which inherits a method or methods from a superclass. +**1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. -**Example:** +**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. -```java -/** - * Sub Class - */ -class Car { - //... -} - -class HybridCar extends Car { - //... -} -``` +**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. + +**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. -## Q. Distinguish between static loading and dynamic class loading? +## # 3. JAVA DATA TYPES -**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. +## Q. What are autoboxing and unboxing? -**Example:** +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 /** - * Static Class Loading + * Autoboxing */ -class TestClass { - public static void main(String args[]) { - TestClass tc = new TestClass(); - } -} -``` - -**2. Dynamic Class Loading:** +class BoxingExample { + public static void main(String args[]) { + int a = 50; + Integer a2 = new Integer(a); // Boxing + Integer a3 = 5; // Boxing -Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. + System.out.println(a2 + " " + a3); + } +} +``` -**Example:** +**Example:** Unboxing ```java /** - * Dynamic Class Loading + * Unboxing */ -Class.forName (String className); +class UnboxingExample { + public static void main(String args[]) { + Integer i = new Integer(50); + int a = i; + + System.out.println(a); + } +} ```
@@ -443,255 +419,207 @@ public class MyRunnable implements Runnable { ↥ back to top
-## 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 -* Verification of code -* Executing the code -* It provide run-time environment to the users +## Q. What are assertions in Java? -**Types of Memory areas allocated by the JVM:** +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. -**1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. +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. -**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. +The assert statement is used with a Boolean expression and can be written in two different ways. -**3. Heap**: It is the runtime data area in which objects are allocated. +```java +// First way +assert expression; -**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. +// Second way +assert expression1 : expression2; +``` -**5. Program Counter Register**: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. +**Example:** -**6. Native Method Stack**: It contains all the native methods used in the application. +```java +/** + * 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); + } +} +``` -## Q. How can constructor chaining be done using this keyword? +## Q. What is the final variable, final class, and final blank variable? -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 – +**1. Final Variable:** -* **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. +Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. + +**Example:** ```java /** - * Constructor Chaining - * within same class Using this() keyword + * Final Variable */ -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(); - } -} +class Demo { + + final int MAX_VALUE = 99; + + void myMethod() { + MAX_VALUE = 101; + } + + public static void main(String args[]) { + Demo obj = new Demo(); + obj.myMethod(); + } +} ``` -Ouput: +Output ```java -30 -10 -The Default constructor +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) ``` +**2. 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` ). + +**Example:** + ```java /** - * Constructor Chaining to - * other class using super() keyword + * Blank final variable */ -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 -``` - - - -## 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. +class Demo { + // Blank final variable + final int MAX_VALUE; -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. + Demo() { + // It must be initialized in constructor + MAX_VALUE = 100; + } -**Example:** + void myMethod() { + System.out.println(MAX_VALUE); + } -```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"); - } + public static void main(String args[]) { + Demo obj = new Demo(); + obj.myMethod(); + } } ``` Output ```java -Cannot override the final method from Test. +100 ``` - - -## 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:** +**3. Final Method:** -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. +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 /** - * Static Polymorphism + * Final Method */ -class SimpleCalculator { - int add(int a, int b) { - return a + b; +class XYZ { + final void demo() { + System.out.println("XYZ Class Method"); } +} - int add(int a, int b, int c) { - return a + b + c; +class ABC extends XYZ { + void demo() { + System.out.println("ABC Class Method"); } -} -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)); + ABC obj = new ABC(); + obj.demo(); } } ``` -Output - -```java -30 -60 -``` + -**2. Runtime Polymorphism:** +## Q. What is a compile time constant in Java? -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. +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. -**Example:** +**Compile time constant must be:** -```java -/** - * Runtime Polymorphism - */ -class ABC { +* Declared final +* Primitive or String +* Initialized within declaration +* Initialized with constant expression - public void myMethod() { - System.out.println("Overridden Method"); - } -} +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. -public class XYZ extends ABC { +```java +private final int x = 10; +``` - public void myMethod() { - System.out.println("Overriding Method"); - } + - public static void main(String args[]) { - ABC obj = new XYZ(); - obj.myMethod(); - } -} -``` +## Q. What are the different access specifiers available in java? -Output: +* 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. ```java -Overriding Method + ... /* 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 */ + ... ``` +## # 4. JAVA METHODS + +
+ ## 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. @@ -718,288 +646,282 @@ class ACMEBicycle implements Bicycle { ↥ back to top -## Q. What is covariant return type? +## Q. What is a native method? -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. +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: -**Example:** +**Main.java:** ```java -/** - * Covariant Return Type - */ -class SuperClass { - SuperClass get() { - System.out.println("SuperClass"); - return this; +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)); } } +``` -public class Tester extends SuperClass { - Tester get() { - System.out.println("SubClass"); - return this; - } +**Main.c:** - public static void main(String[] args) { - SuperClass tester = new Tester(); - tester.get(); - } +```c +#include +#include "Main.h" + +JNIEXPORT jint JNICALL Java_Main_intMethod( + JNIEnv *env, jobject obj, jint i) { + return i * i; } ``` -Output: +**Compile and Run:** ```java -Subclass +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 + +```java +4 ``` -## 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. +## Q. What are the restrictions that are applied to the Java static methods? -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. +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. -**Difference:** +There are a few restrictions imposed on a static method - - - - - - - - - - - - -
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.
+* 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 ). +* 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:** -## Q. Can we use private or protected member variables in an interface? +```java +/** + * Static Methods + */ +class Parent { + static void display() { + System.out.println("Super class"); + } +} -The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically +public class Example extends Parent { + void display() // trying to override display() { + System.out.println("Sub class"); + } -```java -public interface Test { - public string name1; - private String email; - protected pass; + public static void main(String[] args) { + Parent obj = new Example(); + obj.display(); + } } ``` -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. +This generates a compile time error. The output is as follows − ```java -public interface Test { - public static final string name1; - public static final String email; - public static final pass; -} -``` +Example.java:10: error: display() in Example cannot override display() in Parent +void display() // trying to override display() + ^ +overridden method is static -* 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** +1 error +``` -## Q. When can an object reference be cast to a Java interface reference? +## Q. What is a lambda? -An interface reference can point to any object of a class that implements this interface + 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. -```java -/** - * Interface - */ -interface MyInterface { - void display(); -} +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. -public class TestInterface implements MyInterface { +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. - void display() { - System.out.println("Hello World"); - } +```java +interface Operationable { + int calculate ( int x , int y ); +} - public static void main(String[] args) { - MyInterface myInterface = new TestInterface(); - MyInterface.display(); - } +public static void main ( String [] args) { + Operationable operation = (x, y) - > x + y; + int result = operation.calculate ( 10 , 20 ); + System.out.println (result); // 30 } ``` - - -## 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 − +In fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java. -* **InPutStream** − The InputStream is used to read data from a source. -* **OutPutStream** − The OutputStream is used for writing data to a destination. +* _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. -**1. Byte Streams:** +* _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method: -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. +```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; +``` -**Example:** +* Trailing lambda expressions are not required to return any value. ```java -/** - * Byte Streams - */ -import java.io.*; - -public class CopyFile { +interface Printable { + void print( String s ); +} + +public static void main ( String [] args) { + Printable printer = s - > System.out.println(s); + printer.print("Hello, world"); +} - public static void main(String args[]) throws IOException { - FileInputStream in = null; - FileOutputStream out = null; +// _ 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 ' : - 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(); - } - } +Operationable operation = ( int x, int y) - > { + if (y == 0 ) { + return 0 ; } -} + else { + return x / y; + } +}; ``` -**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:** +* Passing a lambda expression as a method parameter ```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"); +interface Condition { + boolean isAppropriate ( int n ); +} - int c; - while ((c = in.read()) != -1) { - out.write(c); - } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } +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 is the purpose of the Runtime class and System class? +## Q. What variables do lambda expressions have access to? -**1. Runtime Class:** +Access to external scope variables from a lambda expression is very similar to access from anonymous objects. -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. +* immutable ( effectively final - not necessarily marked as final) local variables; +* class fields +* static variables. -**Example:** +The default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression. + + + +## 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 -/** - * Runtime Class - */ -public class RuntimeTest -{ - static class Message extends Thread { - public void run() { - System.out.println(" Exit"); - } - } +private interface Measurable { + public int length ( String string ); +} - 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(); - } - } +public static void main ( String [] args) { + Measurable a = String::length; + System.out.println(a.length("abc")); } ``` -**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. +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 are assertions in Java? +## Q. What types of method references do you know? -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. +* on the static method; +* per instance method; +* to the constructor. -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. +## # 5. JAVA CLASSES -```java -// First way -assert expression; +
-// Second way -assert expression1 : expression2; -``` +## 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 /** - * Assertions + * Inner Class */ -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); - } +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 { + //... } ``` @@ -1007,74 +929,79 @@ public class Example { ↥ back to top -## Q. What is the difference between abstract class and interface? +## Q. Distinguish between static loading and dynamic class loading? -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. +**1. Static Class Loading:** -|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.| +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:** -## Q. What are Wrapper classes? +```java +/** + * Static Class Loading + */ +class TestClass { + public static void main(String args[]) { + TestClass tc = new TestClass(); + } +} +``` -The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. +**2. Dynamic Class Loading:** -**Use of Wrapper classes in Java:** +Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. -* **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. +**Example:** -* **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. +```java +/** + * Dynamic Class Loading + */ +Class.forName (String className); +``` -* **Synchronization**: Java synchronization works with objects in Multithreading. + -* **java.util package**: The java.util package provides the utility classes to deal with objects. +## Q. What is the purpose of the Runtime class and System class? -* **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. +**1. Runtime Class:** -| 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| +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:** Primitive to Wrapper +**Example:** ```java /** - * Java program to convert primitive into objects - * Autoboxing example of int to Integer + * Runtime Class */ -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 +public class RuntimeTest +{ + static class Message extends Thread { + public void run() { + System.out.println(" Exit"); + } + } - System.out.println(a + " " + i + " " + j); + 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:** -```java -20 20 20 -``` +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 @@ -1178,60 +1105,63 @@ Test ↥ 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 are the ways to instantiate the Class class? -**Types of Java Constructors:** +**1. Using new keyword:** -* Default Constructor (or) no-arg Constructor -* Parameterized Constructor +```java +MyObject object = new MyObject(); +``` -**Example:** Default Constructor (or) no-arg constructor +**2. Using Class.forName():** ```java -/** - * Default Constructor - */ -public class Car { - Car() { - System.out.println("Default Constructor of Car class called"); - } +MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); +``` - public static void main(String args[]) { - // Calling the default constructor - Car c = new Car(); - } -} +**3. Using clone():** + +```java +MyObject anotherObject = new MyObject(); +MyObject object = (MyObject) anotherObject.clone(); ``` -Output +**4. Using object deserialization:** ```java -Default Constructor of Car class called +ObjectInputStream inStream = new ObjectInputStream(anInputStream ); +MyObject object = (MyObject) inStream.readObject(); ``` -**Example:** Parameterized Constructor + + +## 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 /** - * Parameterized Constructor + * Immutable Object */ -public class Car { - String carColor; - - Car(String carColor) { - this.carColor = carColor; - } +public class DateContainer { + private final Date date; - public void display() { - System.out.println("Color of the Car is : " + carColor); + public DateContainer() { + this.date = new Date(); } - public static void main(String args[]) { - // Calling the parameterized constructor - Car c = new Car("Blue"); - c.display(); + public Date getDate() { + return new Date(date.getTime()); } } ``` @@ -1240,155 +1170,193 @@ public class Car { ↥ back to top -## 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. +## Q. How can we create an immutable class in Java? -There are a few restrictions imposed on a static method +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. -* 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 ). -* 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 +**Rules to create immutable classes:** -**Example:** +* 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 /** - * Static Methods + * Immutable Class */ -class Parent { - static void display() { - System.out.println("Super class"); - } -} +public final class Employee { -public class Example extends Parent { - void display() // trying to override display() { - System.out.println("Sub class"); + final String pancardNumber; + + public Employee(String pancardNumber) { + this.pancardNumber = pancardNumber; } - public static void main(String[] args) { - Parent obj = new Example(); - obj.display(); + public String getPancardNumber() { + return pancardNumber; } } ``` -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() - ^ -overridden method is static - -1 error -``` - -## Q. What is the final variable, final class, and final blank variable? +## Q. How bootstrap class loader works in java? -**1. Final Variable:** +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: -Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. +**1. Bootstrap Class Loader:** It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes -**Example:** +**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 /** - * Final Variable + * ClassLoader */ -class Demo { - - final int MAX_VALUE = 99; +import java.util.logging.Level; +import java.util.logging.Logger; - void myMethod() { - MAX_VALUE = 101; - } +public class ClassLoaderTest { public static void main(String args[]) { - Demo obj = new Demo(); - obj.myMethod(); + 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); + } } } ``` -Output - -```java -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) -``` + -**2. Blank final variable:** +## Q. How can we create a object of a class without using new operator? -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` ). +Different ways to create an object in Java -**Example:** +* **Using new Keyword:** ```java -/** - * Blank final variable - */ -class Demo { - // Blank final variable - final int MAX_VALUE; +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(); + } +} +``` - Demo() { - // It must be initialized in constructor - MAX_VALUE = 100; - } +* **Using New Instance (Reflection)** - void myMethod() { - System.out.println(MAX_VALUE); - } +```java +class CreateObjectClass { + static int j = 10; + CreateObjectClass() { + i = j++; + } + int i; + @Override + public String toString() { + return "Value of i :" + i; + } +} - public static void main(String args[]) { - Demo obj = new Demo(); - obj.myMethod(); - } +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(); + } + } } ``` -Output +* **Using Clone:** ```java -100 -``` - -**3. Final Method:** + 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; + } +} -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. +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(); + } + } +} +``` -**Example:** +* **Using ClassLoader** ```java -/** - * Final Method - */ -class XYZ { - final void demo() { - System.out.println("XYZ Class Method"); - } +class CreateObjectWithClassLoader { + static int j = 10; + CreateObjectWithClassLoader() { + i = j++; + } + int i; + @Override + public String toString() { + return "Value of i :" + i; + } } -class ABC extends XYZ { - void demo() { - System.out.println("ABC Class Method"); - } - - public static void main(String args[]) { - ABC obj = new ABC(); - obj.demo(); - } +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); + } } ``` @@ -1396,87 +1364,87 @@ class ABC extends XYZ { ↥ 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 -/** - * Static Import - */ -import static java.lang.System.*; +## Q. What are methods of Object Class? -class StaticImportExample { +The Object class is the parent class of all the classes in java by default. - public static void main(String args[]) { - out.println("Hello");// Now no need of System.out - out.println("Java"); - } -} -``` + + + + + + + + + + + + + +
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.
-## Q. Name some classes present in java.util.regex package? +## # 6. JAVA CONSTRUCTORS -The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. +
-**Regular Expression Package:** +## Q. How many types of constructors are used in Java? -* MatchResult interface -* Matcher class -* Pattern class -* PatternSyntaxException class +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. -**Example:** +**Types of Java Constructors:** + +* Default Constructor (or) no-arg Constructor +* Parameterized Constructor + +**Example:** Default Constructor (or) no-arg constructor ```java /** - * Regular Expression + * Default Constructor */ -import java.util.regex.*; +public class Car { + Car() { + System.out.println("Default Constructor of Car class called"); + } -public class Index { public static void main(String args[]) { - - // Pattern, String - boolean b = Pattern.matches(".s", "as"); - - System.out.println("Match: " + b); + // Calling the default constructor + Car c = new Car(); } } ``` - - -## Q. How will you invoke any external process in Java? +Output -In java, external process can be invoked using **exec()** method of **Runtime Class**. +```java +Default Constructor of Car class called +``` -**Example:** +**Example:** Parameterized Constructor ```java /** - * exec() + * Parameterized Constructor */ -import java.io.IOException; +public class Car { + String carColor; -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(); - } + 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(); } } ``` @@ -1485,160 +1453,166 @@ class ExternalProcessExample { ↥ back to top -## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? +## Q. How can constructor chaining be done using this keyword? -`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. +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 – -**Example:** +* **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 /** - * BufferedInputStream + * Constructor Chaining + * within same class Using this() keyword */ -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(); - } - } - } -} +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(); + } +} ``` -Output +Ouput: ```java -This is an example of reading data from file +30 +10 +The Default constructor ``` -**Example:** - ```java /** - * BufferedOutputStream + * Constructor Chaining to + * other class using super() keyword */ -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(); - } - } - } -} +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 +Output: ```java -This is an example of writing data to a file +Calling parameterized constructor of base +Calling parameterized constructor of derived ``` -## 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. What is a private constructor? -**Example:** +* 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 -/** - * 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); +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(); + } - // add others permissions - perms.add(PosixFilePermission.OTHERS_READ); - perms.add(PosixFilePermission.OTHERS_WRITE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); + 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(); + } +} - Files.setPosixFilePermissions(Paths.get("/Users/run.sh"), perms); +class Visitor{ + { + new MyClass();//gives compilation error as MyClass() has private access in MyClass } } ``` @@ -1647,280 +1621,273 @@ public class FilePermissions { ↥ back to top -## Q. In Java, How many ways you can take input from the console? +## # 7. JAVA ARRAY -In Java, there are three different ways for reading input from the user in the command line environment ( console ). +
-**1. Using Buffered Reader Class:** +## Q. What is copyonwritearraylist in java? -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. +* `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 -/** - * Buffered Reader Class - */ -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; + 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 + } +``` -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(); +## # 8. JAVA STRINGS - // Printing the read line - System.out.println(name); - } -} -``` +
-**2. Using Scanner Class:** +## Q. What is the difference between creating String as new() and literal? -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. +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 /** - * Scanner Class + * String literal */ -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() ). +String a = "abc"; +String b = "abc"; +System.out.println(a == b); // true -```java /** - * Console Class + * Using new() */ -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); - } -} +String c = new String("abc"); +String d = new String("abc"); +System.out.println(c == d); // false ``` -## 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; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -class Super implements Serializable { - private static final long serialVersionUID = 1L; -} - -class Sub extends Super { +## Q. What is difference between String, StringBuffer and StringBuilder? - private static final long serialVersionUID = 1L; - private Integer id; +**1. Mutability Difference:** - public Sub(Integer id) { - this.id = id; - } +`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. - @Override - public String toString() { - return "Employee [id=" + id + "]"; - } +**2. Thread-Safety Difference:** - /* - * define how Serialization process will write objects. - */ - private void writeObject(ObjectOutputStream os) throws NotSerializableException { - throw new NotSerializableException("This class cannot be Serialized"); - } -} +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. -public class SerializeDeserialize { +**Example:** +```java +/** + * StringBuffer + */ +public class BufferTest { 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(); - } + StringBuffer buffer = new StringBuffer("Hello"); + buffer.append(" World"); + System.out.println(buffer); } } ``` -Output +**Example:** ```java -Serialization process has started, serializing objects... -java.io.NotSerializableException: This class cannot be Serialized - at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) - at java.io.ObjectOutputStream.writeSerialData(Unknown Source) - at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) - at java.io.ObjectOutputStream.writeObject0(Unknown Source) - at java.io.ObjectOutputStream.writeObject(Unknown Source) - at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) +/** + * StringBuilder + */ +public class BuilderTest { + public static void main(String[] args) { + StringBuilder builder = new StringBuilder("Hello"); + builder.append(" World"); + System.out.println(builder); + } +} ``` -## Q. What is the difference between Serializable and Externalizable interface? +## Q. Why string is immutable in java? -|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. | +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 are the ways to instantiate the Class class? - -**1. Using new keyword:** - -```java -MyObject object = new MyObject(); -``` - -**2. Using Class.forName():** +## Q. What is Java String Pool? -```java -MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); -``` +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. -**3. Using clone():** +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 -MyObject anotherObject = new MyObject(); -MyObject object = (MyObject) anotherObject.clone(); -``` +/** + * String Pool + */ +public class StringPool { -**4. Using object deserialization:** + public static void main(String[] args) { + String s1 = "Java"; + String s2 = "Java"; + String s3 = new String("Java"); -```java -ObjectInputStream inStream = new ObjectInputStream(anInputStream ); -MyObject object = (MyObject) inStream.readObject(); + System.out.println("s1 == s2 :" + (s1 == s2)); // true + System.out.println("s1 == s3 :" + (s1 == s3)); // false + } +} ``` -## Q. What is the purpose of using javap? +## Q. What is difference between String, StringBuilder and StringBuffer? -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. +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. - ```java - /** - * Java Disassembler - */ -class Simple { - public static void main(String args[]) { - System.out.println("Hello World"); - } -} -``` +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. -```cmd -cmd> javap Simple.class +**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 +Output ```java -Compiled from ".java" -class Simple { - Simple(); - public static void main(java.lang.String[]); -} +String: Hello +StringBuilder: World +StringBuffer: World ``` -## Q. What are autoboxing and unboxing? +## # 9. JAVA REFLECTION -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 +## # 10. JAVA STREAMS -```java -/** - * 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); - } -} -``` +## # 11. JAVA REGULAR EXPRESSIONS -**Example:** Unboxing +
+ +## 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 /** - * Unboxing + * Regular Expression */ -class UnboxingExample { +import java.util.regex.*; + +public class Index { public static void main(String args[]) { - Integer i = new Integer(50); - int a = i; - System.out.println(a); + // Pattern, String + boolean b = Pattern.matches(".s", "as"); + + System.out.println("Match: " + b); } } ``` @@ -1929,80 +1896,164 @@ class UnboxingExample { ↥ back to top -## Q. What is a native method? +## # 12. JAVA FILE HANDLING -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: +
-**Main.java:** +## 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 -public class Main { - public native int intMethod(int i); +/** + * 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) { - System.loadLibrary("Main"); - System.out.println(new Main().intMethod(2)); + 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(); + } + } } } ``` -**Main.c:** - -```c -#include -#include "Main.h" +Output -JNIEXPORT jint JNICALL Java_Main_intMethod( - JNIEnv *env, jobject obj, jint i) { - return i * i; -} +```java +This is an example of reading data from file ``` -**Compile and Run:** +**Example:** ```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 +/** + * 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 -4 +This is an example of writing data to a file ``` -## 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. +## Q. How to set the Permissions to a file in Java? -**Creating an Immutable Object:** +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. -* 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. +**Example:** ```java /** - * Immutable Object + * FilePermissions */ -public class DateContainer { - private final Date date; +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 DateContainer() { - this.date = new Date(); - } +public class FilePermissions { - public Date getDate() { - return new Date(date.getTime()); + 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); } } ``` @@ -2011,113 +2062,177 @@ public class DateContainer { ↥ back to top -## Q. The difference between Inheritance and Composition? +## Q. Give the hierarchy of InputStream and OutputStream classes? -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"**. +A stream can be defined as a sequence of data. There are two kinds of Streams − -**Example:** Inheritance +* **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 /** - * Inheritance + * Byte Streams */ -class Fruit { - // ... -} +import java.io.*; -class Apple extends Fruit { - // ... +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(); + } + } + } } ``` -**Example:** Composition +**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 /** - * Composition + * Character Streams */ -class Fruit { - // ... -} - -class Apple { - private Fruit fruit = new Fruit(); - // ... -} -``` +import java.io.*; - +public class CopyFile { -## Q. The difference between DOM and SAX parser in Java? + public static void main(String args[]) throws IOException { + FileReader in = null; + FileWriter out = null; -DOM and SAX parser are extensively used to read and parse XML file in java and have their own set of advantage and disadvantage. + try { + in = new FileReader("input.txt"); + out = new FileWriter("output.txt"); -| |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| + int c; + while ((c = in.read()) != -1) { + out.write(c); + } + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } +} +``` -## Q. What is the difference between creating String as new() and literal? +## Q. How serialization works in java? -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. +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 /** - * String literal - */ -String a = "abc"; -String b = "abc"; -System.out.println(a == b); // true +* Serialization and Deserialization +*/ +import java.io.*; -/** - * Using new() - */ -String c = new String("abc"); -String d = new String("abc"); -System.out.println(c == d); // false -``` +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; + } +} -## Q. How can we create an immutable class in Java? +public class SerialExample { -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. + 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); + } -**Rules to create immutable classes:** + public static void main(String[] args) { + Employee object = new Employee("ab", 20, 2, 1000); + String filename = "file.txt"; -* 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 + // Serialization + try { + // Saving of object in a file + FileOutputStream file = new FileOutputStream(filename); + ObjectOutputStream out = new ObjectOutputStream(file); -```java -/** - * Immutable Class - */ -public final class Employee { + // Method for serialization of object + out.writeObject(object); - final String pancardNumber; + out.close(); + file.close(); - public Employee(String pancardNumber) { - this.pancardNumber = pancardNumber; - } + 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"); + } - public String getPancardNumber() { - return pancardNumber; + 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"); + } } } ``` @@ -2126,94 +2241,93 @@ public final class Employee { ↥ back to top -## Q. What is difference between String, StringBuffer and StringBuilder? +## # 13. JAVA EXCEPTIONS -**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. +## Q. What are the types of Exceptions? -**2. Thread-Safety Difference:** +Exception is an error event that can happen during the execution of a program and disrupts its normal flow. -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. +**1. Checked Exception**: -**Example:** +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. -```java -/** - * StringBuffer - */ -public class BufferTest { - public static void main(String[] args) { - StringBuffer buffer = new StringBuffer("Hello"); - buffer.append(" World"); - System.out.println(buffer); - } -} -``` +**2. Unchecked Exception**: -**Example:** +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. -```java -/** - * StringBuilder - */ -public class BuilderTest { - public static void main(String[] args) { - StringBuilder builder = new StringBuilder("Hello"); - builder.append(" World"); - System.out.println(builder); - } -} -``` +**3. Error**: + +Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. -## Q. What is a Memory Leak? - -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. Explain hierarchy of Java Exception classes? -Some tools that do memory management to identifies useless objects or memeory leaks like: +The **java.lang.Throwable** class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. -* HP OpenView -* HP JMETER -* JProbe -* IBM Tivoli +

+ Exception in Java +

**Example:** ```java /** - * Memory Leaks + * Exception classes */ -import java.util.Vector; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; -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"); - } +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"); + } + } + } } ``` -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 - @@ -2358,229 +2472,249 @@ You shouldn\'t divide number by zero ↥ back to top -## Q. The difference between Serial and Parallel Garbage Collector? +## Q. While overriding a method can you throw another exception or broader exception? -**1. Serial Garbage Collector:** +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. -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. +**Example:** -Turn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector. +```java +class A { + public void message() throws IOException {..} +} -**2. Parallel Garbage Collector:** +class B extends A { + @Override + public void message() throws SocketException {..} // allowed -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. + @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 difference between WeakReference and SoftReference in Java? +## Q. What is checked, unchecked exception and errors? -**1. Weak References:** +**1. Checked Exception**: -Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. +* 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). -```java -/** - * Weak Reference - */ -import java.lang.ref.WeakReference; +**Example:** **IOException, SQLException** etc. -class MainClass { - public void message() { - System.out.println("Weak References Example"); - } -} +```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(); + } +} +``` -public class Example { - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); +output: - // 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(); - } -} +```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) ``` -**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. +After adding IOException ```java -/** - * Soft Reference - */ -import java.lang.ref.SoftReference; - -class MainClass { - public void message() { - System.out.println("Soft References Example"); - } -} +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(); + } +} +``` -public class Example { - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); +output: - // 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(); - } -} +```java +Output: First three lines of file “C:\assets\file.txt” ``` - - -## Q. What is a compile time constant in Java? +**2. Unchecked Exception**: -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. +* 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. -**Compile time constant must be:** +**Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. -* Declared final -* Primitive or String -* Initialized within declaration -* Initialized with constant expression +```java +class Main { + public static void main(String args[]) { + int x = 0; + int y = 10; + int z = y/x; + } +} +``` -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. +Output: ```java -private final int x = 10; +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. 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 -/** - * ClassLoader - */ -import java.util.logging.Level; -import java.util.logging.Logger; +## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? -public class ClassLoaderTest { +`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. - public static void main(String args[]) { - try { - // printing ClassLoader of this class - System.out.println("ClassLoader : " + ClassLoaderTest.class.getClassLoader()); +`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. - // 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); - } - } -} -``` +`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. -## 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. +## # 14. JAVA INHERITANCE -Since string is immutable it can safely share between many threads and avoid any synchronization issues in java. +
- +## Q. What is the difference between aggregation and composition? -## Q. What is Java String Pool? +**1. Aggregation:** -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. +We call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object. -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:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes ```java /** - * String Pool + * Aggregation */ -public class StringPool { +public class Organization { + private List employees; +} - public static void main(String[] args) { - String s1 = "Java"; - String s2 = "Java"; - String s3 = new String("Java"); +public class Person { + private String name; +} +``` - System.out.println("s1 == s2 :" + (s1 == s2)); // true - System.out.println("s1 == s3 :" + (s1 == s3)); // false +**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; +} +``` -## Q. How Garbage collector algorithm works? +

+ Aggregation +

-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. + + + + + + + + + + + +
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.
-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 +*Note: "final" keyword is used in Composition to make sure child variable is initialized.* -## Q. How to create marker interface? +## Q. The difference between Inheritance and Composition? -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. +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"**. -**Syntax:** +**Example:** Inheritance ```java -public interface Interface_Name { +/** + * Inheritance + */ +class Fruit { + // ... +} +class Apple extends Fruit { + // ... } ``` -**Example:** +**Example:** Composition ```java /** - * Maker Interface + * Composition */ -interface Marker { -} - -class MakerExample implements Marker { - // do some task +class Fruit { + // ... } -class Main { - public static void main(String[] args) { - MakerExample obj = new MakerExample(); - if (obj instanceOf Marker) { - // do some task - } - } +class Apple { + private Fruit fruit = new Fruit(); + // ... } ``` @@ -2588,365 +2722,293 @@ class Main { ↥ back to top -## Q. How serialization works in java? +## Q. Can you declare the main method as final? -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. +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 -/** -* 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 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"); + } +} +``` -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(); +Output - 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"); - } - } -} +```java +Cannot override the final method from Test. ``` -## Q. Java Program to Implement Singly Linked List? +## Q. What is covariant return type? -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. +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 -public class SinglyLinkedList { - // Represent a node of the singly linked list - class Node{ - int data; - Node next; - - public Node(int data) { - this.data = data; - this.next = null; - } - } - - // Represent the head and tail of the singly linked list - public Node head = null; - public Node tail = null; - - // addNode() will add a new node to the list - public void addNode(int data) { - // Create a new node - Node newNode = new Node(data); - - // Checks if the list is empty - if(head == null) { - // If list is empty, both head and tail will point to new node - head = newNode; - tail = newNode; - } - else { - // newNode will be added after tail such that tail's next will point to newNode - tail.next = newNode; - // newNode will become new tail of the list - tail = newNode; - } - } - - // display() will display all the nodes present in the list - public void display() { - // Node current will point to head - Node current = head; - - if(head == null) { - System.out.println("List is empty"); - return; - } - System.out.println("Nodes of singly linked list: "); - while(current != null) { - // Prints each node by incrementing pointer - System.out.print(current.data + " "); - current = current.next; - } - System.out.println(); - } - - public static void main(String[] args) { - - SinglyLinkedList sList = new SinglyLinkedList(); - - // Add nodes to the list - sList.addNode(10); - sList.addNode(20); - sList.addNode(30); - sList.addNode(40); - - // Displays the nodes present in the list - sList.display(); - } -} +/** + * 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:** +Output: ```java -Nodes of singly linked list: -10 20 30 40 +Subclass ``` -## Q. While overriding a method can you throw another exception or broader exception? +## Q. Can you explain Liskov Substitution principle? -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. +Liskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.** -**Example:** +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 -class A { - public void message() throws IOException {..} +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..."); + } } -class B extends A { - @Override - public void message() throws SocketException {..} // allowed +public class VlcMediaPlayer extends MediaPlayer {} - @Override - public void message() throws SQLException {..} // NOT allowed +public class WinampMediaPlayer extends MediaPlayer { - public static void main(String args[]) { - A a = new B(); - try { - a.message(); - } catch (IOException ex) { - // forced to catch this by the compiler - } - } + // Play video is not supported in Winamp player + public void playVideo() { + throw new VideoUnsupportedException(); + } } -``` - +public class VideoUnsupportedException extends RuntimeException { -## Q. What is checked, unchecked exception and errors? + private static final long serialVersionUID = 1 L; -**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). +public class ClientTestProgram { -**Example:** **IOException, SQLException** etc. + public static void main(String[] args) { -```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(); - } -} -``` + // Created list of players + List < MediaPlayer > allPlayers = new ArrayList < MediaPlayer > (); + allPlayers.add(new VlcMediaPlayer()); + allPlayers.add(new DivMediaPlayer()); -output: + // Play video in all players + playVideoInAllMediaPlayers(allPlayers); -```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) -``` + // Well - all works as of now...... :-) + System.out.println("---------------------------"); -After adding IOException + // Now adding new Winamp player + allPlayers.add(new WinampMediaPlayer()); -```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(); - } -} + // 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(); + } + } +} ``` -output: +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 -Output: First three lines of file “C:\assets\file.txt” -``` +public class MediaPlayer { -**2. Unchecked Exception**: + // Play audio implementation + public void playAudio() { + System.out.println("Playing audio..."); + } +} -* 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. +//separated video playing ability from base class +public class VideoMediaPlayer extends MediaPlayer { -**Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. + // Play video implementation + public void playVideo() { + System.out.println("Playing video..."); + } +} -```java -class Main { - public static void main(String args[]) { - int x = 0; - int y = 10; - int z = y/x; - } -} -``` +public class DivMediaPlayer extends VideoMediaPlayer {} -Output: +public class VlcMediaPlayer extends VideoMediaPlayer {} -```java -Exception in thread "main" java.lang.ArithmeticException: / by zero - at Main.main(Main.java:5) -Java Result: 1 -``` +//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 {} -**3. Error**: + /** + * This method is playing video in all players + * + * @param allPlayers + */ + public static void playVideoInAllMediaPlayers(List allPlayers) { -**Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. -Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. + 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*. -## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? +## # 15. JAVA METHOD OVERRIDING -`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. +## # 16. JAVA POLYMORPHISM -`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. +
- +## Q. What is the difference between compile-time polymorphism and runtime polymorphism? -## Q. What do we mean by weak reference? +There are two types of polymorphism in java: -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. +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 /** -* Weak reference -*/ -import java.lang.ref.WeakReference; + * 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 { -class WeakReferenceExample { - - public void message() { - System.out.println("Weak Reference Example!"); - } -} + public void myMethod() { + System.out.println("Overridden Method"); + } +} -public class MainClass { +public class XYZ extends ABC { - public static void main(String[] args) { - // Strong Reference - WeakReferenceExample obj = new WeakReferenceExample(); - obj.message(); - - // Creating Weak Reference to WeakReferenceExample-type object to which 'obj' - // is also pointing. - WeakReference weakref = new WeakReference(obj); + public void myMethod() { + System.out.println("Overriding Method"); + } - obj = null; // is available for garbage collection. - obj = weakref.get(); - obj.message(); - } -} + public static void main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } +} ``` -Output +Output: ```java -Weak Reference Example! -Weak Reference Example! +Overriding Method ```
@@ -3020,653 +3082,471 @@ Overriding Method ↥ back to top
-## 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. - - - -## 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. -1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. -1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. -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. What is runtime polymorphism in java? -## Q. How Encapsulation concept implemented 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. -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`. +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. -To achieve encapsulation in Java − +```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;} +} -* Declare the variables of a class as private. -* Provide public setter and getter methods to modify and view the variables values. +Bank b; +b=new SBI(); +System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); -**Example:** +b=new ICICI(); +System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); -```java -public class EncapClass { - private String name; +b=new AXIS(); +System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); - public String getName() { - return name; - } - public void setName(String newName) { - name = newName; - } -} +System.out.println("Bank Rate of Interest: "+b.roi); -public class MainClass { +/**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 - public static void main(String args[]) { - EncapClass obj = new EncapClass(); - obj.setName("Pradeep Kumar"); - System.out.print("Name : " + obj.getName()); - } -} +//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. +**/ ``` -## 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. +## # 17. JAVA ABSTRACTION -**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(); - } -} -``` +## Q. What is the difference between abstract class and interface? -Output: +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. -```java -Generic Class Example ! -100 -``` +|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 is difference between String, StringBuilder and StringBuffer? +## Q. What are Wrapper classes? -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 wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. -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. +**Use of Wrapper classes in Java:** -**Situations:** +* **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. -* 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. +* **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. -**Example:** +* **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 -class StringExample { +/** + * 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 - // 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); - } -} + System.out.println(a + " " + i + " " + j); + } +} ``` -Output +Output ```java -String: Hello -StringBuilder: World -StringBuffer: World +20 20 20 ``` -## Q. How can we create a object of a class without using new operator? +## Q. What is the difference between abstraction and encapsulation? -Different ways to create an object in Java +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. -* **Using new Keyword:** +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. -```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(); - } -} -``` +**Difference:** -* **Using New Instance (Reflection)** + + + + + + + + + + + + +
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.
-```java -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(); - } - } -} -``` +## # 18. JAVA INTERFACES -* **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. Can we use private or protected member variables in an interface? -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(); - } - } +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; } ``` -* **Using ClassLoader** +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 -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); - } +public interface Test { + public static final string name1; + public static final String email; + public static final pass; } ``` - - -## 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.
+* 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. 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: +## Q. When can an object reference be cast to a Java interface reference? - - 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. +An interface reference can point to any object of a class that implements this interface ```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 +/** + * Interface + */ +interface MyInterface { + void display(); +} - 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 - } +public class TestInterface implements MyInterface { - 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 - } + void display() { + System.out.println("Hello World"); + } + + public static void main(String[] args) { + MyInterface myInterface = new TestInterface(); + MyInterface.display(); + } +} ``` -## Q. Can you explain Liskov Substitution principle? +## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface? -Liskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.** +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. -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. +```java +/** + * Serialization + */ +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; -`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**. +class Super implements Serializable { + private static final long serialVersionUID = 1L; +} -```java -public class MediaPlayer { +class Sub extends Super { - // Play audio implementation - public void playAudio() { - System.out.println("Playing audio..."); + private static final long serialVersionUID = 1L; + private Integer id; + + public Sub(Integer id) { + this.id = id; + } + + @Override + public String toString() { + return "Employee [id=" + id + "]"; } - // Play video implementation - public void playVideo() { - System.out.println("Playing video..."); + /* + * define how Serialization process will write objects. + */ + private void writeObject(ObjectOutputStream os) throws NotSerializableException { + throw new NotSerializableException("This class cannot be Serialized"); } } -public class VlcMediaPlayer extends MediaPlayer {} +public class SerializeDeserialize { -public class WinampMediaPlayer extends MediaPlayer { + public static void main(String[] args) { - // Play video is not supported in Winamp player - public void playVideo() { - throw new VideoUnsupportedException(); + 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(); + } } } +``` -public class VideoUnsupportedException extends RuntimeException { - - private static final long serialVersionUID = 1 L; +Output -} +```java +Serialization process has started, serializing objects... +java.io.NotSerializableException: This class cannot be Serialized + at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) + at java.io.ObjectOutputStream.writeSerialData(Unknown Source) + at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) + at java.io.ObjectOutputStream.writeObject0(Unknown Source) + at java.io.ObjectOutputStream.writeObject(Unknown Source) + at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) +``` -public class ClientTestProgram { + - public static void main(String[] args) { +## Q. What is the difference between Serializable and Externalizable interface? - // Created list of players - List < MediaPlayer > allPlayers = new ArrayList < MediaPlayer > (); - allPlayers.add(new VlcMediaPlayer()); - allPlayers.add(new DivMediaPlayer()); +|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. | - // Play video in all players - playVideoInAllMediaPlayers(allPlayers); + - // Well - all works as of now...... :-) - System.out.println("---------------------------"); +## Q. How to create marker interface? - // Now adding new Winamp player - allPlayers.add(new WinampMediaPlayer()); +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. - // 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); - } +**Syntax:** - /** - * This method is playing video in all players - * - * @param allPlayers - */ - public static void playVideoInAllMediaPlayers(List < MediaPlayer > allPlayers) { +```java +public interface Interface_Name { - 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 +**Example:** ```java -public class MediaPlayer { - - // Play audio implementation - public void playAudio() { - System.out.println("Playing audio..."); - } +/** + * Maker Interface + */ +interface Marker { } -//separated video playing ability from base class -public class VideoMediaPlayer extends MediaPlayer { - - // Play video implementation - public void playVideo() { - System.out.println("Playing video..."); - } +class MakerExample implements Marker { + // do some task } -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(); +class Main { + public static void main(String[] args) { + MakerExample obj = new MakerExample(); + if (obj instanceOf Marker) { + // do some task } } +} ``` -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*. + + +## 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 are the different access specifiers available in java? +## Q. What is a Functional Interface? -* 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. +A **functional interface** is an interface that defines only one abstract method. -```java - ... /* 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 */ - ... -``` +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 runtime polymorphism in java? +## # 19. JAVA ENCAPSULATION -**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. +## 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 -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;} -} +public class EncapClass { + private String name; -Bank b; -b=new SBI(); -System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); + public String getName() { + return name; + } + public void setName(String newName) { + name = newName; + } +} -b=new ICICI(); -System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); +public class MainClass { -b=new AXIS(); -System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); + public static void main(String args[]) { + EncapClass obj = new EncapClass(); + obj.setName("Pradeep Kumar"); + System.out.print("Name : " + obj.getName()); + } +} +``` -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 +## # 20. MISCELLANEOUS + +
+ +## Q. How will you invoke any external process in Java? + +In java, external process can be invoked using **exec()** method of **Runtime Class**. -//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. -**/ +**Example:** + +```java +/** + * exec() + */ +import java.io.IOException; + +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 is a private constructor? +## Q. What is the static import? -* 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** +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 -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(); - } +/** + * Static Import + */ +import static java.lang.System.*; - 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 StaticImportExample { -class Visitor{ - { - new MyClass();//gives compilation error as MyClass() has private access in MyClass + public static void main(String args[]) { + out.println("Hello");// Now no need of System.out + out.println("Java"); } } ``` @@ -3675,216 +3555,405 @@ class Visitor{ ↥ back to top -## Q. What are the important features of Java 8 release? +## Q. What is the difference between factory and abstract factory pattern? -* 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. +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. + +**Example:** credit card validator factory which returns a different validator for each card type. + +```java +/** + * 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. Can you declare an interface method static? +## Q. What are the methods used to implement for key Object in HashMap? -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. +**1. equals()** and **2. hashcode()** + +Class inherits methods from the following classes in terms of HashMap + +* java.util.AbstractMap +* java.util.Object +* java.util.Map -## Q. What is a lambda? +## Q. What is a Memory Leak? - 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 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. -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. +Some tools that do memory management to identifies useless objects or memeory leaks like: -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. +* HP OpenView +* HP JMETER +* JProbe +* IBM Tivoli + +**Example:** ```java -interface Operationable { - int calculate ( int x , int y ); -} +/** + * Memory Leaks + */ +import java.util.Vector; -public static void main ( String [] args) { - Operationable operation = (x, y) - > x + y; - int result = operation.calculate ( 10 , 20 ); - System.out.println (result); // 30 +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"); + } } ``` -In fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java. +Output -* _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. +```java +Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed +``` -* _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method: +**Types of Memory Leaks in Java:** -```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; -``` +* 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 -* 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"); -} +## Q. The difference between Serial and Parallel Garbage Collector? -// _ 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 ' : +**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. -Operationable operation = ( int x, int y) - > { - if (y == 0 ) { - return 0 ; +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. + + + +## Q. What is difference between WeakReference and SoftReference in Java? + +**1. Weak References:** + +Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. + +```java +/** + * Weak Reference + */ +import java.lang.ref.WeakReference; + +class MainClass { + public void message() { + System.out.println("Weak References Example"); } - else { - return x / y; +} + +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(); } -}; +} ``` -* Passing a lambda expression as a method parameter +**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 -interface Condition { - boolean isAppropriate ( int n ); -} +/** + * Soft Reference + */ +import java.lang.ref.SoftReference; -private static int sum ( int [] numbers, Condition condition) { - int result = 0 ; - for ( int i : numbers) { - if (condition.isAppropriate(i)) { - result + = i; - } +class MainClass { + public void message() { + System.out.println("Soft References Example"); } - 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 )); -} +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. 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. +## Q. How Garbage collector algorithm works? -* immutable ( effectively final - not necessarily marked as final) local variables; -* class fields -* static variables. +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. -The default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression. +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. How to sort a list of strings using a lambda expression? +## 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. + +**Example:** ```java -public static List < String > sort ( List < String > list) { - Collections.sort(list, (a, b) -> a.compareTo(b)); - return list; -} +public class SinglyLinkedList { + // Represent a node of the singly linked list + class Node{ + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } + } + + // Represent the head and tail of the singly linked list + public Node head = null; + public Node tail = null; + + // addNode() will add a new node to the list + public void addNode(int data) { + // Create a new node + Node newNode = new Node(data); + + // Checks if the list is empty + if(head == null) { + // If list is empty, both head and tail will point to new node + head = newNode; + tail = newNode; + } + else { + // newNode will be added after tail such that tail's next will point to newNode + tail.next = newNode; + // newNode will become new tail of the list + tail = newNode; + } + } + + // display() will display all the nodes present in the list + public void display() { + // Node current will point to head + Node current = head; + + if(head == null) { + System.out.println("List is empty"); + return; + } + System.out.println("Nodes of singly linked list: "); + while(current != null) { + // Prints each node by incrementing pointer + System.out.print(current.data + " "); + current = current.next; + } + System.out.println(); + } + + public static void main(String[] args) { + + SinglyLinkedList sList = new SinglyLinkedList(); + + // Add nodes to the list + sList.addNode(10); + sList.addNode(20); + sList.addNode(30); + sList.addNode(40); + + // Displays the nodes present in the list + sList.display(); + } +} +``` + +**Output:** + +```java +Nodes of singly linked list: +10 20 30 40 ``` -## Q. What is a method reference? +## Q. What do we mean by weak 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. +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 -private interface Measurable { - public int length ( String string ); -} +/** +* Weak reference +*/ +import java.lang.ref.WeakReference; -public static void main ( String [] args) { - Measurable a = String::length; - System.out.println(a.length("abc")); -} +class WeakReferenceExample { + + public void message() { + System.out.println("Weak Reference Example!"); + } +} + +public class MainClass { + + public static void main(String[] args) { + // Strong Reference + WeakReferenceExample obj = new WeakReferenceExample(); + obj.message(); + + // Creating Weak Reference to WeakReferenceExample-type object to which 'obj' + // is also pointing. + WeakReference weakref = new WeakReference(obj); + + obj = null; // is available for garbage collection. + obj = weakref.get(); + obj.message(); + } +} ``` -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. +Output + +```java +Weak Reference Example! +Weak Reference Example! +``` -## Q. What types of method references do you know? +## Q. What are the different types of JDBC Driver? -* on the static method; -* per instance method; -* to the constructor. +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. +1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. +1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. +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. Explain the expression `System.out::println`? +## Q. Do you know Generics? How did you used in your coding? -The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. +`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:** -## Q. What is a Functional Interface? +* **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. -A **functional interface** is an interface that defines only one abstract method. +**Example:** -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. +```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(); + } +} +``` -An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. +Output: + +```java +Generic Class Example ! +100 +``` + ## 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: From 6e33fc994ed400ea328560626fc419f6d04d80ae Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 14:54:24 +0530 Subject: [PATCH 087/100] Update README.md --- README.md | 3623 ++++++++++++++++++++++++++--------------------------- 1 file changed, 1811 insertions(+), 1812 deletions(-) diff --git a/README.md b/README.md index 387675e..5a669c3 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,47 @@ The specified expression illustrates passing a reference to a static method of a ↥ back to top +## 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 ()); +``` + + + ## # 2. JAVA ARCHITECTURE
@@ -1007,104 +1048,6 @@ The purpose of the System class is to provide access to system resources. It con ↥ back to top -## 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 -``` - - - ## Q. What are the ways to instantiate the Class class? **1. Using new keyword:** @@ -1387,6 +1330,23 @@ The Object class is the parent class of all the classes in java by default. ↥ 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" +``` + + + ## # 6. JAVA CONSTRUCTORS
@@ -1850,536 +1810,389 @@ StringBuffer: World ↥ back to top -## # 9. JAVA REFLECTION +## 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: -## # 10. JAVA STREAMS +```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 REGULAR EXPRESSIONS +## # 9. JAVA REFLECTION
-## Q. Name some classes present in java.util.regex package? +## Q. What is Java Reflection API? -The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. +Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at **runtime**. -**Regular Expression Package:** +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. -* MatchResult interface -* Matcher class -* Pattern class -* PatternSyntaxException class +* forName() method of Class class +* getClass() method of Object class +* the .class syntax -**Example:** +**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 /** - * Regular Expression + * forName() */ -import java.util.regex.*; +class Simple { +} -public class Index { +class Test { public static void main(String args[]) { - - // Pattern, String - boolean b = Pattern.matches(".s", "as"); - - System.out.println("Match: " + b); + Class c = Class.forName("Simple"); + System.out.println(c.getName()); } } ``` - - -## # 12. JAVA FILE HANDLING - -
+Output -## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? +```java +Simple +``` -`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. +**2. getClass() method:** -**Example:** +It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives. ```java /** - * BufferedInputStream + * getClass */ -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; +class Simple { +} -public class BufferedInputStreamExample { +class Test { + void printName(Object obj) { + Class c = obj.getClass(); + System.out.println(c.getName()); + } - 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(); - } - } - } -} -``` + public static void main(String args[]) { + Simple s = new Simple(); + Test t = new Test(); + t.printName(s); + } +} +``` Output ```java -This is an example of reading data from file +Simple ``` -**Example:** +**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 /** - * BufferedOutputStream + * .class Syntax */ -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(); - } - } - } -} +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 -This is an example of writing data to a file +boolean +Test ``` -## Q. How to set the Permissions to a file in Java? +## # 10. JAVA STREAMS -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:** +## Q. What is Stream? -```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; +An interface `java.util.Stream` is a sequence of elements on which various operations can be performed. -public class FilePermissions { +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. - public static void main(String[] args) throws IOException { - File file = new File("/Users/file.txt"); +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()`). - // 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); +Streams are created based on sources of some, for example, classes from `java.util.Collection`. - // using PosixFilePermission to set file permissions 777 - Set perms = new HashSet(); +Associative arrays (maps), for example `HashMap`, are not supported. - // add owners permission - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.add(PosixFilePermission.OWNER_EXECUTE); +Operations on streams can be performed both sequentially and in parallel. - // add group permissions - perms.add(PosixFilePermission.GROUP_READ); - perms.add(PosixFilePermission.GROUP_WRITE); - perms.add(PosixFilePermission.GROUP_EXECUTE); +Streams cannot be reused. As soon as some final operation has been called, the flow is closed. - // add others permissions - perms.add(PosixFilePermission.OTHERS_READ); - perms.add(PosixFilePermission.OTHERS_WRITE); - perms.add(PosixFilePermission.OTHERS_EXECUTE); +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: - Files.setPosixFilePermissions(Paths.get("/Users/run.sh"), perms); - } -} -``` +* use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`; +* support additional end operations `sum()`, `average()`, `mapToObj()`. -## 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. +## Q. What are the ways to create a stream? -**1. Byte Streams:** +* Using collection: -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. +```java +Stream < String > fromCollection = Arrays.asList ( " x " , " y " , " z " ).stream (); +``` -**Example:** +* Using set of values: ```java -/** - * Byte Streams - */ -import java.io.*; +Stream < String > fromValues = Stream.of( " x " , " y " , " z " ); +``` -public class CopyFile { +* Using Array - public static void main(String args[]) throws IOException { - FileInputStream in = null; - FileOutputStream out = null; +```java +Stream < String > fromArray = Arrays.stream( new String [] { " x " , " y " , " z " }); +``` - try { - in = new FileInputStream("input.txt"); - out = new FileOutputStream("output.txt"); +* Using file (each line in the file will be a separate element in the stream): - int c; - while ((c = in.read()) != -1) { - out.write(c); - } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - } - } -} +```java +Stream < String > fromFile = Files.lines( Paths.get(" input.txt ")); ``` -**2. Character Streams:** +* From the line: -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. +```java +IntStream fromString = " 0123456789 " . chars (); +``` -**Example:** +* With the help of `Stream.builder()`: ```java -/** - * Character Streams - */ -import java.io.*; +Stream < String > fromBuilder = Stream.builder().add (" z ").add(" y ").add(" z ").build (); +``` -public class CopyFile { +* Using `Stream.iterate()(infinite)`: - public static void main(String args[]) throws IOException { - FileReader in = null; - FileWriter out = null; +```java +Stream < Integer > fromIterate = Stream.iterate ( 1 , n - > n + 1 ); +``` - try { - in = new FileReader("input.txt"); - out = new FileWriter("output.txt"); +* Using `Stream.generate()(infinite)`: - int c; - while ((c = in.read()) != -1) { - out.write(c); - } - } finally { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - } - } -} +```java +Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); ``` -## Q. How serialization works in java? +## Q. What is the difference between `Collection` and `Stream`? -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. +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. -**Example:** + -```java -/** -* Serialization and Deserialization -*/ -import java.io.*; +## Q. What is the method `collect()`for streams for? -class Employee implements Serializable { - private static final long serialversionUID = 129348938L; - transient int a; - static int b; - String name; - int age; +A method `collect()`is the final operation that is used to represent the result as a collection or some other data structure. - // Default constructor - public Employee(String name, int age, int a, int b) { - this.name = name; - this.age = age; - this.a = a; - this.b = b; - } -} +`collect()`accepts an input that contains four stages: -public class SerialExample { +* **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. - 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); - } +In Java 8, the class `Collectors` implements several common collectors: - public static void main(String[] args) { - Employee object = new Employee("ab", 20, 2, 1000); - String filename = "file.txt"; +* `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. - // Serialization - try { - // Saving of object in a file - FileOutputStream file = new FileOutputStream(filename); - ObjectOutputStream out = new ObjectOutputStream(file); +There is also the possibility of creating your own collector through `Collector.of()`: - // Method for serialization of object - out.writeObject(object); +```java +Collector < String , a List < String > , a List < String > > toList = Collector.of ( + ArrayList :: new , + List :: add, + (l1, l2) -> {l1 . addAll (l2); return l1; } +); +``` - 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"); - } +## Q. Why do streams use `forEach()`and `forEachOrdered()` methods? - object = null; +* `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. - // 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(); +## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream? - 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"); - } - } -} +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] ``` -## # 13. JAVA EXCEPTIONS - -
+## Q. What is the purpose of `filter()` method in streams? -## Q. What are the types of Exceptions? +The method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition. -Exception is an error event that can happen during the execution of a program and disrupts its normal flow. + -**1. Checked Exception**: +## Q. What is the use of `limit()` method in streams? -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. +The method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements. -**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. +## Q. What is the use of `sorted()` method in streams? -**3. Error**: +The method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator. -Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. +The order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation. -## 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 -

+## Q. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`? -**Example:** +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 -/** - * Exception classes - */ -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +Stream + .of ( " Hello " , " world! " ) + .flatMap ((p) -> Arrays.stream (p . split ( " , " ))) + .toArray ( String [] :: new ); // ["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"] +``` -public class CustomExceptionExample { +`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. - 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(); - } - } +## Q. What are the final methods of working with streams you know? - 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"); - } - } - } -} -``` +* `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 is difference between Error and Exception? +## Q. What intermediate methods of working with streams do you know? -|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.| +* `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 about Exception Propagation? +## # 11. JAVA REGULAR EXPRESSIONS -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. +
+ +## 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 /** - * Exception Propagation + * Regular Expression */ -class TestExceptionPropagation { - - void method1() { - int data = 10 / 0; // generates an exception - System.out.println(data); - } +import java.util.regex.*; - void method2() { - method1(); // doesn't catch the exception - } +public class Index { + public static void main(String args[]) { - void method3() { // method3 catches the exception - try { - method2(); - } catch (Exception e) { - System.out.println("Exception is caught"); - } - } + // Pattern, String + boolean b = Pattern.matches(".s", "as"); - public static void main(String args[]) { - TestExceptionPropagation obj = new TestExceptionPropagation(); - obj.method3(); + System.out.println("Match: " + b); } } ``` @@ -2388,44 +2201,55 @@ class TestExceptionPropagation { ↥ back to top -## Q. What are different scenarios causing "Exception in thread main"? +## # 12. JAVA FILE HANDLING -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. +## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? -* **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. +`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. -* **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:** +**Example:** ```java /** - * Throw in Java + * BufferedInputStream */ -public class ThrowExample { - void checkAge(int age) { - if (age < 18) - throw new ArithmeticException("Not Eligible for voting"); - else - System.out.println("Eligible for voting"); - } +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; - public static void main(String args[]) { - ThrowExample obj = new ThrowExample(); - obj.checkAge(13); - System.out.println("End Of Program"); +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(); + } + } } } ``` @@ -2433,30 +2257,45 @@ public class ThrowExample { 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) +This is an example of reading data from file ``` **Example:** ```java /** - * Throws in Java + * BufferedOutputStream */ -public class ThrowsExample { - int division(int a, int b) throws ArithmeticException { - int t = a / b; - return t; - } +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; - public static void main(String args[]) { - ThrowsExample obj = new ThrowsExample(); +public class BufferedOutputStreamExample { + + public static void main(String[] args) { + File file = new File("outfile.txt"); + FileOutputStream fileOutputStream = null; + BufferedOutputStream bufferedOutputStream = null; try { - System.out.println(obj.division(15, 0)); - } catch (ArithmeticException e) { - System.out.println("You shouldn't divide number by zero"); + 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(); + } } } } @@ -2465,39 +2304,62 @@ public class ThrowsExample { Output ```java -You shouldn\'t divide number by zero +This is an example of writing data to a file ``` -## Q. While overriding a method can you throw another exception or broader exception? +## Q. How to set the Permissions to a file in Java? -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. +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 -class A { - public void message() throws IOException {..} -} +/** + * 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; -class B extends A { - @Override - public void message() throws SocketException {..} // allowed +public class FilePermissions { - @Override - public void message() throws SQLException {..} // NOT allowed + public static void main(String[] args) throws IOException { + File file = new File("/Users/file.txt"); - public static void main(String args[]) { - A a = new B(); - try { - a.message(); - } catch (IOException ex) { - // forced to catch this by the compiler - } - } + // 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); + } } ``` @@ -2505,216 +2367,178 @@ class B extends A { ↥ back to top -## Q. What is checked, unchecked exception and errors? +## Q. Give the hierarchy of InputStream and OutputStream classes? -**1. Checked Exception**: +A stream can be defined as a sequence of data. There are two kinds of Streams − -* 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). +* **InPutStream** − The InputStream is used to read data from a source. +* **OutPutStream** − The OutputStream is used for writing data to a destination. -**Example:** **IOException, SQLException** etc. +**1. Byte Streams:** -```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(); - } -} -``` +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: +**Example:** ```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) -``` +/** + * Byte Streams + */ +import java.io.*; -After adding IOException +public class CopyFile { -```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(); - } -} -``` + public static void main(String args[]) throws IOException { + FileInputStream in = null; + FileOutputStream out = null; -output: + try { + in = new FileInputStream("input.txt"); + out = new FileOutputStream("output.txt"); -```java -Output: First three lines of file “C:\assets\file.txt” + int c; + while ((c = in.read()) != -1) { + out.write(c); + } + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } +} ``` -**2. Unchecked Exception**: +**2. Character Streams:** -* 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. +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:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. +**Example:** ```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. - - +/** + * Character Streams + */ +import java.io.*; -## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? +public class CopyFile { -`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. + public static void main(String args[]) throws IOException { + FileReader in = null; + FileWriter out = null; -`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. + try { + in = new FileReader("input.txt"); + out = new FileWriter("output.txt"); -`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. + int c; + while ((c = in.read()) != -1) { + out.write(c); + } + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + } +} +``` -## # 14. JAVA INHERITANCE - -
- -## Q. What is the difference between aggregation and composition? - -**1. Aggregation:** +## Q. How serialization works in java? -We call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object. +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:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes +**Example:** ```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. +* Serialization and Deserialization +*/ +import java.io.*; -**Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. +class Employee implements Serializable { + private static final long serialversionUID = 129348938L; + transient int a; + static int b; + String name; + int age; -```java -/** - * Composition - */ -public class Car { - //final will make sure engine is initialized - private final Engine engine; - - public Car(){ - engine = new Engine(); + // Default constructor + public Employee(String name, int age, int a, int b) { + this.name = name; + this.age = age; + this.a = a; + this.b = b; } } -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.
+public class SerialExample { -*Note: "final" keyword is used in Composition to make sure child variable is initialized.* + 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"; -## Q. The difference between Inheritance and Composition? + // Serialization + try { + // Saving of object in a file + FileOutputStream file = new FileOutputStream(filename); + ObjectOutputStream out = new ObjectOutputStream(file); -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"**. + // Method for serialization of object + out.writeObject(object); -**Example:** Inheritance + out.close(); + file.close(); -```java -/** - * Inheritance - */ -class Fruit { - // ... -} + 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"); + } -class Apple extends Fruit { - // ... -} -``` + object = null; -**Example:** Composition + // Deserialization + try { + // Reading the object from a file + FileInputStream file = new FileInputStream(filename); + ObjectInputStream in = new ObjectInputStream(file); -```java -/** - * Composition - */ -class Fruit { - // ... -} + // Method for deserialization of object + object = (Employee) in.readObject(); -class Apple { - private Fruit fruit = new Fruit(); - // ... + 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"); + } + } } ``` @@ -2722,248 +2546,191 @@ class Apple { ↥ back to top -## Q. Can you declare the main method as final? +## # 13. JAVA EXCEPTIONS -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. +## Q. What are the types of Exceptions? -**Example:** +Exception is an error event that can happen during the execution of a program and disrupts its normal flow. -```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"); - } -} -``` +**1. Checked Exception**: -Output +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. -```java -Cannot override the final method from Test. -``` +**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. What is covariant return type? +## Q. Explain hierarchy of Java Exception classes? -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. +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 /** - * Covariant Return Type + * Exception classes */ -class SuperClass { - SuperClass get() { - System.out.println("SuperClass"); - return this; - } -} +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; -public class Tester extends SuperClass { - Tester get() { - System.out.println("SubClass"); - return this; - } +public class CustomExceptionExample { - public static void main(String[] args) { - SuperClass tester = new Tester(); - tester.get(); - } -} -``` + public static void main(String[] args) throws MyException { + try { + processFile("file.txt"); + } catch (MyException e) { + processErrorCodes(e); + } + } -Output: + 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(); + } + } -```java -Subclass + 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. 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. +## Q. What is difference between Error and Exception? -`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**. +|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.| -```java -public class MediaPlayer { + - // Play audio implementation - public void playAudio() { - System.out.println("Playing audio..."); - } +## Q. Explain about Exception Propagation? - // Play video implementation - public void playVideo() { - System.out.println("Playing video..."); - } -} +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. -public class VlcMediaPlayer extends MediaPlayer {} +**Example:** -public class WinampMediaPlayer extends MediaPlayer { +```java +/** + * Exception Propagation + */ +class TestExceptionPropagation { - // Play video is not supported in Winamp player - public void playVideo() { - throw new VideoUnsupportedException(); + void method1() { + int data = 10 / 0; // generates an exception + System.out.println(data); } -} -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); + void method2() { + method1(); // doesn't catch the exception } - /** - * This method is playing video in all players - * - * @param allPlayers - */ - public static void playVideoInAllMediaPlayers(List < MediaPlayer > allPlayers) { - - for (MediaPlayer player: allPlayers) { - player.playVideo(); + void method3() { // method3 catches the exception + try { + method2(); + } catch (Exception e) { + System.out.println("Exception is caught"); } } -} -``` - -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 static void main(String args[]) { + TestExceptionPropagation obj = new TestExceptionPropagation(); + obj.method3(); } } - -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*. - -## # 15. JAVA METHOD OVERRIDING +## Q. What are different scenarios causing "Exception in thread main"? -
+Some of the common main thread exception are as follows: -## # 16. JAVA POLYMORPHISM +* **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. -## Q. What is the difference between compile-time polymorphism and runtime polymorphism? +* **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. -There are two types of polymorphism in java: +* **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. -1. Static Polymorphism also known as Compile time polymorphism -2. Runtime polymorphism also known as Dynamic Polymorphism + -**1. Static Polymorphism:** +## Q. What are the differences between throw and throws? -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. +**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 /** - * Static Polymorphism + * Throw in 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 ThrowExample { + void checkAge(int age) { + if (age < 18) + throw new ArithmeticException("Not Eligible for voting"); + else + System.out.println("Eligible for voting"); } -} -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)); + ThrowExample obj = new ThrowExample(); + obj.checkAge(13); + System.out.println("End Of Program"); } } ``` @@ -2971,326 +2738,288 @@ public class Demo { Output ```java -30 -60 +Exception in thread "main" java.lang.ArithmeticException: +Not Eligible for voting +at Example1.checkAge(Example1.java:4) +at Example1.main(Example1.java:10) ``` -**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:** +**Example:** ```java /** - * Runtime Polymorphism + * Throws in 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 class ThrowsExample { + int division(int a, int b) throws ArithmeticException { + int t = a / b; + return t; + } public static void main(String args[]) { - ABC obj = new XYZ(); - obj.myMethod(); + 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: +Output ```java -Overriding Method +You shouldn\'t divide number by zero ``` -## 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: +## Q. While overriding a method can you throw another exception or broader exception? -* **Static Polymorphism** also known as compile time polymorphism -* **Dynamic Polymorphism** also known as runtime polymorphism +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:** Static Polymorphism +**Example:** ```java -class SimpleCalculator { - - int add(int a, int b) { - return a + b; - } - int add(int a, int b, int c) { - return a + b + c; - } +class A { + public void message() throws IOException {..} } -public class MainClass -{ + +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[]) { - SimpleCalculator obj = new SimpleCalculator(); - System.out.println(obj.add(10, 20)); - System.out.println(obj.add(10, 20, 30)); + A a = new B(); + try { + a.message(); + } catch (IOException ex) { + // forced to catch this by the compiler + } } } ``` -Output + -```java -30 -60 -``` +## Q. What is checked, unchecked exception and errors? -**Example:** Runtime polymorphism +**1. Checked Exception**: -```java -class ABC { - public void myMethod() { - System.out.println("Overridden Method"); - } -} -public class XYZ extends ABC { +* 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). - public void myMethod() { - System.out.println("Overriding Method"); - } - public static void main(String args[]) { - ABC obj = new XYZ(); - obj.myMethod(); - } -} +**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 +output: ```java -Overriding Method +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) ``` - - -## Q. What is runtime polymorphism in java? +After adding IOException -**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. +```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(); + } +} +``` -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. +output: ```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;} -} +Output: First three lines of file “C:\assets\file.txt” +``` -Bank b; -b=new SBI(); -System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); +**2. Unchecked Exception**: -b=new ICICI(); -System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); +* 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. -b=new AXIS(); -System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); +**Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. -System.out.println("Bank Rate of Interest: "+b.roi); +```java +class Main { + public static void main(String args[]) { + int x = 0; + int y = 10; + int z = y/x; + } +} +``` -/**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 +Output: -//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. -**/ +```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. + -## # 17. JAVA ABSTRACTION - -
+## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? -## Q. What is the difference between abstract class and interface? +`ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. -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. +`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. -|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.| +`NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. -## 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. +## # 14. JAVA INHERITANCE -* **Synchronization**: Java synchronization works with objects in Multithreading. +
-* **java.util package**: The java.util package provides the utility classes to deal with objects. +## Q. What is the difference between aggregation and composition? -* **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. +**1. Aggregation:** -| 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| +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:** Primitive to Wrapper +**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 /** - * Java program to convert primitive into objects - * Autoboxing example of int to Integer + * Aggregation */ -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 +public class Organization { + private List employees; +} - System.out.println(a + " " + i + " " + j); - } +public class Person { + private String name; } ``` -Output - -```java -20 20 20 -``` +**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. -## Q. What is the difference between abstraction and encapsulation? +**Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. -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. +```java +/** + * Composition + */ +public class Car { + //final will make sure engine is initialized + private final Engine engine; + + public Car(){ + engine = new Engine(); + } +} -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. +class Engine { + private String type; +} +``` -**Difference:** +

+ Aggregation +

- - - - - - - - - - - + + + + + + + + + +
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.
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.* + -## # 18. JAVA INTERFACES - -
+## Q. The difference between Inheritance and Composition? -## Q. Can we use private or protected member variables in an interface? +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"**. -The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically +**Example:** Inheritance ```java -public interface Test { - public string name1; - private String email; - protected pass; +/** + * Inheritance + */ +class Fruit { + // ... } -``` - -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; +class Apple extends Fruit { + // ... } ``` -* 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 +**Example:** Composition ```java /** - * Interface + * Composition */ -interface MyInterface { - void display(); +class Fruit { + // ... } -public class TestInterface implements MyInterface { - - void display() { - System.out.println("Hello World"); - } - - public static void main(String[] args) { - MyInterface myInterface = new TestInterface(); - MyInterface.display(); - } +class Apple { + private Fruit fruit = new Fruit(); + // ... } ``` @@ -3298,335 +3027,248 @@ public class TestInterface implements MyInterface { ↥ back to top -## 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; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -class Super implements Serializable { - private static final long serialVersionUID = 1L; -} - -class Sub extends Super { +## Q. Can you declare the main method as final? - private static final long serialVersionUID = 1L; - private Integer id; +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. - public Sub(Integer id) { - this.id = id; - } +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. - @Override - public String toString() { - return "Employee [id=" + id + "]"; - } +**Example:** - /* - * define how Serialization process will write objects. - */ - private void writeObject(ObjectOutputStream os) throws NotSerializableException { - throw new NotSerializableException("This class cannot be Serialized"); - } +```java +public class Test { + public final static void main(String[] args) throws Exception { + System.out.println("This is Test Class"); + } } - -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(); - } - } + +class Child extends Test { + public static void main(String[] args) throws Exception { + System.out.println("This is Child Class"); + } } ``` Output ```java -Serialization process has started, serializing objects... -java.io.NotSerializableException: This class cannot be Serialized - at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) - at java.lang.reflect.Method.invoke(Unknown Source) - at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) - at java.io.ObjectOutputStream.writeSerialData(Unknown Source) - at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) - at java.io.ObjectOutputStream.writeObject0(Unknown Source) - at java.io.ObjectOutputStream.writeObject(Unknown Source) - at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) +Cannot override the final method from Test. ``` -## Q. What is the difference between Serializable and 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. 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 -public interface Interface_Name { +## 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 /** - * Maker Interface + * Covariant Return Type */ -interface Marker { +class SuperClass { + SuperClass get() { + System.out.println("SuperClass"); + return this; + } } -class MakerExample implements Marker { - // do some task -} +public class Tester extends SuperClass { + Tester get() { + System.out.println("SubClass"); + return this; + } -class Main { public static void main(String[] args) { - MakerExample obj = new MakerExample(); - if (obj instanceOf Marker) { - // do some task - } + SuperClass tester = new Tester(); + tester.get(); } } ``` - - -## Q. Can you declare an interface method static? +Output: -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. +```java +Subclass +``` -## Q. What is a Functional Interface? - -A **functional interface** is an interface that defines only one abstract method. +## Q. Can you explain Liskov Substitution principle? -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. +Liskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.** -An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. +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**. -## # 19. JAVA ENCAPSULATION +```java +public class MediaPlayer { -
+ // Play audio implementation + public void playAudio() { + System.out.println("Playing audio..."); + } -## Q. How Encapsulation concept implemented in JAVA? + // Play video implementation + public void playVideo() { + System.out.println("Playing video..."); + } +} -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`. +public class VlcMediaPlayer extends MediaPlayer {} -To achieve encapsulation in Java − +public class WinampMediaPlayer extends MediaPlayer { -* Declare the variables of a class as private. -* Provide public setter and getter methods to modify and view the variables values. + // Play video is not supported in Winamp player + public void playVideo() { + throw new VideoUnsupportedException(); + } +} -**Example:** +public class VideoUnsupportedException extends RuntimeException { -```java -public class EncapClass { - private String name; + private static final long serialVersionUID = 1 L; - public String getName() { - return name; - } - public void setName(String newName) { - name = newName; - } } -public class MainClass { - - public static void main(String args[]) { - EncapClass obj = new EncapClass(); - obj.setName("Pradeep Kumar"); - System.out.print("Name : " + obj.getName()); - } -} -``` +public class ClientTestProgram { - + public static void main(String[] args) { -## # 20. MISCELLANEOUS + // 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); -## Q. How will you invoke any external process in Java? + // Well - all works as of now...... :-) + System.out.println("---------------------------"); -In java, external process can be invoked using **exec()** method of **Runtime Class**. + // Now adding new Winamp player + allPlayers.add(new WinampMediaPlayer()); -**Example:** + // 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); + } -```java -/** - * exec() - */ -import java.io.IOException; + /** + * This method is playing video in all players + * + * @param allPlayers + */ + public static void playVideoInAllMediaPlayers(List < MediaPlayer > allPlayers) { -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(); - } + for (MediaPlayer player: allPlayers) { + player.playVideo(); + } } } ``` - - -## Q. What is the static import? +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` -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. +lets reimplement the refactored code ```java -/** - * Static Import - */ -import static java.lang.System.*; +public class MediaPlayer { -class StaticImportExample { + // Play audio implementation + public void playAudio() { + System.out.println("Playing audio..."); + } +} - public static void main(String args[]) { - out.println("Hello");// Now no need of System.out - out.println("Java"); +//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 {} -## Q. What is the difference between factory and abstract factory pattern? +public class VlcMediaPlayer extends VideoMediaPlayer {} -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. +//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 {} -**Example:** credit card validator factory which returns a different validator for each card type. + /** + * This method is playing video in all players + * + * @param allPlayers + */ + public static void playVideoInAllMediaPlayers(List allPlayers) { -```java -/** - * 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"); + for (VideoMediaPlayer player: allPlayers) { + player.playVideo(); + } } -} ``` -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. +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*. -## Q. What are the methods used to implement for key Object in HashMap? +## # 15. JAVA METHOD OVERRIDING -**1. equals()** and **2. hashcode()** +
-Class inherits methods from the following classes in terms of HashMap +## # 16. JAVA POLYMORPHISM -* java.util.AbstractMap -* java.util.Object -* java.util.Map +
- +## Q. What is the difference between compile-time polymorphism and runtime polymorphism? -## Q. What is a Memory Leak? +There are two types of polymorphism in java: -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. +1. Static Polymorphism also known as Compile time polymorphism +2. Runtime polymorphism also known as Dynamic Polymorphism -Some tools that do memory management to identifies useless objects or memeory leaks like: +**1. Static Polymorphism:** -* HP OpenView -* HP JMETER -* JProbe -* IBM Tivoli +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 /** - * Memory Leaks + * Static Polymorphism */ -import java.util.Vector; +class SimpleCalculator { + int add(int a, int b) { + return a + b; + } -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"); + 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)); } } ``` @@ -3634,343 +3276,491 @@ public class MemoryLeaksExample { Output ```java -Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed +30 +60 ``` -**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 +**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. -## Q. The difference between Serial and Parallel Garbage Collector? +**Example:** -**1. Serial Garbage Collector:** +```java +/** + * Runtime Polymorphism + */ +class ABC { -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. + public void myMethod() { + System.out.println("Overridden Method"); + } +} -Turn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector. +public class XYZ extends ABC { -**2. Parallel Garbage Collector:** + public void myMethod() { + System.out.println("Overriding Method"); + } -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 main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } +} +``` + +Output: + +```java +Overriding Method +``` -## Q. What is difference between WeakReference and SoftReference in Java? +## Q. What do you mean Run time Polymorphism? -**1. Weak References:** +`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: -Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. +* **Static Polymorphism** also known as compile time polymorphism +* **Dynamic Polymorphism** also known as runtime polymorphism + +**Example:** Static Polymorphism ```java -/** - * Weak Reference - */ -import java.lang.ref.WeakReference; +class SimpleCalculator { -class MainClass { - public void message() { - System.out.println("Weak References Example"); + int add(int a, int b) { + return a + b; } -} - -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(); + 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)); + } +} ``` -**2. Soft References:** +Output -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 +30 +60 +``` + +**Example:** Runtime polymorphism ```java -/** - * Soft Reference - */ -import java.lang.ref.SoftReference; +class ABC { + public void myMethod() { + System.out.println("Overridden Method"); + } +} +public class XYZ extends ABC { -class MainClass { - public void message() { - System.out.println("Soft References Example"); - } + public void myMethod() { + System.out.println("Overriding Method"); + } + public static void main(String args[]) { + ABC obj = new XYZ(); + obj.myMethod(); + } } +``` -public class Example { - public static void main(String[] args) { - // Strong Reference - MainClass g = new MainClass(); - g.message(); +Output - // 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(); - } -} +```java +Overriding Method ``` -## Q. How Garbage collector algorithm works? +## Q. What is runtime polymorphism in java? -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. +**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. -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 +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;} +} -## Q. Java Program to Implement Singly Linked List? +Bank b; +b=new SBI(); +System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); -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. +b=new ICICI(); +System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); -**Example:** +b=new AXIS(); +System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); -```java -public class SinglyLinkedList { - // Represent a node of the singly linked list - class Node{ - int data; - Node next; - - public Node(int data) { - this.data = data; - this.next = null; - } - } - - // Represent the head and tail of the singly linked list - public Node head = null; - public Node tail = null; - - // addNode() will add a new node to the list - public void addNode(int data) { - // Create a new node - Node newNode = new Node(data); - - // Checks if the list is empty - if(head == null) { - // If list is empty, both head and tail will point to new node - head = newNode; - tail = newNode; - } - else { - // newNode will be added after tail such that tail's next will point to newNode - tail.next = newNode; - // newNode will become new tail of the list - tail = newNode; - } - } - - // display() will display all the nodes present in the list - public void display() { - // Node current will point to head - Node current = head; - - if(head == null) { - System.out.println("List is empty"); - return; - } - System.out.println("Nodes of singly linked list: "); - while(current != null) { - // Prints each node by incrementing pointer - System.out.print(current.data + " "); - current = current.next; - } - System.out.println(); - } - - public static void main(String[] args) { - - SinglyLinkedList sList = new SinglyLinkedList(); - - // Add nodes to the list - sList.addNode(10); - sList.addNode(20); - sList.addNode(30); - sList.addNode(40); - - // Displays the nodes present in the list - sList.display(); - } -} -``` +System.out.println("Bank Rate of Interest: "+b.roi); -**Output:** +/**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 -```java -Nodes of singly linked list: -10 20 30 40 +//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. +**/ ``` -## Q. What do we mean by weak reference? - -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. +## # 17. JAVA ABSTRACTION -```java -/** -* Weak reference -*/ -import java.lang.ref.WeakReference; +
-class WeakReferenceExample { - - public void message() { - System.out.println("Weak Reference Example!"); - } -} +## Q. What is the difference between abstract class and interface? -public class MainClass { +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. - public static void main(String[] args) { - // Strong Reference - WeakReferenceExample obj = new WeakReferenceExample(); - obj.message(); - - // Creating Weak Reference to WeakReferenceExample-type object to which 'obj' - // is also pointing. - WeakReference weakref = new WeakReference(obj); +|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.| - obj = null; // is available for garbage collection. - obj = weakref.get(); - obj.message(); - } -} + + +## 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 -Weak Reference Example! -Weak Reference Example! +20 20 20 ``` -## Q. What are the different types of JDBC Driver? +## Q. What is the difference between abstraction and encapsulation? -JDBC Driver is a software component that enables java application to interact with the database. -There are 4 types of JDBC drivers: +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. -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. -1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. -1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. -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. +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.
-## Q. Do you know Generics? How did you used in your coding? +## # 18. JAVA INTERFACES -`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:** +## Q. Can we use private or protected member variables in an interface? -* **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. +The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically -**Example:** +```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 -/** -* 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(); - } +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 +/** + * 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. + +```java +/** + * Serialization + */ +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.io.Serializable; + +class Super implements Serializable { + 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; + } + + @Override + public String toString() { + return "Employee [id=" + id + "]"; + } + + /* + * define how Serialization process will write objects. + */ + 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(); + } + } +} +``` + +Output + +```java +Serialization process has started, serializing objects... +java.io.NotSerializableException: This class cannot be Serialized + at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) + at java.lang.reflect.Method.invoke(Unknown Source) + at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) + at java.io.ObjectOutputStream.writeSerialData(Unknown Source) + at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) + at java.io.ObjectOutputStream.writeObject0(Unknown Source) + at java.io.ObjectOutputStream.writeObject(Unknown Source) + at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) +``` + + + +## Q. What is the difference between Serializable and 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. 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 +public interface Interface_Name { + } ``` -Output: +**Example:** ```java -Generic Class Example ! -100 +/** + * Maker Interface + */ +interface Marker { +} + +class MakerExample implements Marker { + // do some task +} + +class Main { + public static void main(String[] args) { + MakerExample obj = new MakerExample(); + if (obj instanceOf Marker) { + // do some task + } + } +} ``` +## Q. Can you declare an interface method static? -## Q. What is StringJoiner? +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. -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 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 are `default`interface methods? +## Q. What are `default` interface methods? Java 8 allows you to add non-abstract method implementations to an interface using the keyword default: @@ -4051,290 +3841,607 @@ class License { ↥ back to top -## Q. What is Optional +## Q. What are the functional interfaces `Function`, `DoubleFunction`, `IntFunction` and `LongFunction`? -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`: +`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`. -```java -Optional < String > optional = Optional . of ( " hello " ); +Default methods can be used to build call chains ( `compose`, `andThen`). -optional.isPresent(); // true -optional.ifPresent(s -> System.out.println(s . length ())); // 5 -optional.get(); // "hello" -optional.orElse( " ops ... " ); // "hello" +```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 is Stream? - -An interface `java.util.Stream` is a sequence of elements on which various operations can be performed. +## Q. What are the functional interfaces `UnaryOperator`, `DoubleUnaryOperator`, `IntUnaryOperator`and `LongUnaryOperator`? -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. +`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`: -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()`). +```java +UnaryOperator < Integer > operator = x - > x * x; +System.out.println(operator.apply ( 5 )); // 25 +``` -Streams are created based on sources of some, for example, classes from `java.util.Collection`. +* `DoubleUnaryOperator`- unary operator receiving input `Double`; +* `IntUnaryOperator`- unary operator receiving input `Integer`; +* `LongUnaryOperator`- unary operator receiving input `Long`. -Associative arrays (maps), for example `HashMap`, are not supported. + -Operations on streams can be performed both sequentially and in parallel. +## Q. What are the functional interfaces `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`? -Streams cannot be reused. As soon as some final operation has been called, the flow is closed. +`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`. -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: +```java +BinaryOperator < Integer > operator = (a, b) -> a + b; +System.out.println(operator.apply ( 1 , 2 )); // 3 +``` -* use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`; -* support additional end operations `sum()`, `average()`, `mapToObj()`. +* `DoubleBinaryOperator`- binary operator receiving input Double; +* `IntBinaryOperator`- binary operator receiving input Integer; +* `LongBinaryOperator`- binary operator receiving input Long. -## Q. What are the ways to create a stream? +## Q. What are the functional interfaces `Predicate`, `DoublePredicate`, `IntPredicateand` `LongPredicate`? -* Using collection: +`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 -Stream < String > fromCollection = Arrays.asList ( " x " , " y " , " z " ).stream (); +Predicate < String > predicate = (s) -> s.length () > 0 ; +predicate.test("foo"); // true +predicate.negate().test("foo"); // false ``` -* Using set of values: +* `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 -Stream < String > fromValues = Stream.of( " x " , " y " , " z " ); +Consumer hello = (name) -> System.out.println( " Hello, " + name); +hello.accept( " world " ); ``` -* Using Array +* `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 -Stream < String > fromArray = Arrays.stream( new String [] { " x " , " y " , " z " }); +Supplier < LocalDateTime > now = LocalDateTime::now; +now.get(); ``` -* Using file (each line in the file will be a separate element in the stream): +* `DoubleSupplier`- the supplier is returning `Double`; +* `IntSupplier`- the supplier is returning `Integer`; +* `LongSupplier`- the supplier is returning `Long`. + + + +## # 19. 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 -Stream < String > fromFile = Files.lines( Paths.get(" input.txt ")); +public class EncapClass { + private String name; + + public String getName() { + return name; + } + public void setName(String newName) { + name = newName; + } +} + +public class MainClass { + + public static void main(String args[]) { + EncapClass obj = new EncapClass(); + obj.setName("Pradeep Kumar"); + System.out.print("Name : " + obj.getName()); + } +} ``` -* From the line: + + +## # 20. MISCELLANEOUS + +
+ +## Q. How will you invoke any external process in Java? + +In java, external process can be invoked using **exec()** method of **Runtime Class**. + +**Example:** ```java -IntStream fromString = " 0123456789 " . chars (); +/** + * exec() + */ +import java.io.IOException; + +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(); + } + } +} ``` -* With the help of `Stream.builder()`: + + +## 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 -Stream < String > fromBuilder = Stream.builder().add (" z ").add(" y ").add(" z ").build (); +/** + * 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"); + } +} ``` -* Using `Stream.iterate()(infinite)`: + + +## 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. + +**Example:** credit card validator factory which returns a different validator for each card type. ```java -Stream < Integer > fromIterate = Stream.iterate ( 1 , n - > n + 1 ); +/** + * 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"); + } +} ``` -* Using `Stream.generate()(infinite)`: +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 -Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); -``` +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. What is the difference between `Collection` and `Stream`? +## Q. What are the methods used to implement for key Object in HashMap? -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. +**1. equals()** and **2. hashcode()** + +Class inherits methods from the following classes in terms of HashMap + +* java.util.AbstractMap +* java.util.Object +* java.util.Map -## Q. What is the method `collect()`for streams for? +## Q. What is a Memory Leak? -A method `collect()`is the final operation that is used to represent the result as a collection or some other data structure. +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. -`collect()`accepts an input that contains four stages: +Some tools that do memory management to identifies useless objects or memeory leaks like: -* **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. +* HP OpenView +* HP JMETER +* JProbe +* IBM Tivoli -In Java 8, the class `Collectors` implements several common collectors: +**Example:** -* `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. +```java +/** + * Memory Leaks + */ +import java.util.Vector; -There is also the possibility of creating your own collector through `Collector.of()`: +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"); + } +} +``` + +Output ```java -Collector < String , a List < String > , a List < String > > toList = Collector.of ( - ArrayList :: new , - List :: add, - (l1, l2) -> {l1 . addAll (l2); return l1; } -); +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. Why do streams use `forEach()`and `forEachOrdered()` methods? +## Q. The difference between Serial and Parallel Garbage Collector? -* `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. +**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. -## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream? +## Q. What is difference between WeakReference and SoftReference in Java? -The method `map()`is an intermediate operation, which transforms each element of the stream in a specified way. +**1. Weak References:** + +Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. -`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] +/** + * Weak Reference + */ +import java.lang.ref.WeakReference; + +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(); + } +} ``` - +**2. Soft References:** -## Q. What is the purpose of `filter()` method in streams? +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. -The method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition. +```java +/** + * Soft Reference + */ +import java.lang.ref.SoftReference; - +class MainClass { + public void message() { + System.out.println("Soft References Example"); + } +} -## Q. What is the use of `limit()` method in streams? +public class Example { + public static void main(String[] args) { + // Strong Reference + MainClass g = new MainClass(); + g.message(); -The method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements. + // 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. What is the use of `sorted()` method in streams? +## Q. How Garbage collector algorithm works? -The method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator. +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. -The order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation. +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. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`? +## Q. Java Program to Implement Singly Linked List? -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. +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:** ```java -Stream - .of ( " Hello " , " world! " ) - .flatMap ((p) -> Arrays.stream (p . split ( " , " ))) - .toArray ( String [] :: new ); // ["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"] +public class SinglyLinkedList { + // Represent a node of the singly linked list + class Node{ + int data; + Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } + } + + // Represent the head and tail of the singly linked list + public Node head = null; + public Node tail = null; + + // addNode() will add a new node to the list + public void addNode(int data) { + // Create a new node + Node newNode = new Node(data); + + // Checks if the list is empty + if(head == null) { + // If list is empty, both head and tail will point to new node + head = newNode; + tail = newNode; + } + else { + // newNode will be added after tail such that tail's next will point to newNode + tail.next = newNode; + // newNode will become new tail of the list + tail = newNode; + } + } + + // display() will display all the nodes present in the list + public void display() { + // Node current will point to head + Node current = head; + + if(head == null) { + System.out.println("List is empty"); + return; + } + System.out.println("Nodes of singly linked list: "); + while(current != null) { + // Prints each node by incrementing pointer + System.out.print(current.data + " "); + current = current.next; + } + System.out.println(); + } + + public static void main(String[] args) { + + SinglyLinkedList sList = new SinglyLinkedList(); + + // Add nodes to the list + sList.addNode(10); + sList.addNode(20); + sList.addNode(30); + sList.addNode(40); + + // Displays the nodes present in the list + sList.display(); + } +} +``` + +**Output:** + +```java +Nodes of singly linked list: +10 20 30 40 ``` -`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. - -## Q. Tell us about parallel processing in Java 8? +## Q. What do we mean by weak reference? -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. +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. -You can also use the `parallelStream()`interface method to create a parallel stream from the collection `Collection`. +```java +/** +* Weak reference +*/ +import java.lang.ref.WeakReference; -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. +class WeakReferenceExample { + + public void message() { + System.out.println("Weak Reference Example!"); + } +} -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: +public class MainClass { -```java -collection - .stream () - .peek ( ... ) // operation is sequential - .parallel () - .map ( ... ) // the operation can be performed in parallel, - .sequential () - .reduce ( ... ) // operation is sequential again -``` + public static void main(String[] args) { + // Strong Reference + WeakReferenceExample obj = new WeakReferenceExample(); + obj.message(); + + // Creating Weak Reference to WeakReferenceExample-type object to which 'obj' + // is also pointing. + WeakReference weakref = new WeakReference(obj); -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()`. + obj = null; // is available for garbage collection. + obj = weakref.get(); + obj.message(); + } +} +``` -* 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()`: +Output ```java -collection.parallelStream () - .sorted () - .unordered () - .collect ( Collectors . toList ()); +Weak Reference Example! +Weak Reference Example! ``` -## Q. What are the final methods of working with streams you know? +## Q. What are the different types of JDBC Driver? -* `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. +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. +1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. +1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. +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. What intermediate methods of working with streams do you know? +## Q. Do you know Generics? How did you used in your coding? -* `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. +`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. -For numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream. +**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. + +**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(); + } +} +``` + +Output: + +```java +Generic Class Example ! +100 +```
↥ back to top @@ -4465,114 +4572,6 @@ new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // inp ↥ back to top
-## 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? From 6bd5755d77bafe8eae107b18a085c25ef69061e9 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 15:00:57 +0530 Subject: [PATCH 088/100] Update README.md --- README.md | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 5a669c3..9b5aafd 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ * [Java Abstraction](#-17-java-abstraction) * [Java Interfaces](#-18-java-interfaces) * [Java Encapsulation](#-19-java-encapsulation) -* [Miscellaneous](#-20-react-miscellaneous) +* [Miscellaneous](#-20-miscellaneous)
@@ -85,6 +85,22 @@ ↥ back to top +## 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. 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 ). @@ -893,14 +909,16 @@ The default methods of the implemented functional interface are not allowed to b 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. +**Example:** + ```java -private interface Measurable { - public int length ( String string ); +private interface Measurable { + public int length(String string); } public static void main ( String [] args) { - Measurable a = String::length; - System.out.println(a.length("abc")); + Measurable a = String::length; + System.out.println(a.length("abc")); } ``` @@ -4530,22 +4548,6 @@ To define a repeatable annotation, you must create a container annotation for th ↥ back to top -## 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 . From a67b971c66120d4bde5c3ab429fc790ec90b64cd Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Mon, 14 Nov 2022 15:30:44 +0530 Subject: [PATCH 089/100] Update README.md --- README.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9b5aafd..53ed4be 100644 --- a/README.md +++ b/README.md @@ -2181,6 +2181,14 @@ For numerical streams, an additional method is available `mapToObj()`that conver ↥ back to top +#### Q. Explain Difference between Collection API and Stream API? + +*ToDo* + + + ## # 11. JAVA REGULAR EXPRESSIONS
@@ -3967,6 +3975,16 @@ now.get(); ↥ back to top +#### 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* + + + ## # 19. JAVA ENCAPSULATION
@@ -4574,16 +4592,7 @@ new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // inp ↥ back to top -#### 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? #### 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? #### 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? From b909d21f1ddf3bc7cca3d1d9d77366d9df395828 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 20 Nov 2022 19:47:44 +0530 Subject: [PATCH 090/100] Update README.md --- README.md | 127 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 66 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 53ed4be..5e7d9f1 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ * [Java Abstraction](#-17-java-abstraction) * [Java Interfaces](#-18-java-interfaces) * [Java Encapsulation](#-19-java-encapsulation) -* [Miscellaneous](#-20-miscellaneous) +* [Java Generics](#-20-java-generics) +* [Miscellaneous](#-21-miscellaneous)
@@ -4026,7 +4027,70 @@ public class MainClass { ↥ back to top -## # 20. MISCELLANEOUS +## # 20. JAVA GENERICS + +
+ +## 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. + +**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(); + } +} +``` + +Output: + +```java +Generic Class Example ! +100 +``` + + + +## # 21. MISCELLANEOUS
@@ -4424,65 +4488,6 @@ There are 4 types of JDBC drivers: ↥ back to top -## 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. - -**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(); - } -} -``` - -Output: - -```java -Generic Class Example ! -100 -``` - - - ## 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: From 6296b2025ffd7abee78983e9a528604495eefa65 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 20 Nov 2022 20:13:19 +0530 Subject: [PATCH 091/100] Update README.md --- README.md | 78 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 44 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 5e7d9f1..0df8330 100644 --- a/README.md +++ b/README.md @@ -26,23 +26,25 @@ * [Java Architecture](#-2-java-architecture) * [Java Data Types](#-3-java-data-types) * [Java Methods](#-4-java-methods) -* [Java Classes](#-5-java-classes) -* [Java Constructors](#-6-java-constructors) -* [Java Array](#-7-java-array) -* [Java Strings](#-8-java-strings) -* [Java Reflection](#-9-java-reflection) -* [Java Streams](#-10-java-streams) -* [Java Regular Expressions](#-11-java-regular-expressions) -* [Java File Handling](#-12-java-file-handling) -* [Java Exceptions](#-13-java-exceptions) -* [Java Inheritance](#-14-java-inheritance) -* [Java Method Overriding](#-15-java-method-overriding) -* [Java Polymorphism](#-16-java-polymorphism) -* [Java Abstraction](#-17-java-abstraction) -* [Java Interfaces](#-18-java-interfaces) -* [Java Encapsulation](#-19-java-encapsulation) -* [Java Generics](#-20-java-generics) -* [Miscellaneous](#-21-miscellaneous) +* [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)
@@ -939,7 +941,15 @@ Method references are potentially more efficient than using lambda expressions. ↥ back to top -## # 5. JAVA CLASSES +## # 5. JAVA FUNCTIONAL PROGRAMMING + +
+ +## # 6. JAVA LAMBDA EXPRESSIONS + +
+ +## # 7. JAVA CLASSES
@@ -1366,7 +1376,7 @@ optional.orElse( " ops ... " ); // "hello" ↥ back to top -## # 6. JAVA CONSTRUCTORS +## # 8. JAVA CONSTRUCTORS
@@ -1600,7 +1610,7 @@ class Visitor{ ↥ back to top -## # 7. JAVA ARRAY +## # 9. JAVA ARRAY
@@ -1658,7 +1668,7 @@ class Visitor{ ↥ back to top -## # 8. JAVA STRINGS +## # 10. JAVA STRINGS
@@ -1845,7 +1855,7 @@ System.out.println(joiner); // prefix-Hello.the.brave.world-suffix ↥ back to top -## # 9. JAVA REFLECTION +## # 11. JAVA REFLECTION
@@ -1947,7 +1957,7 @@ Test ↥ back to top -## # 10. JAVA STREAMS +## # 12. JAVA STREAMS
@@ -2190,7 +2200,7 @@ For numerical streams, an additional method is available `mapToObj()`that conver ↥ back to top -## # 11. JAVA REGULAR EXPRESSIONS +## # 13. JAVA REGULAR EXPRESSIONS
@@ -2228,7 +2238,7 @@ public class Index { ↥ back to top -## # 12. JAVA FILE HANDLING +## # 14. JAVA FILE HANDLING
@@ -2573,7 +2583,7 @@ public class SerialExample { ↥ back to top -## # 13. JAVA EXCEPTIONS +## # 15. JAVA EXCEPTIONS
@@ -2943,7 +2953,7 @@ Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. ↥ back to top -## # 14. JAVA INHERITANCE +## # 16. JAVA INHERITANCE
@@ -3256,11 +3266,11 @@ that satisefies *Liskov's substitution principle*. ↥ back to top -## # 15. JAVA METHOD OVERRIDING +## # 17. JAVA METHOD OVERRIDING
-## # 16. JAVA POLYMORPHISM +## # 18. JAVA POLYMORPHISM
@@ -3464,7 +3474,7 @@ Bank Rate of Interest: 0.0 ↥ back to top -## # 17. JAVA ABSTRACTION +## # 19. JAVA ABSTRACTION
@@ -3567,7 +3577,7 @@ Abstraction is about hiding unwanted details while giving out most essential det ↥ back to top -## # 18. JAVA INTERFACES +## # 20. JAVA INTERFACES
@@ -3986,7 +3996,7 @@ now.get(); ↥ back to top -## # 19. JAVA ENCAPSULATION +## # 21. JAVA ENCAPSULATION
@@ -4027,7 +4037,7 @@ public class MainClass { ↥ back to top -## # 20. JAVA GENERICS +## # 22. JAVA GENERICS
@@ -4090,7 +4100,7 @@ Generic Class Example ! ↥ back to top -## # 21. MISCELLANEOUS +## # 23. MISCELLANEOUS
From ef0fd267c20a8fb00753c18fa2470e7f91581dc0 Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Wed, 30 Nov 2022 09:45:43 +0530 Subject: [PATCH 092/100] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0df8330..868f30f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Java Basics -*Click if you like the project. Pull Request are highly appreciated.* +> *Click ★ if you like the project. Your contributions are heartily ♡ welcome.*
From 17ba7f2ca1dcb4e4d4ea1826202fd2ae71219bab Mon Sep 17 00:00:00 2001 From: Dnyanesh Nimbalkar <78072155+Dnyaneshvn@users.noreply.github.com> Date: Sat, 3 Dec 2022 23:28:06 +0530 Subject: [PATCH 093/100] deleted extra syntax --- core-java/arrays/package-info.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) 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; From f39b25450e92ce67e7aebc17940a404a544334ba Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 19 Feb 2023 10:56:26 +0530 Subject: [PATCH 094/100] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 868f30f..3570c76 100644 --- a/README.md +++ b/README.md @@ -6,16 +6,16 @@ ## Related Topics -* *[Multithreading Basics](multithreading-questions.md)* -* *[Collections Basics](collections-questions.md)* -* *[JDBC Basics](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 Basics](jsp-questions.md)* -* *[Servlets Basics](servlets-questions.md)* +* *[Jakarta Server Pages (JSP)](jsp-questions.md)* +* *[Servlets](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* -* *[Spring Basics](https://github.com/learning-zone/spring-basics)* -* *[Hibernate Basics](https://github.com/learning-zone/hibernate-basics)* +* *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)* +* *[Hibernate](https://github.com/learning-zone/hibernate-basics)* * *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)*
From d1ea04d344ef3eea922fe058f4efd5c7f44e52ab Mon Sep 17 00:00:00 2001 From: Pradeep Kumar Date: Sun, 19 Feb 2023 10:59:49 +0530 Subject: [PATCH 095/100] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3570c76..380fef3 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,9 @@ * *[Jakarta Server Pages (JSP)](jsp-questions.md)* * *[Servlets](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* -* *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)* -* *[Hibernate](https://github.com/learning-zone/hibernate-basics)* * *[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)*
From 8ab4deb1030b4d863f8d8048b892d34f18dfaebe Mon Sep 17 00:00:00 2001 From: Srinjoy Pal <144480997+srinjoy07pal@users.noreply.github.com> Date: Mon, 25 Dec 2023 20:37:51 +0530 Subject: [PATCH 096/100] Update BinarySearch.java binary search explained in a better way using functions --- core-java/basics/BinarySearch.java | 62 ++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 17 deletions(-) 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); } } From b9b06afc2c6014e8cbff007992d34216c7e3ea3f Mon Sep 17 00:00:00 2001 From: NischalKothari Date: Thu, 28 Dec 2023 17:42:48 +0530 Subject: [PATCH 097/100] More Efficient Bubble Sort Code --- java-programs/BubbleSort.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) 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; + } } } From 4ccb582c7204ca58bdbd0683a5ab463204fe2508 Mon Sep 17 00:00:00 2001 From: Anup Maharjan <52039155+Anup6452@users.noreply.github.com> Date: Tue, 6 Aug 2024 18:23:11 +0545 Subject: [PATCH 098/100] Remove duplicate question --- java-multiple-choice-questions-answers.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/java-multiple-choice-questions-answers.md b/java-multiple-choice-questions-answers.md index 9bb173c..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 From cd7bbb61f8f8a96de9710c6687f120c91d8275e7 Mon Sep 17 00:00:00 2001 From: Kaustubh Pandey <146510603+kautubh01@users.noreply.github.com> Date: Tue, 27 Aug 2024 22:35:11 +0530 Subject: [PATCH 099/100] Update BoundedTypesGenerics02.java --- core-java/basics/BoundedTypesGenerics02.java | 39 ++++++++++---------- 1 file changed, 19 insertions(+), 20 deletions(-) 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(); + } } From 968a729f2577549397f7ad75f0f3bb5ef79bf1c4 Mon Sep 17 00:00:00 2001 From: Kaustubh Pandey <146510603+kautubh01@users.noreply.github.com> Date: Tue, 27 Aug 2024 22:42:13 +0530 Subject: [PATCH 100/100] Update EnumConstructorExample.java --- core-java/basics/EnumConstructorExample.java | 25 +++++++++----------- 1 file changed, 11 insertions(+), 14 deletions(-) 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()); } } }