What is Java.

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies.Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language.
Java main() Method – public static void main(String[] args)
1. Public
It is an Access modifier, which specifies from where and who can access the method. Making the main() method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
2. Static
It is a keyword that is when associated with a method, making it a class-related method. The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.
3. Void
It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn’t make any sense to return from the main() method as JVM can’t do anything with the return value of it.
4. main
It is the name of the Java main method. It is the identifier that the JVM looks for as the starting point of the java program. It’s not a keyword.
5. String[] args
It stores Java command-line arguments and is an array of type java.lang.String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it.
Why main() is static in Java?
  • Main() is static in java to make sure that it can be called without creating any instance.

Datatypes


Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

DatatypeDefault ValuesMemory Used
booleanfalse1 bit
char'\u0000'2 byte
byte01 byte
short02 byte
int04 byte
long0L8 byte
float0.0f4 byte
double0.0d8 byte

Reserved Keywords


Java has 67 reserved words that have a predefined meaning in the language.
You cannot use any of the reserved keywords as identifiers in your programs.
The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.

Exceptions/Errors


Exceptions - It is an event that occurs during the execution of the program and interrupts the normal flow of program instructions. These are the errors that occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by using the try-catch block and throws keyword.
There are two types of exceptions
  • checked exceptions
  • unchecked exceptions

Advantages of Exceptions
  • It separates error handling code from regular code.
  • It has the ability to propagate error reporting up the call stack of methods.
  • The grouping or categorizing of exceptions is a natural outcome of the class hierarchy.

Errors - In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error. Generally, it has been noticed that most of the occurring errors are abnormal conditions and cannot be resolved by normal conditions. As these errors are abnormal conditions and should not occur, thus, error and its subclass are referred to as Unchecked Exceptions.

Generics


Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature.
Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.

Abstract classes vs Interface


Abstract Class - Abstract class can have abstract and non-abstract methods.
Abstract class doesn't support multiple inheritance.
Abstract class can have final, non-final, static and non-static variables
Abstract class can provide the implementation of interface.
The abstract keyword is used to declare abstract class.
An abstract class can extend another Java class and implement multiple Java interfaces.
An abstract class can be extended using keyword "extends".
A Java abstract class can have class members like private, protected, etc.

Interface - Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Interface supports multiple inheritance.
Interface has only static and final variables.
Interface can't provide the implementation of abstract class.
The interface keyword is used to declare interface.
An interface can extend another Java interface only.
An interface can be implemented using keyword "implements".
Members of a Java interface are public by default.

Super/this keyword


“super” and “this” Java are two predefined keywords, that cannot be used as an identifier.
“super” in Java is used to refer to methods, static and instance variables, constructors of an immediate parent class.
“this” in Java is used to refer to methods, static and instance variables, constructors of a current class.

super() acts as immediate parent class constructor and should be first line in child class constructor.
this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
Can we use this () and super () in a method?
No, we cannot use this() and super() in a method in java.
can a constructor call another constructor java?
Constructor chaining refers to the ability to call a constructor inside another constructor. You can use a constructor chain either within the same class or even with another one. For the latter, the constructor should be through inheritance from the super class.The line inside a constructor that calls another constructor should be the first line of the constructor.

Static/non-static members

  • A non-static class can have both static and non-static members .
  • ___________
  • Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object.static methods are not inherited.
    If a superclass member is accessible by its simple name in the subclass (without the use of any extra syntax like super), that member is considered inherited.
  • ____________
  • Can a non static parent class have static child class. - No You are not able to call a non-static method of a parent class from a static method of a child class. Your best option is to make the method non-static.
  • _____________
  • Static class can't have non static members - Static classes can't be instantiated in the first place, so even if you could declare non-static (instance) members, they can never be accessed.
  • _____________
  • The static nested class can't directly access outerField because it's an instance variable of the enclosing class, OuterClass. The Java compiler generates an error at the highlighted statement:
    public class OuterClass {
    String outerField = "Outer field";
    static class StaticNestedClass {
    void accessMembers(OuterClass outer) {
    // Compiler error: Cannot make a static reference to the non-static
    // field outerField System.out.println(outerField); }
    } }
    To fix this error, access outerField through an object reference:
    System.out.println(outer.outerField);
In versions prior to java8 , we were able to execute our program without main() using static block but not from java 8.

Superclass members


A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).
In other words the superclass, also known as the parent class , is the class from which a child class (or a subclass) inherits its constructors
The class named Object is the super class of every class in Java.

JDK/JRE/JVM/JIT


