Java Theory Notes
Java Theory Notes
JAVA
⁉️ HOTS
Introduction to Java 🌟
Java is a simple programming language that was developed by Sun
Microsystems Inc in 1991, later acquired by Oracle Corporation. It was
developed by James Gosling and Patrick Naughton.
Java is based on the concept of OOP. As the name suggests, at the center of it
all is an object. Objects contains both data and functionality that operates on
JAVA 1
the data. This is controlled by the following paradigms:
Information Hiding
Program run phase: the JVM executes the bytecode generated by the
compiler
JAVA 2
"The primary function of JVM is to execute the bytecode
produced by the compiler."
Each operating system has a different JVM, but the output they produce after
execution of bytecode is the same across all operating systems. This is why
Java is called a platform independent language.
Bytecode 💻
The javac compiler of JDK compiles the Java source code into bytecode, which
is saved in a .class file by the compiler.
compilers
To create, compile, and run a Java program, you need JDK installed on your
computer.
JVM
browser plugins
applets support
With JRE installed on your system, you can run a Java program, but you won't
be able to compile it.
JAVA 3
This bytecode can run on any platform, such as Windows, Linux, Mac OS,
etc.
B. Object-Oriented Language
Abstraction
Encapsulation
Inheritance
Polymorphism
C. Simple
Java is considered a simple language because it does not have complex
features like:
Operator overloading
Multiple inheritance
Pointers
D. Robust
Java is a robust language that emphasizes early checking for possible
errors
Garbage collection
Exception Handling
Memory allocation
E. Secure
Java does not have pointers
This makes Java secure and prevents several security flaws like stack
corruption or buffer overflow
JAVA 4
F. Distributed
Java can be used to create distributed applications using:
Java programs can be distributed on more than one system connected via
the internet
G. Multithreading
Java supports multithreading, which allows concurrent execution of two or
more parts of a program for maximum utilization of CPU
H. Portable
Java code that is written on one machine can run on another machine
Component Description
Class Loader Reads [Link] file and saves the bytecode in the method area
Keeps track of which instruction has been executed and which one is
PC Registers
going to be executed
Native Method Enables native methods to access runtime data areas of the virtual
Stack machine
Native Method
Enables Java code to call or be called by native applications
Interface
Garbage
Automatically destroys class instances for memory management
Collection
JAVA 5
JVM Vs JRE Vs JDK 🤔
Aspect JDK JRE JVM
Superset of JRE,
Runs the program by
includes
Environment within using class, libraries,
development tools
which JVM runs and files provided by
like compiler,
JRE
debugger, etc.
Just-in-time compiler
Component javac JVM
(JIT)
Platform
No, platform-specific Yes Yes
Independent
User by
Yes No No
developers?
Used By end
No Yes No
users?
Needed for
Yes No No
Compilation
JAVA 6
}
}
Output:
Go to the directory where you have installed Java on your system and
locate the bin directory
Copy the complete path and write it in the command like this: set
path=C:\Program Files\Java\jdk1.8.0_121\bin
Type the following command on the terminal to confirm the path: echo
$JAVA_HOME
JAVA 7
Temporary Path Setup
The steps above are for setting up the path temporarily, which means that
when you close the Command Prompt or Terminal, the path settings will be lost
and you will have to set the path again next time you use it.
Data Type
Data types are the used to define the type and size of the data that can be
stored in variables.
Essential for declaring the variables, specifying the function return types and
ensuring type safety.
Java supports the range of primitive and non-primitive(reference) data types.
JAVA 8
Class Definition
JAVA 9
Class Access Modifier
These are the keywords used to control the visibility and accessibility of a
class, method, variables and other members in the java program.
Define the level of access that other classes have over the current class
members.
Public
Widest visibility
Protected
they’re accessed only by the same class and subclass and package
(also from other classes within same package) not outside the
package
Private
they’re not visible from other classes and not even from subclasses
Default
Multiple instance multiple object from a class different instances with own data
JAVA 10
Feature Class Object
Static member
Variables in method that are declared using the static keyword are the static
members of a class .
Static members are belong to the classes instead of instance of class.
Static Members help to maintain the common data across the classes instances
methods and constraints.
There are two types of static variable:
1. Static Variable
b. They act like the global variables and can be accessed by any instance
of the class and have only single copy in the memory.
c. They are accessed by using the class name followed by dot(.) operator.
2. Static method
b. They can not access the instance specific data (non static members)
because they do no have access to the “this”.
d. They are invoked by using the class name followed by dot(.) operator.
4.
JAVA 11
Main Method
public static void main(String[] args) { ... }
Definition: This is the entry point method from which the JVM
can run your program.
Keyword Description
Makes the main method public, which means it can be called from
public
outside the class.
import [Link];
JAVA 12
long n = [Link]();
JAVA 13
Subsets of java lang
Reference Data type: These are the data types that stores reference to
objects.
Identifiers
Name given to various program elements - variables, constants, clas,
methods, etc..
May consist of letters, digits and the underscores character, with no space
between.
JAVA 14
First Character must be an alphabet or underscore.
Array
It is an data structure used to store a collection of elements of the same data
type.
It provide a way to group multiple values of same data type together under a
single variable name.
Each element can be accessed by an index(non negative integer).
<type><array name>[];
int x[];
<type>[]>arrayname>;
int [] x;
// in one go define
<type><arrayname>[]=new<type>[<size>];
int x[] =new int[100];
// 2D ARRAY
int array[][];
int array[][]=new int[3][4];
<arrayname>=new<type>[<size>];
x=new int[100];
JAVA 15
// 2D ARRAY
array=new int[3][4];
<type><arrayname>[]={<list of values>};
int x[]={12,56,78};
// 2D Array
int array[][]={{112,3},{4,5},{7789,56}};
Encapsulation in JAVA
The object is at the core of java programming.
JAVA 16
A class defines the shape and working of an object
The concept of class is the logical construct upon which the entire java lang
is built.
Class
It is a group of objects which have common properties.
It is a logical entity.
It contains
Fields
Methods
Constructor
Blocks
The name of the program file should be same as the name of the main class
followed by .java as an extension.
If there is no main class, then there should be compilation error i.e. that
program cannot be compiled or executed.
JAVA 17
Constructor
It can be tedious to initialize all of the variables in a class each time an
object is instantiated.
JAVA 18
Types of constructor
Default Constructor
Parameterized Constructor:
JAVA 19
public class Example {
private int value;
// Parameterized constructor
public Example(int value) {
[Link] = value;
}
No-Argument Constructor
Used when you want to perform some initialization that doesn't require
parameters.
Copy Constructor
JAVA 20
public class Example {
private int value;
// Parameterized constructor
public Example(int value) {
[Link] = value;
}
// Copy constructor
public Example(Example example) {
[Link] = [Link];
}
JAVA 21
Final Keyword
Final keyword is used to put a restriction on the variable, method or class to
prevent it from being changed or modified or overridden once declared or
defined.
When applied it puts the constraints on its usage.
1. Final Variables:
2. Final Methods:
JAVA 22
b. Often used to prevent the preserve the specific behavior from being
changed.
c. Subclass can still inherit and use the final methods but cannot provide a
different implementation.
3. Final Classes:
String
It is an object that represent a collection or series of characters.
They are used to store and manipulate the text based data.
They are immutable i.e. once created will not be able to change the value of
string.
Java provides a built-in function for the string creation called ‘[Link]’.
Any operation that appears on the string will result in the new string rather than
modified string.
Stirng greet="Hello";
String name= new String("John");
String emptyString="";
String nullString=null;
2. Concatenation
String first="John"
String second="Oak"
JAVA 23
String fullName= first + " " + second
Inheritance
In inheritance a class (subclass) can inherit behavior and properties of already
existing classes.
In this a subclass that extends a superclass can inherit its attributes and adding
new ones or modifying the existing.
The inheritance in java is achieved by the keyword “extends”.
2. Abstraction
6. Method overriding
Types of inheritance
1. Single Inheritance
b. All classes implicitly inherit from the ‘Object class’ , which serves as a
root of the class hierarchy.
2. Multiple Inheritance
JAVA 24
a. Java does not support multiple inheritance of classes, which means a
class cannot directly inherit from more than one class.
3. Multilevel inheritance
b. A class “C” extends class “B” which in turn extends class “A”.
4. Hierarchical Inheritance
Superclass VS Subclass
Method Overriding
JAVA 25
Method overriding in java is allows the subclass to inherit the superclass
properties and implement them.
In this the subclass can modify, or add its own operations. It only customize
the behavior of the inherited methos.
It redefines the superclass with same name, return type and parameters.
Why?
5. Consistency: When the object is called it should act consistently with the
method contract defined in the superclass.
6.
class Animal{
public void makeSound(){
[Link]("Some generic sound");
}
}
Method Overloading
These are used to define multiple methods with the same name in the class.
They can differ in the parameter name, data type or number.
JAVA 26
When a method is called the java compiler determines which methods to be
executed based on their parameter or arguments in the method call.
Role
1. Improved code readability: Overloading methods have the same name
making it east to understand and read.
2. Flexibility: Help you to define the methods with same name having distinct
input data without changing the name of the method.
Encapsulation
Encapsulation is used to group different methods that operate on a data under
a single class.
It helps to hide the internal implementation detail of the class.
It provide controlled access to the data by using the access modifiers such as
‘private’, ‘protected’ and ‘public’.
Advantages
1. Data security
JAVA 27
2. Controlled access
3. Code flexibility
4. Enhanced maintenance
5. improved testing
6. simplified maintenance
7. Reusability
class Student{
private String name;
private age;
public String getName(){
return name;
}
public void String setName(String name){
[Link]=name;
}
public int getAge(){
return age;
}
public void setAge(int age){
if(age>=0 && age<=120){
[Link]=age;}
}
}
// This code encapsulate the name and age field by keeping it private and prov
// controlled access to them through getter and Setter method.
// It Infosys data validation rules for age and hides the internal implementation
// details of the student class
Polymorphism
It refers to the ability of different objects to respond to a same method
appropriately for their specific types.
JAVA 28
It allows objects of different class to be treated as the object from common
superclass.
Abstraction
Abstraction helps in breaking down complex system into smaller systems, into
more manageable parts while hiding the unnecessary details.
It one of the four main principle of the OOP’S in java.
It allows to focus on the essential characteristic and behaviors of objects while
ignoring the less important or unnecessary details or aspects.
It allows you to define common interfaces with common behavior and hide
implementation details, making it easier to understand and work with.
Key Aspects
1. Abstraction classes and interface
5. Reducing complexity
Abstract classes
Abstract class cannot be directly instantiated but serves as a blueprint for other
classes.
JAVA 29
These classes define common methods and fields that should be shared
among the subclasses and allowing them to provide specific implementations
for some or for all abstract classes.
These classes are the way to implement abstraction in the java and they play a
central role in creating a hierarchy of the classes with shared characteristics.
Purpose
2. Inheritance: Can inherit from both abstract method and concrete method.
4. Polymorphism: i.e. we can use reference to the abstract class type to work
with instances of its concrete subclasses.
Packages
JAVA 30
Packages are the collection of classes, interfaces and sub packages.
It is a way to organize classes, interfaces and sub packages.
It provides a mechanism of related type together, making it easier to manage a
large codebase.
Benefits of Package
1. Code Reusability: We can use the code again and again in different
projects without defining them each time from the package.
JAVA 31
3. Code organization: It organize the related code or classes, interfaces and
sub-packages together, making it easier to locate and manage code files.
CLASSPATH
This is a configuration in java that specifies where the JVM compiler should
look for classes and resources.
It’s crucial for enabling the JVM to locate and load the classes and resources
and libraries when running java applications.
Proper CLASSPATH management is essential for java development, ensuring
the necessary dependencies are available to your programs.
2. NoClassDefFoundError
JAVA 32
JAR : Java Archive files
These are compressed java files used to package java classes, associated
metadata and resources into a single file. JAR files are commonly used for
distributing java libraries, applications and applets.
2. CLASSPATH management
3. Modularity
5. Security
7. Version control
Import Statement
Import statement is followed by the fully qualified name of the package that we
want to import. The syntax is as follows:
import [Link].*;
The use of “ * ” wildcard character to import all classes and interfaces from a
specific package making them available for use in your code.
import [Link];
JAVA 33
They import all classes and interfaces from a package you can use the *
wildcard character.
They should appear at the top of the file after the package declaration if
present and before the class declaration.
Purpose of import
the purpose of the imposed statement is to simplify and clarify Java code.
It allows you to reference classes and interfaces from other packages using
their simple names making a code more readable and reducing the need for
fully qualified class name.
It also promotes court reusability by align you to integrate external classes and
libraries seamlessly into your project.
Exception Handling
Exception
Exception is a event that disrupts the normal flow of the program execution.
Java handles the exception through combination of try, catch and finally
blocks.
Statements that we want to monitor stay in the try block.
JAVA 34
If the exception occur in the try it will be thrown.
The code will catch the error in the catch block and handle it.
Any code that must be run even when the error occur is in the finaly block.
try{
// statement may catch the error;
}
catch(ExceptionType e){
// handle the exception
}
finally{
// code that must be run regardless of the occurence of the error/exception
}
Exception VS Error
Nature of
Usually recoverable and handled Severe, often unrecoverable
Occurrence
Types of exception
Checked Exception
These are the type of exception that are checked by the compiler at compile-
time.
The compiler ensures that these type of error either get caught or thrown using
throw clause.
Example of checked exception are FileNotFoundException,
ClallNotFoundException.
JAVA 35
These exceptions usually represent conditions that a well-behaved application
should anticipate and recover them.
Unchecked Exception
These exception are not checked by the compiler during the compile time.
Instead they occur at runtime and are typically caused by programming error.
Examples are ArrayOutOfBoundException, ArithmeticException.
These exception indicated programming errors that could have been avoided
with proper coding practices.
2. Exception thrown
5. Exception Handling
6. Program execution
Try Block
This block encloses the code that might throw an exception.
JAVA 36
It is used to define a block a code where exception might occur.
try{
// code that might arise a exception
}
The try block must be followed by either catch block, a finally block or both of
them.
Catch Block
This block specify the exception and handle it.
This block follows the try block and handle the exception that occur within the
try block.
If the exception occurs in the try block java searches for the matching catch
block.
catch(ExceptioType e){
// hanldes it
}
Multiple catch block can follow the single try block to handle different types of
exceptions.
Finally block
The finally block follows after try-catch block and contains code that always
executes regardless of whether an exception occurred or not.
It is used for releasing resources, performing cleanup operations of finalizing
the task.
The finally block executes even if the exception is thrown or caught, allowing
for essential cleanup actions.
finally{
// code that must be executed for performing cleanup operations and for
JAVA 37
// releasin the resources aor finalizing the task.
}
This block is optional, but if it used, it must follow the last catch block(if any).
Throw
Throw keyword is used to explicitly throw an exception within the method.
It allows the developers to create and throw their own exception or to re-throw
exceptions that were caught earlier.
Throw statement is typically used when a method encounters an exception and
it cannot be resolved itself.
throw throwableObject;
JAVA 38
// otherwise perform the division
return dividend/divisor;
}
}
}
Throws
The throws keyword is used to indicate that the method may throw an
exception during the execution.
It is part of the method signature and provide information to the caller about the
type of exceptions that the method might throw.
This helps in informing the caller about the potential exception that need to be
handled.
1. Informing callers: It informs the caller about the type of exception that
might occur. It helps informing the caller about the potential exceptions that
need to be handled during the execution process.
Inbuilt Exceptions
These exception are provided by the java standard library.
These are typically organized in hierarchy of exception classes, with base class
being [Link]
JAVA 39
User defined exception are exceptions that are defined by the user or the
programmer.
These exception provide better method to resolve an exception by allowing
developers to create more specific and meaningful methods to handle the
exceptions/error.
Developer can define its own exception classes by extending the the base
exception class provided by the java language.
class MyCustomException{
// constructor that takes a message as parameter
public MyCustomException(String message){
// call the constructor of the superclass exception with the message
super(message);
}
}
Byte Stream
In java byte streams are streams of raw bytes.
JAVA 40
It is used to input/output operations on binary data such as video, audio,
images or any non-textual data.
Byte streams are suitable for reading and writing raw bytes and making them
efficient for handling binary data.
3. FileInputStream: This is used to read the data from the file as a stream of
bytes.
2. Write data:
JAVA 41
b. This releases any system resources that are associated with it and
ensure that the data is flushed in the file.
import [Link];
import [Link];
a. Create a FileInputStream:
b. This class represents the input stream for reading raw bites from them.
b. Read Data:
a. Use the read() method of the FileInputStream to read the bytes from the
file.
JAVA 42
a. After reading the data it is essential to close FileInputStream using the
close() method .
import [Link];
import [Link];
Character streams
This is used to perform I/O operations on characters or text data.
Character streams deals with characters instead of the raw bytes.
These are designed to handle Unicode characters efficiently.
These provide a convenient mean of reading and writing in a text data in
various characters encoding.
JAVA 43
b. Writer: It is also an abstract class a superclass of all the classes
representing an output streams of characters it is used for writing
characters to the destination.
c. FileReader: It is the class that is used to read the data from the file as a
stream of character.
d. FileWriter: It is a class that is used to write the data to the file as a stream
of characters.
e. BufferedReader: This class reads the text from the character input streams
,buffering characters to provide efficient reading of the characters arrays
and lines.
Thread
Threads are the light weighted process that exists within a larger process in
JVM and it operates independently.
Threads allows concurrent execution of multiple process within a single
application,
It enables developers to perform multiple operations simultaneously.
Significance of thread
1. Concurrency: Thread enable concurrent execution of the operation or task
within the java application.
JAVA 44
6. Resource Sharing: Thread can share the resources and memory files within
the same process.
2. Waiting state: Sometimes a thread enters the waiting state while it waits for
the other process to complete its task. A waiting thread transient back to
the runnable state once the previous thread has completed its task.
3. TimedWaiting State: A thread can enter the timed waiting state for a
specified interval of time. Timed Waiting and waiting thread cannot access
the processor even it one is available.
5. Terminated State: When the thread executes all the process and it is
successfully completed its task it enters termination state also known as
dead state. A process can also get terminated if an error is encountered.
JAVA 45
Ways to create a thread
1. Extending the thread class:
a. You can create a class that extends the thread class and overrides the
run() method.
b. The run() method contains the code that will be executed in the new
thread.;
a. You can create a class that implements the runnable interface and
overrides the run() method.
JAVA 46
}
}
Inheritance Extends the thread class Does not extend any class
Inter-thread Communication
It is a process of exchanging the information and coordinating between multiple
thread in a multi-threaded application.
It allows to synchronized year activities share data and execution in a controlled
manner.
This is essential for building concurrent programs where threads will work
together to reach or achieve the result efficiently.
In Java inter threat communication is typically achieved by some fundamental
methods provided by object class: wait(), notify() and notifyAll().
These methods enable thread to wait for a certain condition to be met and then
notify all other threads when those conditions are satisfied.
Functional Interfaces
Functional Interfaces in java are interfaces that contain only one abstract
method.
JAVA 47
These are key features in the java that support functional programming
paradigms.
These are often used to represent functions or actions allowing them to be
passed around as a parameter or return a method.
The predefined interfaces provide common functional constructs.
And these predefined interfaces are extensively used in conjunction with
lambda expression and the Stream API.
Lambda Expression
Lambda expression in java are used for defining anonymous functions(without
name).
Lambda expression are similar to the methods but they do not need a name and
can be implemented right in the body of the method.
The Lambda expression is used to provide an implementation of an interfaces
which has functional interface.
Lambda functions are particularly useful when you need to pass the behavior
or code as an argument of method.
They are a key features introduced in Java 8 for supporting the functional
programming style.
(argument-list)->{body}
b. Arrow token: which is used to link an argument list with the body of
expression.
JAVA 48
// lambda expression using Stream API
List<Integer> numbers=[Link](1,2,3,4,5,6);
List<Integer> evenNumbers=[Link]().filter(num->num%2==0).collec
interface MyFunction{
void performAction(String message);
}
public class Main{
public static void main(String [] srgs){
MyFunction myFunction =(String message)->{
[Link]("Message : "+ message);
}
[Link]("Hello Lmbda");
}
}
JAVA 49
Method references
Method references in Java provides a shorthand syntax for writing lambda
expression that call a single method.
They allow you to refer to methods or constructor without invoking them.
They provide more concise and readable alternative to Lambda expression.
[Link](number->{[Link](number));
[Link]([Link]::println);
List<String> upperCase=[Link]()
.map(string->[Link]())
.collect([Link]());
List<String> upperCase=[Link]()
.map(String::toUpperCase())
.collect([Link]());
[Link]()
.map(number->[Link](number))
.for each([Link]::println);
[Link]()
.map(number->Math::sqrt)
.for each([Link]::println);
JAVA 50
4. Simplified constructor invocation: Method reference can simplify the
instantiation of object by referencing constructors directly animating the
need of land expression to call constructors.
Supplier<List<String>>listSupplier=()->new Array<>();
Supplier<List<String>>listSupplier=ArrayList::new;
Return values each case return statement each case must return a value
Type Annotation
Type annotation other type of the annotation in Java that allows the developer
to apply annotation to various types in addition to just declaration.
These type of annotation provides the additional metadata about types which
can be used by tools and frameworks.
These type of annotation can be applied to a wide range of program elements.
Roles of type annotation :
JAVA 51
compile time and runtime checks.
Repeating Annotations
Repeating an annotation that is introduced in Java 8 allows multiple instances
of the same annotation to be applied in a single program element.
Each annotation could only be applied once to a given element which limit their
flexibility in certain scenarios.
Yield Keyword
The yield keyword in Java is used within the switch expression to specify the
data or value that has to be returned from the case.
It indicates result of evaluating a particular case and terminates the execution
of the switch expression.
It can only be used within the switch expression and it is not valid in any other
context in Java.
It is specially designed to work with the switch expression to provide a concise
way to return the values.
int dayNum=3;
String dayNum=switch(dayNum){
case 1-> "Monday";
JAVA 52
case 2-> "Tuesday";
case 3-> "Wednesday";
case 4-> "Thursday";
case 5-> "Friday";
case 6-> "Satday";
case 7-> "Sunday";
default->{
yield "Invalid day";
}
};
In this example the eat keyword is used within the default case to return the
value invalid day.
Switch expression terminates the yield statement with the value is assigned to
the variable dayNum.
Sealed classes
So sealed classes pro ride a way to restrict which class can be a class of a
particular class or a interface
They allow you to define a finite set of class That are Permitted to extend or
implement a sealed class or interface.
Sealed classes in Java provider powerful mechanism to control the inheritance
hierarchy enhancing the encapsulation and improving the API design.
They promote stronger type safety better code organization and easy and
maintenance of complex class hierarchies.
Collection
In Java collection refers to the framework provided in the Java api for manage
and manipulating the group of objects.
These objects are commonly refers to elements or items.
JAVA 53
it allows developer to easily store retrieve manage manipulate and iterate the
elements in the collection.
Key feature of collections:
JAVA 54
5. Scalability: the framework supports scalable data structure enabling
developers to handle large data set efficiency.
Iterator interface
Iterator interface is the root interface of the entire collection framework.
Iterator interface is used to iterate over the elements of the collections.
Iterator interface also provides a uniform way to access the elements in the
collection types without exposing the underlying implementation details.
Purpose of the iterator interface:
3. Safe removal: iterators supports safe removal of the elements from the
collection during the iteration this prevent concurrent modification
exception.
4. Enhanced for loop support: the iterator interface is utilized implicitly in the
enhanced for loop syntax
Collection Interface
in Java collection interface is the root of collection framework hierarchy .
It represents a group of objects known as elements and provide a unified way
to work with the collections of objects in Java.
The collection interface provides a set of operations that can be operated on
the objects of the collection regardless of their specific implementation.
Collection interface It does not specify any particular ordering of the element.
The collection interface allows the Duplicate elements.
JAVA 55
The collection interface is a fundamental building block of the collection
framework which provides the method to work with the collection of objects in
Java.
It also provides a set of common operations to operate the collection of objects
in Java across different type of collections.
List Interface
Listen to face is the child of collection interface i.e. It is the child in the face of
the collection interface.
This interface is dedicated to the data type of the list type in which we can
store all the ordered collections of the object
This also allows the duplicate data to be present in it. This list interface is
implemented by various classes like ArrayList, vector, stack etc.
Since all the classes implement the list we can instantiate a list object with any
of these classes.
Key Characteristic:
1. Ordered Collection: lists maintain the order of elements in which they are
inserted
2. Indexed access: List elements in the list can be accessed by their index.
3. Dynamic size: List are resizable meaning they can grow or shrink on
dynamically.
4. Iterate: List implements the iterator interface which means they can be
traversed using iterators.
ArrayList
1. Implementation: ArrayList Is a dynamic array based implementation of the
list interface.
2. Data structure: it In deadly uses an array to store the elements which allow
for the fast random access and retrieval of the elements by their index.
JAVA 56
3. Performance: analyst provides over O(1) time complexity for adding or
retrieving elements by index however inserting or deleting elements in the
middle of the list can be slower due to the need to shift elements.
4. Use case: this is suitable for the scenarios where random access in
retrieval of elements are frequent and the list size is expected to be change
over time.
LinkedList
1. Implementation: linked list is a doubly linked list based implementation of
the list interface.
4. Use case: linked list suitable for the scenarios where frequent insertion and
deletion of elements is required specially at the beginning and the end of
the list.
Vector
1. Implementation: Vector is a synchronized dynamic array based
implementation of the list interface.
4. Use case: Vector is suitable for scenarios where thread safety is the
concern and multiple thread need to access or modify the list concurrently.
JAVA 57
Stack
1. Implementation: Stack is a subclass of vector and represents a last in last
out stack data structure
4. Use case: Stack is suitable for implementing algorithm and application that
requires last and first out behavior such as expression evaluation
backtracking and undo mechanism.
Queue Interface
Queue interface in Java represent the collection of elements that follows the
first and first out principle
The queue interface extends the collection interface and add specific methods
for adding removing and inspecting the elements in the queue
Key Characteristics of the queue interface:
1. First and first out ordering: elements are inserted at the end of the queue
and they are removed from the front maintaining the order in which they
were added.
2. Adding and removing elements: provides the method for adding the
elements to the end of the queue offer() add() and removing elements from
the front poll() remove().
3. Peeking: allows accessing the elements from the front of the queue without
removing it peek().
1. Linked list class implements queue interface and provides w linked list
based implementation of the queue.
2. Priority Queue: class implements the queue interface using a priority heap.
3. Array dequeue array deque class implements the dequeue interface which
extends the queue interface.
JAVA 58
Set Interface
Set interface in java represent a collection of unique elements.
It doesn’t contain the duplicate elements.
It has no two elements in the set can be same or equal according to the equal()
method.
Also they do not maintain the insertion order of elements.
1. Uniqueness: No element can repeat more than once that means there will
be no duplicate element
3. Equality: Elements in a set are compared for equality using the equal()
method
4. No index: Set do not support index based access to elements elements can
only be accessed through the iteration or specific search operation.
1. Hash set: It is widely used implementation of the set interface that stores
the element in a hash table.
2. Tree set: Treeset is an implementation of the set interface that stores the
element in a sorted tree structure
3. Linked hash set: Lindh has set is an implementation of the set interface that
maintains the insertion order of elements in addition to ensuring the
uniqueness it achieved this by using a hash table and a linked list.
HashSet
Hashtag is the implementation of the set interface that stores the element in the
hash table form.
It forms or provides constant time average cage performance for basic
operation like add remove and contains making it efficient for handling large
databases.
Hashtag does not guarantee the order of the elements that are being inserted in
it and it does not maintain the insertion order.
JAVA 59
1. Uniqueness: No element in the hashed occurred more than once that
means there is no duplicate element present in the hash table collection
3. No ordering: Elements in the hash table are not shorted in any particular
manner.
1. Uniqueness: No element in the linked hash set occurred more than once
that means there is no duplicate element present in the hash table
collection
2. Efficient Lookup: hash table provides fast lookup operation due to its
underlying hash table implementation.
3. Predictable iteration order: Unlike hash set, linked hash set ensures
Guarantee that element will be iterated over in order as they were inserted.
JAVA 60
It is commonly used in the scenario where sorted collections are required such
as maintaining the sorted dictionaries shorted list or implementing algorithms
that require sorted data.
2. uniqueness Like others set implementation sorted set does not allow
duplicate elements
4. no index based access Unlike list implementation sorted set does not
support index based accessing of the elements we have to iterate to the
particular element we want
Tree Set
Trees set in is a class in Java that implements sorted set interface providing a
sorted collection of unique elements.
It used red black tree data structure to maintain elements in sorted order.
Tree set provides a convenient and efficient way to work with the sorted
collection in sorted order.
It is commonly used in scenario where elements need to be sorted and
accessed in sorted order.
2. Unique elements: Like others set implementation tree set does not allow
duplicate elements.
5. Use of red black tree: internally to reset user red black tree data structure
to maintain elements in sorted order.
Map interface
JAVA 61
The map interfaces in Java presents a collection of key value pair where each
case associated with the corresponding value.
It provides a way to store and retrieve elements based on their keys.
The value of the key does not repeat that means there will be only one value
associated with one key.
The map interfaces provides an efficient retrieval and manipulation of the
values based on their keys.
This makes maps suitable for scenarios where quick access to value based on
the unique identifiers is required.
2. Uniqueness of keys
3. No ordering
4. Efficient retrieval
3. Ordering: Hash map does not guarantee any specific order of elements the
order of elements may change over the time as elements were added or
removed from the map.
JAVA 62
Retrieval of the elements with slightly higher memory overhead due to
maintaining the linked list.
JAVA 63
Sorting
Using comparable interface
Many classes in Java such as string integer and other wrapper classes
implement the comparable interface.
This interface defines some method compareTo() that specifies the natural
ordering of the objects.
To sort a collection of objects that implement comparable you can use methods
provided by the collection utility class.
This method sorts the element of the specified list in ascending order
according to their natural ordering.
JAVA 64
Sorting Arrays
Java also provides utility methods for sorting arrays.
the array's class contained overload version of sort method.
It accepts array of different type such as sort(int [] a) for sorting arrays of
integer and sort(object[] a) or sorting errors of object that intimate
comparable.
Comparable interface
So the comparable interface in Java collection framework is used to define the
natural ordering of the object.
It provides a way for object to specify how they should be compared to when
another for the purpose of sorting.
Classes that implement comparable can be sorted into the natural order using
utility method provided by the collection framework.
It consists of single method called compareTo() which takes another object of
the same type as an argument and returns an integer value indicating the
comparison result.
Uses:
Comparator Interface
the comparator interface in Java collection framework is used to define custom
ordering of the objects.
JAVA 65
the comparator interface is a part of Java utility package.
The Comparator interface allows for the definition of multiple comparison
strategies for a given class
It defines simple method or we can see a single method called compare()
which compared two objects and returns an integer indicating the comparison
result.
The comparator interface provides powerful mechanism for defining custom
sorting strategies.
It allows for flexible and customizable sorting based on different criteria
enhancing the functionality and versatility of the collection framework.
Property class
The property class in Java collection framework is a subclass of hash table and
represent a persistent set of properties where each poverty consists of a key
value pair.
It is commonly used for handling configurations I think such as application
settings or parameters will key value pair assaulted in text file.
Purpose:
JAVA 66
b. It provides convenient way to store and retrieve the configuration settings
such as database collection parameters application settings or system
properties.
Usage:
Spring core
Spring is a lightweight framework it can be thought as a framework of
frameworks because it provide support to many frameworks.
The framework can be defined as a structure where we find the solution for the
various technical problems.
The string framework comprises of several modules such as APOP IOC.
3. Easy to test: The dependency injections make easier to test the application
the EJB requires server to run the application but spring framework does
not require the server.
Spring Framework
JAVA 67
Spring framework is an open source Java framework that provides
comprehensive support for building enterprise level application.
it offers a lightweight and modular approach to develop robust scalable and
maintainable applications.
The spring framework focuses on the concept of dependency injection and
inversion of control.
4. Spring MVC: Spring MBC is a web based framework build on top of the
spring framework providing a robust and flexible architecture
Dependency Injection
Dependency injection is a design pattern that removes the dependency from
the programming port so that it can be easily managed and it would be easy to
test the application.
Dependency injections makes our programming code couple loosely coupled.
JAVA 68
configuration file. the setter dependency injection is being declared under
the bean configuration file.
Inversion of control
Spring inversion of control container is the core spring framework
It is used to create the objects configures and assemble their dependency and
manage their life cycle
JAVA 69
The container uses dependency injections to manage the component that
makes up the application.
It gets the information about the object from the configuration file or Java code
or Java annotation and Java POJO Glass these objects are called beans.
since the controlling of Java objects and their life cycle is not done by the
developers hence the name inversion of control.
Beans
beans in spring is an object that is managed by the spring inversion of control
container.
It is the core component of the spring framework and it represents the building
block of an application.
Beans in spring are instantiated assembled and they are managed by the
container.
Bees provide various benefits such as dependency injection aspect of oriented
programming and modularity.
The life cycle of bean in spring consist of several phases including bean
instantiation initialization uses and destruction.
JAVA 70
Spring provide mechanism to customize life cycle of the bean.
JAVA 71
conventions.
Spring Framework
Definition: Spring is a comprehensive framework for enterprise Java
development. It provides a wide range of features for building robust and
scalable applications, including dependency injection, aspect-oriented
programming, and transaction management.
Features:
Spring Boot
Definition: Spring Boot is a project within the Spring ecosystem that simplifies
the process of developing and deploying Spring applications. It provides a set
of conventions and defaults that streamline the setup and configuration of
Spring applications.
Features:
JAVA 72
without requiring a separate server installation.
Key Differences
Aspect Spring Spring Boot
Auto-configures based on
Requires extensive manual
Configuration dependencies and
configuration.
conventions.
JAVA 73
💡 Spring Framework: Provides a comprehensive infrastructure for
building Java applications. It offers extensive features but requires
significant configuration and setup.
Spring Boot: Builds on top of Spring, providing an easier and more
efficient way to develop and deploy Spring applications. It
emphasizes convention over configuration, auto-configuration, and
embedded servers, making it faster and simpler to get applications up
and running.
Spring Boot is essentially a way to simplify the development process
and reduce the complexity associated with using the Spring
Framework directly.
Spring Runners
In Spring,
runners are components that execute code at specific points during the
application lifecycle. They are used to perform tasks when the Spring
application context is fully initialized. There are several types of runners in
Spring that you can use to execute code before or after the application starts.
2. ApplicationRunner
3. SpringApplicationRunListener
4. @PostConstruct
JAVA 74
@PostConstruct : Executes initialization code after the bean's dependencies
are injected and the bean is ready.
1. CommandLineRunner
Definition: CommandLineRunner is an interface that allows you to run specific code
after the Spring Boot application has started. It provides a run method that
takes command-line arguments.
Usage:
2. ApplicationRunner
Definition: ApplicationRunner is an interface similar to CommandLineRunner , but it
provides access to ApplicationArguments , which gives a richer way to handle
command-line arguments.
Usage:
3. SpringApplicationRunListener
Definition: SpringApplicationRunListener is an interface that provides hooks into the
application startup process. It allows you to listen to various events during the
application's lifecycle.
Usage:
4. @PostConstruct
JAVA 75
Definition: @PostConstruct is an annotation provided by the [Link] package.
It marks a method to be executed after dependency injection is done and the
bean is fully initialized.
Usage:
Useful for initializing resources or performing tasks once the bean is fully
constructed and dependencies are injected.
Diamond Problem
The diamond problem occurs when a class inherits from two classes that both
inherit from the same superclass. This creates ambiguity about which
superclass method the subclass should inherit.
Complexity
Allowing multiple inheritance increases the complexity of the language, making
it harder to read, understand, and maintain the code. It also complicates the
compiler and runtime environment.
interface A {
void displayA();
}
interface B {
JAVA 76
void displayB();
}
class C implements A, B {
@Override
public void displayA() {
[Link]("Display from interface A");
}
@Override
public void displayB() {
[Link]("Display from interface B");
}
}
POJO class
Plain old Java object
It is a class in Java and it is a simple class that is used to represent the data
It is a standard Java object that does not have any special restrictions other
than those forced by the Java language itself
these are commonly used for modeling the real world objects are for
transferring the data in the application
JAVA 77
No special requirement a class is not bound by any special framework or
libraries
no specific annotation that means it does not require any annotation unless
needed to specify purpose
encapsulation fields are typically private and accessed via public cater and
settle methods
no inheritance from special classes these do not need to extend or implement
any special classes or interfaces
// Parameterized constructor
public Student(String name, int age, String course) {
[Link] = name;
[Link] = age;
[Link] = course;
}
JAVA 78
}
Benefits of Pojo:
Simplicity these are simple To write and maintain
Reusability they can be used across different layers of an application without
dependency on a specific framework
and flexibility they are flexible and can be modified easily
these are commonly used in Java for supporting or representing the data
models specially in frameworks where they are mapped to database tables are
transferred as data between layers of application.
JAVA 79