Java Virtual Machine (JVM) is an abstract computing machine.
Java Runtime Environment (JRE) is an implementation of the JVM.
Java Development Kit (JDK) contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools.
Just In Time compiler (JIT) is runs after the program has started executing, on the fly. It has access to runtime information and makes optimizations of the code for better performance.
jdk is a software development environment that is used to develop,compile & execute java applications & applets.jre is implementation of jvm.jdk is a superset that includes jre , compiler & other system files & library.
Main difference between JRE and JDK is that, you can not compile Java program using JRE.
Tools required for compiling Java source file to create class files, i.e. javac, comes with JDK installation.JDK is something you will need to compile your code to make them executable by your JRE.You will need javac for compiling your code which is present in JDK. Jre can only be use to run a java program and is developed as browser plugin. In order to run any Java program from browser.
JRE was required to run applets like java app on users machines
Firstly java is compiled to bytecode, which then either compiled, or interpreted depending on mood of JIT.
Similarity & distinction in JDK & jre ->
you downloaded just a JRE if you were only interested in running Java program's. If a programmer would like to execute a Java program using the Java command, they should install JRE.
JDK includes all the Java tools, executables and binaries needed to run Java programs. This includes JRE, a compiler, a debugger, an archiver and other tools that are used in Java development.

Collections Framework


A collection is an object that represents a group of objects (such as the classic Vector class). A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.
Benefits :
Reducing the effort required to write the code by providing useful data structures and algorithms
Java collections provide high-performance and high-quality data structures and algorithms thereby increasing the speed and quality
Supports reusability of standard data structures and algorithms
Inside collection framework , we have certain classes and interfaces.like-
1.The Collection Interface
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
2 The List Interface
This extends Collection and an instance of List stores an ordered collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique elements.
4 The SortedSet
This extends Set to handle sorted sets.
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in an ascending order.
8 The Enumeration
This is legacy interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects. This legacy interface has been superceded by Iterator.

Concurrent Collection


Concurrent Collections are thread-safe collection classes that we should use in a scenario where our code involves simultaneous access to a collection. Unlike collections, concurrent collections have a reliable behavior in a multi-threaded environment(with concurrent access to the collection).
ConcurrentHashMap - provides a concurrent alternative to Hashtable or Synchronized Map classes with the aim to support a higher level of concurrency.
Iterator of ConcurrentHashMap are fail-safe iterators that don't throw ConcurrencModificationException thus eliminates another requirement of locking during iteration which results in further scalability and performance.
CopyOnWriteArrayList and CopyOnWriteArraySet - CopyOnWriteArrayList is a concurrent alternative of synchronized List. CopyOnWriteArrayList provides better concurrency than synchronized List by allowing multiple concurrent readers and replacing the whole list on write operation.
write operation is costly on CopyOnWriteArrayList but it performs better when there are multiple readers, and the requirement of iteration is more than writing. Since CopyOnWriteArrayList Iterator also doesn't throw ConcurrencModificationException it eliminates the need to lock the collection during iteration.
BlockingQueue - BlockingQueue makes it easy to implement producer-consumer design pattern by providing inbuilt blocking support for the put() and take() method. put() method will block if the Queue is full while the take() method will block if the Queue is empty.
Deque and BlockingDeque - Deque interface is added in Java 6 and it extends Queue interface to support insertion and removal from both ends of Queue referred to as head and tail. Java6 also provides a concurrent implementation of Deque like ArrayDeque and LinkedBlockingDeque.

Traditional Collection

The Java collections framework provides a set of interfaces and classes to implement various data structures and algorithms. Use of collections framework classes and interfaces is a biggest merit of using Java .

Different classifications under traditional collections -



Collections Framework Vs. Collection Interface
The Collection interface is the root interface of the collections framework. The framework includes other interfaces as well: Map and Iterator.
Here are the subinterfaces of the Collection Interface:

List Interface
The List interface is an ordered collection that allows us to add and remove elements like an array. Set Interface
The Set interface allows us to store elements in different sets similar to the set in mathematics. It cannot have duplicate elements. Queue Interface
The Queue interface is used when we want to store and access elements in First In, First Out manner.
Java Map Interface
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are unique names that can be used to access a particular element in a map. And, each key has a single value associated with it.
Java Iterator Interface
In Java, the Iterator interface provides methods that can be used to access elements of collections.

VM Arguments

The values that we passed I side vm arguments r to be accessed and taken care by the JVM. Present inside system properties. We can access vm argument file using System.getProperty() method.
What data to pass inside VM Argument :
  • * Any info that needs to be available in the system properties.
  • * Controlling the Heap size , data memory size , code cache size which is the tuning of the JVM .
  • * To give any algorithm for garbage collection.
  • * To run any jar file from cmd using vm arguments.

VM arguments data is processed by java SW interpreter .eg... When we run some commands like java -Dxyz p1 p2 Here, java -D is interpreter which makes data xyz available to the JVM. P1 & P2 r program argument
Program Arguments Vs VM Arguments:
  • The values passed inside the program arguments r actually the command line parameters that r accepted by the main(String[] args) Arguments .
  • VM arguments r of knowledge to the JVM.
___________________________
Setting heap size using vm arguments :
-Xms128mere : minimum heap size
-Xmx1024mere : maximum heap size

Serialisation


Serialization - a mechanism of writing the state of an object into a byte-stream.
Deserialisation - byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.

Java Applet Vs Applications


Applet id a most popular web application language that uses java for websites development.
Applet is a program that runs on web browser .ie..it always require internet connection for functioning. Which is not so incase of a java application. Java applications are stand alone applications that needs a JRE as an environment to execute the application. Applets program have a specific life cycle to execute it's code & do not necessarily require main() to start its execution and since applet require browser based access than it is also more prone to security threats.Hence, an applet program needs more security.
For any java program that runs on internet uses applet in it.It can perform arithmetic operation, display some graphics, play sounds,accepting of user inputs,creating animations.ie..for any interactive multimedia files animation etc.we can use java as an applet.It can represent a interactive web documents that can contain not only text but also other media files ,movies,animation,sounds,graphics etc.in it's web page.

Multithreading

Can a given thread be started & called twice ?
No, we cannot start Thread again, doing so will throw runtimeException java.lang.IllegalThreadStateException a Thread can only be started once.If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it. (When a thread is started it called start() which internally called run() ). So , After starting a thread, it can never be started again. Hence, we can't call a same thread multiple times.
Problem with multithreading
Increased difficulty level of code.
Deadlock occurrence if not using synchronize
Overhead due to thread switching

Executor Framework

Executor Framework in java ->A framework having a bunch of components that are used for managing worker threads efficiently is referred to as Executor Framework. It is used to run the Runnable objects without creating new threads every time and mostly re-using the already created threads. It is helpful in resolving IllegalThreadStateException.
In order to use the executor framework, we have to create a thread pool for executing the task by submitting that task to that thread pool.
Executor Importance over Thread class
We need to create a large number of threads for adding a new thread without any throttling for each and every process. Due to which it requires more memory and cause wastage of resource. When each thread is swapped, the CPU starts to spend too much time.
When we create a new thread for executing a new task cause overhead of thread creation. In order to manage this thread life-cycle, the execution time increase respectively.

Design pattern in java

Design Pattern is a description or guideline to solve a problem that occurs repeatedly while developing a software Applications. Design Patterns will help us in fixing performance and memory related issues.
With strong design pattern you will complete your development earlier than the expected time and number of bugs will also be very negligible.
Design Patterns help in finding the solution of a complex problem.
Using design patterns, we can make our code loosely-coupled.
Furthermore, it will have the option of reusable codes, which reduce the total development cost of the application.
  • * creational design pattern ( single ton,prototype etc)
  • * structural design pattern
  • * behavioral design pattern

Compiler Vs Interpreter


When we compile our code than code produces an executable file but incase of interpreter no executable file is produced as the code is executed line by line that9 why it is slower and also debugging through interpreter is easy.
The code of interpreter is portable ie.. It can run on any machine where interpreter is installed.
__________
Hybrid approach - it combines the functioning of both compiler& interpreter. The compiler generates byte code from our code and than that byte code can be easily executed in any machine having interpreter installed in it.
____________
  • Compiled language - c,c++
  • Interpreted lang - js, php
  • Hybrid lang - java, c#, kotlin

OOPS concept


OOPs refers to languages that use objects in programming, they use objects as a primary source to implement what is to happen in the code. Objects are seen by the viewer or user, performing tasks assigned by you.
Pillars of OOPs -
Abstraction
Encapsulation
Inheritance
Polymorphism
  • Compile-time polymorphism
  • Runtime polymorphism

Access/Non-access modifiers


Non-access modifier : The static modifier for creating class methods and variables.
The final modifier for finalizing the implementations of classes, methods, and variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
Access Modifier : Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

Modifiers public, static, strictFp etc they all can be placed in any order before giving the return type.
eg... public static int sum() same as static public int sum().
Access modifiers visibility sequence is : private < default < protected < public which means private is the most restrictive & public is the least restrictive modifier.

visibilty scope


Private: can access the private modifier only within the same class and not from outside the class.
Default: We can access the default modifier only within the same package and not from outside the package. And also, if we do not specify any access modifier it will automatically consider it as default.
Protected: We can access the protected modifier within the same package and also from outside the package with the help of the child class. If we do not make the child class, we cannot access it from outside the package. So inheritance is a must for accessing it from outside the package.
Public: We can access the public modifier from anywhere. We can access public modifiers from within the class as well as from outside the class and also within the package and outside the package

Overriding rules


The following rules for inherited methods are enforced for overridding class-
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.

if parent is protected then child as public is allowed. Child class must not throw newer or broader checked exceptions. . May throw narrower(below in class hierarchy) checked exceptions or any unchecked exception.

Enum


Enum is a type like a class or interface but it can't extend any other class. We cannot create enum instance outside of enum b'coz it can't have public constructor in Enum and compiler doesn't allow any public constructor inside the Enum. Enum can only allow private constructor . An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
eg ...
enum Level {
LOW,
MEDIUM,
HIGH
}
You can access enum constants with the dot syntax:
Level myVar = Level.MEDIUM; //output - MEDIUM

Features of Java 8 to Java 19

Java8 -> Lamdas, stream APIs Java9 -> Interface included private methods. Introduced use of advance methods [helper methods] under collections interface.
eg... List list = List.of("one", "two", "three");
Set set = Set.of("one", "two", "three");
Map map = Map.of("foo", "one");
____________
Switch from java8 to java9 ->
Build tools (Maven, Gradle etc.) and some libraries initially had bugs with versions Java versions > 8 and needed updated. Hence, came up with java9. Up until Java 8 you were pretty much using Oracle’s JDK builds and you did not have to care about licensing. Oracle changed the licensing scheme In 2019.
Up until Java 8, the Oracle website offered JREs and JDKs as separate downloads - even though the JDK also always included a JRE in a separate folder. With Java 9 that distinction was basically gone, and you are always downloading a JDK. The directory structure of JDKs also changed, with not having an explicit JRE folder anymore.
Naming scheme before java9 -- Java 8 can also be called 1.8, Java 5 can be called 1.5 etc. 
________________
Starting from Java 10 -> we can run Java source files without having to compile them first. A step towards scripting.
_____________
Java10 -> Unique garbage collection mechanism, Introduction of the "var"-keyword, also called local-variable type inference.
eg... String myName = "Marco"; //pre java10
var myName = "Marco"; // with java10
Java14 -> Got standardized switch case structure than java 12,13.Enhanced switch case structure would look like -
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
default -> { String s = day.toString();
int result = s.length();
yield result; }
};
Java16 -> Java 16 (no need of casting)
Pattern Matching for instanceof
Instead of:
if (obj instanceof String) { String s = (String) obj; // e.g. s.substring(1) }
You can now do this:
if (obj instanceof String s) { // Let pattern matching do the work! // ... s.substring(1) }

Java 8


It includes a huge upgrade to the Java programming model and a coordinated evolution of the JVM, Java language, and libraries.
he fact that Java 8 is an LTS (Long-Term Support) version is one of the main reasons for its continued popularity. It includes all the new features such as - Lambdas
Streams
Optionals
Functional Interfaces
Parallel Programming
Only Java 8 (2014) and Java 11 (2018) have been recognised as having LTS since the policy was implemented.

Functional Interface

Predefined functional interface benefit ->
make our programming easier. Moreover, Predefined Functional Interfaces include most commonly used methods which are available to a programmer by default. 
They will obviously save our development time and minimize chances of mistakes.

Lambda Expression


A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
Lambda expressions can only be used in context of Functional interfaces. You can assign a lambda expression to a single abstract method (i.e. To a Functional interface). If you could assign a lambda expression to an interface containing more than one abstract method (i.e. a non functional interface), the lambda expression could only have implemented one of its methods, leaving the other methods unimplemented. That’s why Lambda expressions don’t have method name, return types etc. as it talks about a single abstract method.
Lambda expressions are a new and important feature included in Java SE 8. They provide a clear and concise way to represent one method interface using an expression. Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection .
Lambda Advantages
Lambda enables you to use functions with pre-trained machine learning (ML) models to inject artificial intelligence into applications more easily. A single application programming interface (API) request can classify images, analyze videos, convert speech to text, perform natural language processing, and more.
Lambda Disadvantage
they are so syntactically simple to write but so tough to understand if you're not used to them. So if you have to quickly determine what the code is doing, the abstraction brought in by lambdas, even as it simplifies the Java syntax, will be hard to understand quickly and easily.

Stream APIs


Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
Stream API contains various inbuilt methods that supports aggregate methods.It follows a pipeline type of structure starting from source than It may have no or some intermediate operations followed by terminal operations. intermediate operations r optional.
it is a technique to make processing of collection’s data easy by supporting functional-style operations.
Sequential stream :
Parallel stream : It allows us to do operations on collection in thread safe mode.
The features of Java stream are –
A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Different Operations On Streams-
Intermediate Operations:(),filter,sorted()
Terminal Operations:(),foreach(),reduce()

Method Reference


Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
It is a shorthand notation of a lambda expression to call a method. We can replace lambda expression with method reference (:: operator) to separate the class or object from the method name.
Sometimes, a lambda expression only calls an existing method. In those cases, it looks clear to refer to the existing method by name. The method references can do this, they are compact, easy-to-read as compared to lambda expressions. A method reference is the shorthand syntax for a lambda expression that contains just one method call.
To print all elements in a list
Using Lambda - list.forEach(s -> System.out.println(s));
Using Method Reference - list.forEach(System.out::println);

Map-Reduce APIs


It is used to implement MapReduce type operations. Essentially we map a set of values then we reduce it with a function such as average or sum into a single number.
The MapReduce is a paradigm which has two phases, the mapper phase, and the reducer phase. In the Mapper, the input is given in the form of a key-value pair. The output of the Mapper is fed to the reducer as input. The reducer runs only after the Mapper is over. The reducer too takes input in key-value format, and the output of reducer is the final output.
Usage of MapReduce
It can be used in various application like document clustering, distributed sorting, and web link-graph reversal.
It can be used for distributed pattern-based searching.
We can also use MapReduce in machine learning.
It was used by Google to regenerate Google's index of the World Wide Web.

Default Methods in interface

Default methods in interface (java8) : declare a method as default which has very less or negligible chances to be overridden by subclasses. 
The primary idea of including default method in interface is that don’t force the implementing classes to override it.
Till JDK 1.7, all implementing classes were supposed to override the method declared in the interface and provide the concrete implementation of the methods. But after the introduction of default method in Interface, implementing classes are free to either override it or not as per the required behavior.
default method save effort in writing extra lines of code.

Switch to Java 8


Lambda expression helps us to write our code in functional style. It provides a clear and concise way to implement SAM interface(Single Abstract Method) by using an expression. It is very useful in collection library in which it helps to iterate, filter and extract data.
Java 8 is useful due to the use of certain shorthand method/class properties like-
Lambda Expression
Lambda expression helps us to write our code in functional style. It provides a clear and concise way to implement SAM interface(Single Abstract Method) by using an expression. It is very useful in collection library in which it helps to iterate, filter and extract data.
Optional
Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application. We must import java.util package to use this class. It provides methods to check the presence of value for particular variable.
Functional Interface
An Interface that contains only one abstract method is known as functional interface. It can have any number of default and static methods. It can also declare methods of object class. Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).
Method Reference
Java 8 Method reference is used to refer method of functional interface . It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
forEach()
Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream interfaces. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach() method to iterate elements.
DateTime API
Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date and Time classes.
Default Methods
Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with default keyword are known as default methods. These methods are non-abstract methods and can have method body.

Different Java Edition

Java is distributed in three different editions: Java Standard Edition (Java SE), Java Enterprise Edition (Java EE) and Java Micro Edition (Java ME). A new introduced is JavaFX.
JavaSE = Standard Edition. This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...).
Java EE = Enterprise Edition. The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server.
In other words, if your application demands a very large scale, distributed system, then you should consider using Java EE. Built on top of Java SE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JMS), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, Java Server Pages, etc...
Java ME = Micro Edition. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. Java ME provides a subset of the functionality of Java SE, but also introduces libraries specific to mobile devices. Because Java ME is based on an earlier version of Java SE, some of the new language features introduced in Java 1.5 (e.g. generics) are not available.
Java FX - JavaFX is a software platform for creating and delivering desktop applications, as well as rich web applications that can run across a wide variety of devices. JavaFX has support for desktop computers and web browsers on Microsoft Windows, Linux, and macOS, as well as mobile devices running iOS and AndroidJavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.
If you are new to Java, definitely start with Java SE.

Java SE Version History

Java SE VersionVersion Number Release Date
JDK 1.0(Oak)1.0January 1996
JDK 1.11.1February 1997
J2SE 1.21.2December 1998
J2SE 1.31.3May 2000
J2SE 1.4(Merlin)1.4February 2002
J2SE 5.0(Tiger)1.5September 2004
Java SE 6(Mustang)1.6December 2006
Java SE 7(Dolphin)1.7July 2011
Java SE 81.8March 2014
Java SE 99September, 21st 2017
Java SE 1010March, 20th 2018
Java SE 1111September, 25th 2018
Java SE 1212March, 19th 2019
Java SE 1313September, 17th 2019
Java SE 1414March, 17th 2020
Java SE 1515September, 15th 2020
Java SE 1616March, 16th 2021
Java SE 1717September, 14th 2021
Java SE 1818March, 22nd 2022
Java SE 1919September, 20th 2022
Java SE 2020March, 21st 2023

Java SE Vs Java EE

Java is synonymous with Java Standard Edition (Java SE) or Core Java.  Java EE, on the other hand, provides APIs and is typically used to run larger applications.
JavaSE - It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.
In addition to the core API, the Java SE platform consists of a virtual machine, development tools, deployment technologies, and other class libraries and toolkits commonly used in Java technology applications.
Java EE The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

Java Swing Vs Java FX


Java Swing helps programmers create graphical user interface (GUI) applications, and helps make them cleaner and more efficient.
With Swing, developers are free to create labels, buttons, and other UI components.
Java FX is the newly introduction in Java edition history and came after Swing. FX behaves as a GUI library and lends itself to efficient and rapid development of desktop apps. Java FX has a modern design and provides developers with easy access to Rich Internet Application.It gives added support to Swing like - to easily add to create blurs, shadows, and other textural touch-ups.
Key differences :

Swing sees lots of use in GUI creation,and Desktop applications come together more easily when we use FX.
Swing has a wider range of UI components compared to FX, but FX adds more all the time.Swing can provide UI components with a decent look and feel, whereas JavaFX can provide rich internet application having a modern UI.
Swing has a more sophisticated set of GUI components, whereas JavaFX has a decent number of UI .
components available but lesser than what Swing provides.
FX offers consistent support for MVC, while Swing’s MVC support is not equal across all platforms.
FX adds modern touches to your project and makes adding animation and special effects a snap. FX is also the choice for folks who develop mobile apps—it is much more geared to work with mobile programs than Swing.

Class loader in Java


The Java Class Loader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems as this is delegated to the class loader.
There are three types of built-in ClassLoader in Java.
Bootstrap Class Loader – It loads JDK internal classes. It loads rt.jar and other core classes for example java.lang.* package classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – classloader loads classes from the current classpath.

Class loader working and types


Every class loader has a predefined location, from where they load class files. The bootstrap class loader is responsible for loading standard JDK class files f rom rt.jar and it is the parent of all class loaders in Java. The bootstrap class loader doesn't have any parents if you call String.class.getClassLoader() it will return null and any code based on that may throw NullPointerException in Java. The bootstrap class loader is also known as Primordial ClassLoader in Java.
Extension ClassLoader delegates class loading request to its parent, Bootstrap, and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader.
The third default class loader used by JVM to load Java classes is called System or Application class loader and it is responsible for loading application-specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Application class loader a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class. Also, except for the Bootstrap class loader, which is implemented in the native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader.

Static/Dynamic Loading


Static loading refers to loading the whole program into the main memory before executing the program. Dynamic loading refers to the process of loading a program into the main memory on demand.
In Java static binding to the execution of a program where type of object is determined/known at compile time i.e when compiler executes the code it know the type of object or class to which object belongs. While in case of dynamic binding the type of object is determined at runtime.

Stackoverflow error in java


StackOverflowError is a runtime error which points to serious problems that cannot be caught by an application. The java. lang. StackOverflowError indicates that the application stack is exhausted and is usually caused by deep or infinite recursion.
The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack. How do I fix stackoverflow error in java?
Carefully inspecting the error stack trace and looking for the repeating pattern of line numbers enables locating the line of code with the recursive calls. When the line is identified, the code should be examined and fixed by specifying a proper terminating condition.

Static block initialiser


a static block executes code before the object initialization. A static block is a block of code with a static keyword. A static initialization block is mostly used for changing the default value of static variables. A static variable in Java is a variable that belongs to the class and is initialized during the loading of the class into memory. Static variables are initialized only once, at the start of the execution.
Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program.

Shallow copy/Deep copy


In shallow copy, only fields of the primitive data type are copied while the objects' references are not copied. Deep copy involves the copy of primitive data types as well as to object references. There is no hard and fast rule as to when to do shallow copy and when to do a deep copy.
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
In shallow copy, the created reference will point to the original object while in deep copy , the newly created object will be independent of the original object.ie.. the reference will point to the memory location of the newly created object not the original object.

Immutable Objects


An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.
its state doesn't change after it has been initialized. For example, String is an immutable class and, once instantiated, the value of a String object never changes
Immutable object remains in 1 state in which they r created throughout as they don't allow any change with them Hence, they r thread safe.
The internal state of program is consistent even if there r some exception.

Garbage Collector


Garbage collection in Java is the automated process of deleting code that's no longer needed or used. This automatically frees up memory space and ideally makes coding Java apps easier for developers. Java applications are compiled into bytecode that may be executed by a JVM.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
finalize() method The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing.
gc() method The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
gc()(static method) is use to call garbage collector to perform clean up processing present in system & runtime class to unreference & destroy the object than garbage collector thread calls finalize method(protected) present in object class . It is a method defined in Object class.
Garbage collector calls this method to perform clean up activities before destroying the object from the memory.

JDBC/JPA/JSP/Hibernate


JDBC is a programming-level interface for Java applications that communicate with a database. An application uses this API to communicate with a JDBC manager. It's the common API that our application code uses to communicate with the database.
JPA is a Java standard that allows us to bind Java objects to records in a relational database. It's one possible approach to Object Relationship Mapping(ORM), allowing the developer to retrieve, store, update, and delete data in a relational database using Java objects.
JPA vs JDBC
JDBC allows us to write SQL commands to read data from and update data to a relational database. JPA, unlike JDBC, allows developers to construct database-driven Java programs utilizing object-oriented semantics.
When associating database tables in a query with JDBC, we need to write out the full SQL query, while with JPA, we simply use annotations to create one-to-one, one-to-many, many-to-one, and many-to-many associations.
JDBC is database-dependent, which means that different scripts must be written for different databases. On the other side, JPA is database-agnostic, meaning that the same code can be used in a variety of databases with few (or no) modifications.

Pros and Cons
The most obvious benefit of JDBC over JPA is that it's simpler to understand. On the other side, if a developer doesn't grasp the internal workings of the JPA framework or database design, they will be unable to write good code.

JSP/JPA/JDBC/Hibernate Usecase


JPA is thought to be better suited for more sophisticated applications by many developers. But, JDBC is considered the preferable alternative if an application will use a simple database and we don't plan to migrate it to a different database vendor.
a well-tested and robust framework is handling the interaction between the database and the Java application, we should see a decrease in errors from the database mapping layer when using JPA.
1. JSP & Servlets: JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content. Servlets run faster compared to JSP.
2. Spring: Spring is the most popular application development framework for enterprise Java. we use Spring Framework to create high performing, easily testable, and reusable code.
3. JDBC: Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. It is part of the Java Standard Edition platform, from Oracle Corporation.
4. Hibernate : Hibernate framework simplifies the development of java application to interact with the database.

Java Card

This edition was targeted, to run applets smoothly and securely on smart cards and similar technology.
__
Java Card
Java Card is an industry-standard technology platform developed by Sun Microsystems (now Oracle) to enable Java-based applications - applets - to run on smart cards.
Java Card helps developers build, test, and deploy smart card-based applications quickly and efficiently with an object-oriented programming model
Java Card technology is used in a wide range of smart card applications,
Smart ID badges
SIM
Government id & health card

Java applications in realtime


Android SDK uses java
(#1) Desktop GUI Applications
(#2) Web Applications
(#3) Mobile Applications
(#4) Enterprise Applications
(#5) Scientific Applications
(#6) Web Servers & Applications Servers
(#7) Embedded Systems
(#8) Server Apps In Financial Industry
(#9) Software Tools
(#10) Trading Applications
(#11) J2ME Apps
(#12) Big Data Technologies

Frameworks

Framework is a layered structure built on top of a programming language. For example, Rails, also known as Ruby on Rails, is a web framework built on top of the Ruby programming language.Collection of packages or modules that allows us to perform a task or service.
frameworks are software libraries created to make building applications easier and faster.
It is often a layered structure indicating what kind of programs can or should be built and how they would interrelate.

Diamond Warning<> [Java 7]


It came to simplify the use of generics when creating object. It avoids unchecked warnings & make the program more readable. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side.
The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.
The only difference if you specify in Java 5 and 6,
List list = new ArrayList();
is that you have to specify @SuppressWarnings("unchecked") to the list (otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.

Sealed class [JDK 15]


Restrict any class to be sub class of any other class without final keyword by using sealed keyword . Java sealed classes and interfaces restrict that which classes and interfaces may extend or implement them. In other words, we can say that the class that cannot be inherited but can be instantiated is known as the sealed class.
we can seal classes by applying the same sealed modifier. The permits clause should be defined after any extends or implements clauses:
public abstract sealed class Vehicle permits Car, Truck {
protected final String registrationNumber;
public Vehicle(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationNumber() {
return registrationNumber;
}
}

Sealed class Example


A permitted subclass must define a modifier. It may be declared final to prevent any further extensions:
public final class Truck extends Vehicle implements Service {
private final int loadCapacity;
public Truck(int loadCapacity, String registrationNumber) {
super(registrationNumber);
this.loadCapacity = loadCapacity;
}
public int getLoadCapacity() {
return loadCapacity;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 18;
}
}
A permitted subclass may also be declared sealed. However, if we declare it non-sealed, then it is open for extension:
public non-sealed class Car extends Vehicle implements Service {
private final int numberOfSeats;
public Car(int numberOfSeats, String registrationNumber) {
super(registrationNumber);
this.numberOfSeats = numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
@Override
public int getMaxServiceIntervalInMonths() {
return 12;
}
}

Annotation in Java


Annotations( a form of metadata , conveys some special meanings to the compiler) became available in Java since JDK 1.5.
With annotation , the user can get an alert or warning incase we write something wrong or missing anything to write.Such annotation Expression will become prevalent at compile-time.It behaves same as comment but also reveal the intention of the user to the computer that what he actually want to do if he has committed some error.
eg... @override, @suppresswarning etc.

Marker Interface


Marker interface - An interface that does not contain methods, fields, and constants is known as marker interface. It delivers the run-time type information about an object. It is the reason that the JVM and compiler have additional information about an object. it inform the Java compiler by a message so that it can add some special behavior to the class implementing it.
__________
clone() of cloneable marker interface - It generates replica (copy) of an object with different name.
(eg... crudrepotory,jparepository r marker interface) built-in marker interfaces are the interfaces that are already present in the JDK and ready to use.
#1 Serializable interface: Serializable is a marker interface present in the java.io package. We can serialize objects using this interface i.e. save the object state into a file. Serialization can be defined as a process by which we convert the object state into its equivalent byte stream to store the object into the memory in a file or persist the object.
When we want to retrieve the object from its saved state and access its contents, we will have to convert the byte stream back to the actual Java object and his process is called deserialization.
The entire mechanism of serialization and deserialization is platform-independent. This means that we can serialize the object on one platform and then deserialize it on a different platform.
When we say that we have serialized the Java object, it means that we have called the ObjectOutputStream method writeObject () to write the object to a file.
Similarly, in the case of deserialization, we call the ObjectInputStream:: readObject () method to read the data from the file that has stored the object.
If a particular field is not serializable then we should mark it as transient.
Java.io.NotSerializableException
thrown when the class is not eligible for serialization. The class that does not implement the Serializable interface becomes ineligible for serialization.
Serialization (writing)
deserialization (reading)
#2 Cloneable interface: The cloneable interface is a part of the java.lang package and allows the objects to be cloned. Object cloning is a process using which we create an exact copy of the object using the clone () method of the Object class
The clone () method creates an exact copy of the object with less processing time than that taken for creating a new object using the new keyword.
CloneNotSupportedException : If a class does not implement a Cloneable interface and still invokes the clone () method,
When the one-dimensional array is cloned, a deep copy of the array is generated. When a 2-dimensional array is cloned, then a shallow copy is made.
Making a shallow copy is the default behavior of the clone () method in Java.
In deep cloning, we make a copy of the object that is independent of the original object. Any changes then made to the clone object will not reflect in the original .
The default implementation of the clone () method creates a shallow copy of the object while we can override the clone () method to create a deep copy.
#3 Remote interface: The remote interface is a part of the java.RMI package and we use this interface to create RMI applications It marks an object as remote that can be accessed from another machine (host).
__________
How annotations can be use as a replacement to marker interface
As marker interfaces are mostly useful for just marking a class, the same thing can be achievable through annotations. Marker interfaces are better than annotations when they're used to define a type. For example, Serializable can be used as the type of an argument that must be serializable.
public void writeToFile(Serializable object);
If the marker interface doesn't define a type, but only meta-data, then an annotation is better.