0% found this document useful (0 votes)
2 views79 pages

Java Theory Notes

Java is an object-oriented programming language developed by Sun Microsystems in 1991, emphasizing concepts like encapsulation, inheritance, and polymorphism. The Java Virtual Machine (JVM) allows Java to be platform-independent by executing bytecode generated from Java source code. The Java Development Kit (JDK) includes tools for development, while the Java Runtime Environment (JRE) is necessary for running Java applications.

Uploaded by

StealthHelper
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views79 pages

Java Theory Notes

Java is an object-oriented programming language developed by Sun Microsystems in 1991, emphasizing concepts like encapsulation, inheritance, and polymorphism. The Java Virtual Machine (JVM) allows Java to be platform-independent by executing bytecode generated from Java source code. The Java Development Kit (JDK) includes tools for development, while the Java Runtime Environment (JRE) is necessary for running Java applications.

Uploaded by

StealthHelper
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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:

Encapsulation : Encapsulation is Java is a Process of wrapping a data and


code together into a single unit.

Inheritance : Inheritance in Java is a mechanism in which one object


acquires all the properties and behavior of its parent object.

Information Hiding

Polymorphism : It refers to programming lang ability to process the objects


depending on their classes.

Java Virtual Machine (JVM) 🤖


The JVM is generally referred to as JVM. To understand the JVM, let's first see
the phases of program execution:

Writing of the program: done by the Java programmer

Compilation of the program: done by the javac compiler, which generates


Java bytecode as output

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.

Java Development Kit (JDK) 📚


The JDK is a complete Java development kit that includes:

JRE (Java Runtime Environment)

compilers

various tools like JavaDoc, Java debugger, etc.

To create, compile, and run a Java program, you need JDK installed on your
computer.

Java Runtime Environment (JRE) 🌐


The JRE is a part of the JDK that includes:

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.

Main Features of Java 🌈


A. Platform Independent Language
Compiler (javac) converts source code (.java file) to bytecode (.class file)

JVM executes the bytecode produced by the compiler

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

Explicit memory allocation

D. Robust
Java is a robust language that emphasizes early checking for possible
errors

Features that make Java robust:

Garbage collection

Exception Handling

Memory allocation

E. Secure
Java does not have pointers

You cannot access out-of-bound arrays (you get


ArrayIndexOutOfBoundsException if you try to do so)

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:

RMI (Remote Method Invocation)

EJB (Enterprise Java Beans)

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

The platform-independent bytecode can be carried to any platform for


execution, making Java code portable

Java Virtual Machine (JVM) Architecture 📈


The JVM architecture consists of:

Component Description

Class Loader Reads [Link] file and saves the bytecode in the method area

Method Area Holds the class-level information of [Link] file

Heap Part of JVM memory where objects are allocated

Stack Part of JVM memory used for storing temporary variables

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.

Contains JVM, class


Includes everything
libraries, and other
in JRE, along with
files (excluding
development tools
development tools)

Java development Java runtime


Full Form Java virtual Machine
kit environment

for java app


development
for running
Purpose including for executing bytecode
application
compilation and
debugging

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

Compiling and Running Your First Java Program 🎉


Simple Java Program:
public class FirstJavaProgram {
public static void main(String[] args) {
[Link]("This is my first program in Java");

JAVA 6
}
}

Output:

This is my first program in Java

How to Compile and Run the Program:


1. Open a text editor and copy the above program.

2. Save the file as [Link] .

3. Compile the program using the command javac [Link] .

4. Run the program using the command java FirstJavaProgram .

Setting up Java Environment 💻


Setting Path in Windows
To set the path in Windows, follow these steps:

Open the Command Prompt (cmd)

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

Note: Your JDK version may be different.

Setting Path in Mac OS X


To set the path in Mac OS X, follow these steps:

Open the Terminal

Type the following command and hit return: export JAVA_HOME=/Library/Java/Home

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.

Compiling and Running Java Programs

Step 4: Compiling and Running the Program


After compilation, the .java file gets translated into the .class file (byte code).
Now we can run the program. To run the program, type the following command
and hit enter: java FirstJavaProgram
Note: You should not append the .java extension to the file name while running
the program.

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

public class FirstJavaProgram { ... }

Definition: Every Java application must have at least one


class definition that consists of the class keyword followed
by the class name. When I say keyword, it means that it
should not be changed, we should use it as it is.

Classes are the blueprints or templates for creating an object.


They define attributes (data) and methods (behavior) that object of a class
will exhibit.

1. Definition 2. Attributes 3. Methods 4. Access Modifiers

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.

Helps in encapsulation and provide a way to hide the internal


implementation of the class details.

Important for the integrity and security of the program.

Public

accessible from any class or package

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

Can only be accessed within same class

they’re not visible from other classes and not even from subclasses

They have the restricted visibility

Default

it can only be accessible by the content or classes in the package.

package level visibility

Feature Class Object

Definition a class is a blueprint instance of a class

Purpose Define structure and behavior represent specific entity

Instantiation not instantiation itself created from the class

Multiple instance multiple object from a class different instances with own data

Methods define behavior calls the method for action

Static member can have has no

JAVA 10
Feature Class Object

Can be inherited by other


Inheritance inherits properties and behavior
classes

Usage provide structure for object represent specific instances

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

a. Static variable are declared using the static keyword.

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

a. Also declared using the static keyword.

b. They can not access the instance specific data (non static members)
because they do no have access to the “this”.

c. They can only access the other static data.

d. They are invoked by using the class name followed by dot(.) operator.

Characteristic of static members


1. Loaded in the memory when the class is loaded.

2. Have only 1 copy in the memory.

3. They can be accessed if no instances of the class is created.

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.

We do not need to create an object for static methods to run. They


static
can run themselves.
void It does not return anything.
main It is the method name.
String[] args Used for command line arguments that are passed as strings.

Printing to the Console


[Link]("This is my first program in java");

Definition: This method prints the contents inside the double


quotes into the console and inserts a newline after.

Write a Java program and compute the sum of an integer's


digits.

import [Link];

public class W01_P2 {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

// Prompt the user to input an integer


[Link]("Input an integer: ");

// Read the integer from the user

JAVA 12
long n = [Link]();

// Calculate and display the sum of the digits


[Link]("The sum of the digits is: " + sumDigits(n));

// Close the scanner


[Link]();
}

// Method to calculate the sum of the digits of a number


public static long sumDigits(long number) {
long sum = 0; // Initialize sum to 0

while (number > 0) {


long digit = number % 10; // Extract the last digit
sum += digit; // Add the digit to the sum
number /= 10; // Remove the last digit
}

return sum; // Return the calculated sum


}
}

OOP’s in JAVA : Objects Oriented


Programming

JAVA 13
Subsets of java lang

Reference Data type: These are the data types that stores reference to
objects.

Primitive data types: directly contains the data.

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.

Blank and comma are not allowed.

JAVA 14
First Character must be an alphabet or underscore.

An identifier can be arbitrary long.

Identifiers should not be a reserved word.

Java is case sensetive language.

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).

Manipulation of the array

Declaration of the array.

<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];

// same for 3D array and so on

Allocate memory for it.

<arrayname>=new<type>[<size>];
x=new int[100];

JAVA 15
// 2D ARRAY
array=new int[3][4];

Loading the values into array.

<type><arrayname>[]={<list of values>};
int x[]={12,56,78};

// 2D Array
int array[][]={{112,3},{4,5},{7789,56}};

2D array with varibale size

<type><arrayname>[][]=new <type>[<row size>][];


for(int i=0;i< <rowsize>;i++){
<arrayname>[i]=new <type>[<colsize>];
}

Encapsulation in JAVA
The object is at the core of java programming.

It provides the concept of class to build objects.

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 template or blueprint from which objects are created.

It is a logical entity.

It contains

Fields

Methods

Constructor

Blocks

Nested classes and interfaces

class <class name>{


<type> <variable 1>;
<type> <variable 2>;
<type> <variable 3>;
<type> <variable n>;

<type> <method 1>(<parameters-list 1>){


body of the method 1;
}
}

There should be a class which contains a method main(). This class is


called main class.

There should be only one main class.

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 allows objects to initialize themselves when they are created/declared.

This automatic initialization is performed through the concept of


constructor.

JAVA 18
Types of constructor
Default Constructor

A constructor that takes no arguments.

If no constructor is defined in a class, the Java compiler automatically


provides a default constructor.

If you define any constructor, the default constructor is not provided.

public class Example {


// Default constructor
public Example() {
[Link]("Default constructor called");
}

public static void main(String[] args) {


Example example = new Example(); // Default constructor is called
}
}

Parameterized Constructor:

A constructor that takes one or more parameters.

Allows you to initialize an object with specific values at the time of


creation.

JAVA 19
public class Example {
private int value;

// Parameterized constructor
public Example(int value) {
[Link] = value;
}

public static void main(String[] args) {


Example example = new Example(10); // Parameterized constructor is
called
}
}

No-Argument Constructor

Similar to the default constructor, but explicitly defined by the


programmer.

Used when you want to perform some initialization that doesn't require
parameters.

public class Example {


// No-arg constructor
public Example() {
[Link]("No-arg constructor called");
}

public static void main(String[] args) {


Example example = new Example(); // No-arg constructor is called
}
}

Copy Constructor

A constructor that creates a new object as a copy of an existing object.

Not provided by default in Java but can be defined by the programmer.

JAVA 20
public class Example {
private int value;

// Parameterized constructor
public Example(int value) {
[Link] = value;
}

// Copy constructor
public Example(Example example) {
[Link] = [Link];
}

public static void main(String[] args) {


Example original = new Example(10); // Parameterized constructor is
Example copy = new Example(original); // Copy constructor is called
}
}

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:

a. It becomes a constant i.e. its value cannot be changed.

b. They must be initialized when declared or within the constructor of the


class if they’re instance variable.

c. They are typically written in upper case

2. Final Methods:

a. Once declared cannot be overridden or modified by the subclasses.

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:

a. When declared it cannot be extended or subclassed by the other


classes.

b. It marks the class as final implementation and it cannot be further


specialized.

c. Used to prevent inheritance and to ensure that the class behavior


remains unchanged.

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.

Creating a string variable


1. Declare and initialize

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

3. Using string method

String org="hello world!"


String subString=[Link](0,5); // creates a new string "hello" from
// the original string

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”.

Importance of inheritance in OOP


1. Code reusability

2. Abstraction

3. Polymorphism: it is a key-factor for achieving polymorphism.

4. Efficiency: eliminated the need of duplicate code require by different


classes.

5. Hierarchy creation: Lets you create a hierarchy class representing is-a


relationship.

6. Method overriding

Types of inheritance
1. Single Inheritance

a. It involves a subclass inheriting from a single superclass.

b. All classes implicitly inherit from the ‘Object class’ , which serves as a
root of the class hierarchy.

c. Therefore, java support single inheritance.

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.

b. However, multiple inheritance can be achieved using interfaces.

c. A class can implement multiple interfaces, effectively inheriting the


method signatures from multiple source.

3. Multilevel inheritance

a. A subclass derives from another subclass creating the chain of


inheritance.

b. A class “C” extends class “B” which in turn extends class “A”.

4. Hierarchical Inheritance

a. In this multiple subclasses inherits from the same superclass.

b. This creates a branching structure where multiple classes share


common featues.

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?

1. Customization: It allows subclass to provide its own implementation.

2. Extensibility: It allows to extend the the class behavior without changing


the existing code.

3. Specialization: Subclasses can specialize the behavior of inherited


methods.

4. Polymorphism: It allows object of different classes to be treated as an


object of common superclass.

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");
}
}

class Dog extends Animal{


@override
public void makeSound(){
[Link]("Bark");
}
}

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.

3. Default values: This can provide default parameters for optional


parameters.

4. Consistency: Maintains the consistency in the method naming helping the


programmer to understand how to use classes and methods.

5. Polymorphism: When combined with method overriding contributes the


concept of polymorphism.

public class Calculator{


public int add(int a,int b){
return a+b;
}

public double add(double a , double b){


return a+b:
}
}

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.

1. Compile time polymorphism: Method Overloading: Occur when the


different methods have same name but different parameters quantity or
name or data type. Java compiler decides which method to call based on
the parameters during compile time. This method executes on the compile
time and its often known as static/early binding.

2. Runtime Polymorphism: Method Overriding: Occur when a subclass


provides a special implementation of the superclass that already exist. This
decision of which method to call is taken during runtime based on the
actual type of object. This allows different subclasses to customize the
behavior of the method and is often referred as dynamic/late binding.

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

2. Hiding implementation details

3. Modeling real-world concepts

4. Reusability and extensibility

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

1. Abstract methods: is to ensure that all subclasses provide their specific


functionality.

2. Inheritance: Can inherit from both abstract method and concrete method.

3. Partial Implementation: avoid redundancy code and enforces consistency


across the hierarchy of related classes.

4. Polymorphism: i.e. we can use reference to the abstract class type to work
with instances of its concrete subclasses.

Feature Abstract Classes Regular classes

Cannot be instantiation Directly Can be instantiated directly


Instantiation
with new with new

Can only contain concrete


Abstract method Can contain abstract method
method

Can only contain concrete


Concrete method Can contain concrete method
method

can be used as both base


Uses in hierarchy
Is used as base class in hierarchy class and leaf class in
method
hierarchy

Contains method with or without Contains method with


Implementation
implementation concrete

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.

It is a essential directory that contains a collection of java files.

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.

2. Namespace Management: It handles the problem of two classes having


same name in different 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.

4. Encapsulation and Abstraction: This supports encapsulation and


abstraction as it groups the different classes, interfaces and sub-packages
together while hiding the implementation details.

5. Modularity: It promotes modularity. This makes the code base easier to


maintain.

6. Access Control: Packages can be controlled or get visible on the basis of


modifiers used like ’public’, ‘protected’, ‘private’.

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.

Purpose for setting the CLASSPATH


a. Locating classes and resources

b. Handling the dependencies

c. Supporting modular development

d. Avoid clashing class name

e. Class loading and resolution

f. Managing dependencies from third party libraries

Consequence of not setting the CLASSPATH


1. ClassNotFoundException

2. NoClassDefFoundError

3. Resource loading issues

4. Library and dependency problem

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.

Roles of JAR in java


1. Packaging classes and resources

2. CLASSPATH management

3. Modularity

4. Reduced file size

5. Security

6. Cross platform compatibility

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.

Importing a single classes


To import a single class or interface specify the package name and the class
name separated by a dot(.) .
For example

import [Link];

Importing entire packages

JAVA 33
They import all classes and interfaces from a package you can use the *
wildcard character.

Multiple import statements


You can have multiple import statements in your Java source file to import
classes and packages from different sources.

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.

It represents an unexpected condition or error that occurs during the runtime.


These can arise due to many reasons such as invalid user input, file not found
or programming mistakes/error.

The fundamental idea behind the exception handling is to provide a mechanism


for dealing with runtime errors in a structured and graceful manner.
Exception handling allows you to anticipate and handle the exception that may
occur in the program.

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

Aspect Exception Error

Parent Class [Link] [Link]

Nature of
Usually recoverable and handled Severe, often unrecoverable
Occurrence

Generally caused by the Caused by external factors


Cause
application’s logic or environment such as JVM or hardware

Can be caught and handled using


Handling Usually not caught or handled
try-catch blocks

Example FileNotFoundException OutOfMemoryError

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.

Aspect Checked Exception Unchecked exception

Need not to be explicitly handled or


Definition Must be caught or declared
declared

Example IOException NullPointerException

Compilation Done during compile time Done during run time

Must be handled with try- Can be handled by the try-catch


Handling
catch or throws clause optionally if necessary

For programming errors or


Purpose For external factors
exceptional clause

Extent the RuntimeException or its


Inheritance Extend Exception class
subclass

Control flow in exception handling


1. Exception occur

2. Exception thrown

3. Search for matching catch blocks

4. Control transfer to the matching catch block

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.

// the syntax for throw is:

throw throwableObject;

Here, “throwableObject” is a subclass of the “Throwable" such as exception or


error.

public class ThrowExample{


public static void main(String [] args){
try{
// call method which will throw an exception
divideByZero();
} catch(ArithemeticException e){
// handle the exception
[Link]("Exception caught:" + [Link]());
}
}

public static void divideByZero(){


int dividend=10;
int dividor=0;
if(divisor==0){
throw new ArithemeticException("Cannot divide by zero")
}
else{

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.

2. Propagation of Exceptions: If a method is not able to handle the exception


on its own then it is propagated further up in the call stack.

3. Compile-time checking: The throws keyword enables compile-time


checking of exception handling. This helps in ensuring that exceptions are
handled appropriately during the compile-time.

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]

a. NullPointerException: This is thrown when a program attempts to access


or manipulate an object reference that has a null value.

b. ArithmeticException: This is thrown when an arithmetic operation such as


division by zero occurs.

User Defined Exception

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.

By raising a user-defined exception, the developers can communicate specific


error handling method by improving code readability and maintainability.
This allows the developer to create the exception based on their specific
requirement of the project.
Additionally it allows the developer to create more granular exception handling.

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);
}
}

Aspect Inbuilt Exception User defined Exception

Definition Provided by the language Defined by the user

Raised No, must be explicitly raised by


Yes, by the interpreter
Automatically the programmer

All exception inherit from Can inherit from Exception or its


Inheritance
BaseException subclasses

For general error handling Tailored for specific error


Usage
across applications scenarios in the application

Example ZeroDivisionError FileNotFoundError

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.

Commonly used byte streams classes:


1. InputStream: Abstract class: It is superclass of all the classes representing
the input bytes streams. It is used for reading bytes from a source.

2. OutputStreams: Abstract class: It is also a superclass representing the


output streams of bytes. It is used for writing bytes in the destination.

3. FileInputStream: This is used to read the data from the file as a stream of
bytes.

4. FileOutputStream: This is used to write the data in the file as a stream of


bytes.

5. ByteArrayInputStream: This is used to read the data from byte array as a


stream of bytes.

6. ByteArrayOutputStream: This is used to write the data to a byte array as a


stream of bytes.

Writing files using byte streams


Writing files using the buy streams in Java involves the use of class such as
FileOutputStream.

1. Create a file output stream:

a. Creating a FileOutputStream object ,using the file path as a parameter.

2. Write data:

a. Use the write() method of the FileOutputStream to write bytes to the


file.

b. We can write bite array individual bytes or portion of byte arrays.

3. Close the Stream:

a. After writing the data, it is essential to close the FileOutputStream using


the close() method.

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];

public class ByteStreamWriteExample{


public static void main(Stirng [] args){
try{
// create a FileOutputStream
FileOutputStream outputStream= new FileOutputStream("[Link]");
// write data to the file
String data="Hello";
byte[] bytes=[Link](); // con convert strings to bite array
[Link](bytes);
// Close the screen stream
[Link]();
}
catch(IOException e){
[Link]();
}

Reading files using byte streams


Reading a file using bite streams in Java involves the use of classes such as
FileInputStream.

a. Create a FileInputStream:

a. Create a file “FileInputStream” stream object passing the file path as a


parameter.

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.

b. We can read byte arrays or individual bytes.

c. Close the Stream:

JAVA 42
a. After reading the data it is essential to close FileInputStream using the
close() method .

b. This releases any system resource associated with it.

import [Link];
import [Link];

public class ByteStreamWriteExample{


public static void main(Stirng [] args){
try{
// create a FileOutputStream
FileOutputStream outputStream= new FileOutputStream("[Link]");
// read data to the file
int data;
while(data=[Link]())!=-1){
[Link]((char)data);// Convert byte to care and print
}
[Link]();
}
catch(IOException e){
[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.

Commonly used character streams classes:


a. Reader: This is an abstract class a superclass of all the classes
representing an input streams of character it is used for reading characters
from the source.

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.

f. BufferedWriter: This class writes text to the character output streams,


buffering characters to provide efficient writing 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.

2. Multitasking: Thread allows the developers to execute multiple operations


simultaneously.

3. Responsiveness: It enabled an application to be responsive even when it is


running a complex or time-consuming task.

4. Parallelism: Thread is use to achieve parallelism, where multiple task can


be executed or operated simultaneously on multi-core processor.

5. Asynchronous programming: It allows asynchronous programming


allowing certain task to execute independently of the main program flow.

JAVA 44
6. Resource Sharing: Thread can share the resources and memory files within
the same process.

Life Cycle of thread


1. New and runnable state: A new thread begins its life cycle in the new state.
It remains in the new state until it enters the runnable state. Once it enters
the runnable state, it start executing the operations. It is considered to be
executing a task.

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.

4. Blocked State: A runnable thread transient to the blocked state when it


attempts to perform the task that requires another task for its completion
and it cannot be executed immediately and it must be temporarily wait until
that task completes.

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.;

class MyThread extends Thread{


public void run(){
[Link]("This is new thread");
}
}
public class Main{
public static void main(Stirng[] args){
MyThread myThread=new MyThread();
[Link]();
}
}

2. Implementing the runnable interface

a. You can create a class that implements the runnable interface and
overrides the run() method.

b. Then we can create instance of a thread and pass an instance of your


class to its constructor.

class MyRunnable implements Runnable{


public void run(){
[Link]("This is new thread");
}
}
public class Main{
public static void main(Stirng[] args){
Thread myThread=new Thread(new MyRunnable());
[Link]();

JAVA 46
}
}

Thread Class VS runnable Interface


Aspects Thread class Runnable interface

Inheritance Extends the thread class Does not extend any class

Directly implements the run Provides run method to be


Implementation
method implemented

Resource Consumes more system Consumes less system


Consumption resource due to inheritance resource as it is an interface

Cannot be shared among Can we shared among multiple


Sharing
multiple threads threads

Encapsulate both the thread Encapsulate only the thread


Encapsulation
logic and thread creation logic

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.

Also known as Single Abstract method(SAM).

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}

Java lambda expression consists of three components:

a. Argument: list it can be empty or non empty as well.

b. Arrow token: which is used to link an argument list with the body of
expression.

c. Body: It contains the expression or statements for lambda expression.

// Simple lambda function


()->[Link]("Hello Lambda !");

// Lambda using functional interface


List<String> names=[Link]("Arjun", "Bhim", "Ram", "Hari");
[Link](names,(String a,String b)->[Link](b));

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

Functional interface relate to Lambda


expression
Functional interface in Java are closely related to Lambda expression because
Lambda expression can only be used with functional interfaces.
Lambda expression enable the creation of instance or functional interfaces
without having explicitly defined class.
Instead they allow you to specify the implementation of a single abstract
method directly in line.
This makes the code more concise and readable.

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");
}
}

In this example my function is a functional interface with a single abstract


method perform action.
We then use Lambda Expressions [Link]("Message : "+ message);
to provide the implementation of the perform action method directly.
This demonstrates how lambda expression enable concise implementation of
functional interface in Java.

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.

1. Readability: Method references provides a clearer and more intuitive


representation of the code intent compared to the Lambda expression
especially when the method being referenced as a descriptive name.

[Link](number->{[Link](number));
[Link]([Link]::println);

2. Elimination of redundant code: Method reference help eliminate the


redundancy by allowing you to directly reference the existing method
instead of rewriting the Similar code in Lambda expression.

List<String> upperCase=[Link]()
.map(string->[Link]())
.collect([Link]());

List<String> upperCase=[Link]()
.map(String::toUpperCase())
.collect([Link]());

3. Improved maintainability: Using method reference can make code easier


to maintain because they explicitly indicate the method being invoked
making it easier for other developers to understand and modify the code.

[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;

Switch Statement VS Switch Expression


Feature Switch expression Switch statements

Switch keyword ,case labels Switch keyboard, → arrow syntax,


Syntax
and case blocks expression based case

Return values each case return statement each case must return a value

Requires break statement to no fall through behavior by default


Use of break
prevent fall through no need for break

Mandatory must be present with a


Default Case Optional can be omitted
value to return

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 :

1. Providing additional type information: type annotation provides additional


meta data information about the type which can be used by the tools and
frameworks to perform various tasks.

2. Custom Annotation: Developers can define custom type of annotation To


express domain specific constraints and requirements.

3. Improved code quality and safety annotation: type annotation help


improve gold quality safety and maintainability by providing additional

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.

Repeating annotation address this limitation by allowing annotation to be


repeated.
Repeating annotation provides more flexible and expressive way to annotate
program elements.
It improves the code readability and maintainability where multiple annotation
of the same type are needed.

1. Declaring repeating annotation: to declare repeating annotation type use


at the @repeatable meta annotation along with the container annotate on
type.

2. Applying repeating annotation: once a repeating annotation type is


declared you can apply it to a program element using its container
annotation.

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";
}
};

[Link]("The day is:"+dayNum);

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.

The collection framework provides a unified architecture for working with


collection of objects.

JAVA 53
it allows developer to easily store retrieve manage manipulate and iterate the
elements in the collection.
Key feature of collections:

1. Unified architecture: the collection framework provides a unified


architecture for representing and manipulating collections.

2. Generic support: most classes and interfaces in the collection framework


support generics align developers to specify the type of elements a
collection can hold.

3. Dynamic resizing: many collection classes automatically resize themselves


as needed to accommodate the addition or removal of elements.

4. Algorithms: the collection flavor includes various utility methods and


algorithm for sorting searching and manipulating the collection efficiently.

5. Iterators: iterators provide a way to traverse the elements of a collection


sequentially enabling easy iteration over the collection items.

Java collection framework


The Java collection framework is the set of classes and interfaces that provide
the implementation of the commonly reusable collection data structures in
Java.
The data structure can be a list array maps queue stack etc.

It provides a unified architecture to manage and manipulate the collection


objects.
Advantages of Java collection framework:

1. Reusable implementation: the framework provides ready to use


implementation of the common data structure saving developers time and
effort.

2. Consistency: all collections in the framework follow a common set of


interfaces and conventions.

3. Efficiency: the framework offers efficient implementation of data structure


Optimized for various use cases.

4. Type safety: Java generics are extensively used in the collection


framework providing compile time safety.

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:

1. Traversal: it allows a sequential access of the elements in the collection a


type without exposing the underlying implementation details.

2. Uniformity: iterator provides a common way to iterate over the different


types of collections this uniformity simplifies the process of iterating
through collection and it promotes code reusability.

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

a. This syntax provides a concise and readable way to iterate over


collections without explicitly dealing with the iterators.

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.

5. Search Operations: list supports search operation to find the index of a


specified element.

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.

2. Data structure: it consists of a sequence of elements where each element


stores a node that contains a reference to the previous and the next
element in the sequence.

3. Performance: linked list provides O(1) time complexity for adding or


removing elements at the beginning or the end of the list however
accessing elements by index required traversing the list resulting in O(n)
time complexity.

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.

2. Data Structure: similar to ArrayList vectors internally using array to store


the elements.

3. Performance: Vectors provide the same performance characteristics as the


ArrayList list however vector insured thread safety by synchronizing
access to its method which can impact the performance of multithreaded
applications or environment.

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

2. Data structure: It supports two main push and pop operations.

3. Performance: Stack inherits its performance characteristics from vector


with the additional overhead of managing stats specific operations.

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().

Classes that implements the queue interfaces:

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

2. No ordering: The insertion is the set interface is nuts in ordered manner


now that means the element present in it are not in an ordered way

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.

Classes that implements the set interface

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

2. Efficient Lookup: hashtable provides fast lookup operation due to its


underlying hash table implementation.

3. No ordering: Elements in the hash table are not shorted in any particular
manner.

Linked Hash Set


Hashtag is an implementation of the set interface in Java that Maintains the
insertion order of the element in addition to ensuring the uniqueness of the
element and it is achieved by using both hashed and linked list.
It maintains a doubly linked list alongside the hash table ensuring that elements
are stored in the order as they were inserted.
This allows Ling has shed to provide a predictable iterate order while still
offering fast lookup operation.

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.

Sorted Set Interface


A sorted set interface in Java represents a special type of set that maintains the
element in a sorted manner or order.
It extends the set interface and adds method for accessing and manipulating
the elements based on the sorted order.
The sorted set interface provides a powerful way to work with sorted collection
of unique elements in Java.
It offers efficient access to elements based on the sorted order.

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.

1. Sorted order Elements in a sorted set are stored in sorted order

2. uniqueness Like others set implementation sorted set does not allow
duplicate elements

3. efficient retrieval sorted set provide efficient method for retrieving


elements based on their sorted order

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.

1. Sorted order: Treeset maintains the elements in a sorted order according to


the natural ordering or in a specified comparator.

2. Unique elements: Like others set implementation tree set does not allow
duplicate elements.

3. Efficient operation: Preset offers efficient operation for adding removing


and accessing an element.

4. Iterating in sorted order: iterating over a tree set provides element in


sorted order

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.

1. Key value pair

2. Uniqueness of keys

3. No ordering

4. Efficient retrieval

Hash map Class


1. Implementation: hashtag is birthday youth implementation of the map
interface that stores Key value pair in the hash table data structure.

2. Performance: Hash map provides constant time average case performance


for basic operations like put and get assuming a good hash function and a
properly sized packing array it offers efficient insertion deletions and
retrieval of the elements.

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.

Linked Hash map class


1. Implementation: link hashtag is a implementation of the map interface that
extends hash map to maintain double linked list alongside the hash table
preserving the insertion order of the elements.

2. Performance: it provides similar performance characteristics to hash map


for basic operations like potent get it offers efficient insertion deletion and

JAVA 62
Retrieval of the elements with slightly higher memory overhead due to
maintaining the linked list.

3. Ordering: it maintains the assertion order of elements making it suitable for


scenarios where insertion order matters elements are treated over the same
order inverse they were inserted into the map.

Tree map class


1. Implementation: It is an implementation of the sorted map interface that
uses a red black tree data structure to store key value pair in sorted order
based on the keys.

2. Performance: It provides guaranteed log n time complexity for basic


operations like put get and remove it offers efficient insertion and removal
of the elements also retrieval elements with additional overhead for
maintaining the sorted tree structure.

3. Ordering: It maintains the elements in sorted order based on the natural


ordering of key value are a specified comparator this allows for efficient
range queries and iteration over elements in sorted order.

Hash Table class


1. Implementation: It is a legacy implementation of the map interface that
predates the Java collection framework it is similar to the hash map but it is
synchronized making it a thread safe or concurrent access from multiple
threads.

2. Performance: It provides similar performance characteristics to hash map


for basic operation like put and get however the synchronization overhead
may impact the performance of the multi threaded environments.

3. Ordering: It does not guarantee any specific order of elements similar to


hash Map.

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.

Using comparator interface


If the object you want to sort do not implement comparable or if you want to
sort them based on different ordering criteria you can use the comparator
interface.
completed define some method compare() that compares to object.
It returns negative value zero or a positive value depending upon the whether
the first object is less than the 2nd object or it is greater than the 2nd object or
it is equal to the 2nd object.
You can create custom comparator implementation and pass it to the method
like [Link]()

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:

1. Sorting collection the primary use of comparable is to enable sorting op


collection of objects

2. Natural ordering comparable allows object to define the natural ordering

3. Consistent sorting implementing comparable allows for consistent sorting


behavior

4. Ease of use comparable provides sanitized way to define the natural


ordering of the objects.

5. Integration with the collection framework comparable integrate seemingly


with the collection framework.

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:

a. The main purpose of property class is to manage configuration data in key


value pairs.

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:

a. the properties class is typically used in scenario where configuration


settings is need to be managed rather text of application than application
server application.

b. It provides simple and efficient way to handle configuration data in a key


value format.

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.

1. Predefined template: spring framework provides template for several


technologies so there's no need to write too much coat it hides the basic
step of these technologies.

2. Loose Coupling: The spring application are loosely coupled because of


dependency injection DI.

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.

4. Lightweight: spring framework is lightweight because of its POJO


implementation the spring framework does not force the programmer to
inherit any class or implement any interface that is why it is said
noninvasive.

5. Fast Development: The dependency injection feature of spring framework


and its support to various framework makes the easy development of
JavaEE application.

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.

1. Inversion of control: the core principle of spring framework is inversion of


control which allows the framework to manage the creation and lifecycle of
the objects.

2. Aspect oriented programming: enables modularization of concerns such


as logging transaction management security and caching

3. spring container: it manages the creation configuration and life cycle of


object (beans).

4. Spring MVC: Spring MBC is a web based framework build on top of the
spring framework providing a robust and flexible architecture

5. Data access and integration: spring provides powerful abstraction and


integration for working with various data access technologies.

6. Security: Spring Security is a highly flexible and customizable security


framework.

7. Testing and test integration this spring framework promotes testability by


supporting Integration testing and providing mock objects and a testing
utilities.

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.

1. Setter dependency injection: this is a simpler of the two dependency


injection method in this the dependence injection will be injected with the
help of Setter and Getter method now to set the dependency injection as
setter dependency injection in the bean it is done through the bean

JAVA 68
configuration file. the setter dependency injection is being declared under
the bean configuration file.

2. Constructor dependency injection: Spring MVC: in the dependency


injection will be injected with the help of the constructor nor to set
dependency injection as constructor dependency injection will be it is done
to the beam bound regression file. The constructor 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.

Aspect oriented programming


It is defined as the breaking of code into different modules where the aspect is
the key unit of modularity.
It addresses cross cutting concerns in an application.
Cross cutting concerns are functionalities that cut across multiple modules or
components such as longing caching authentication and transaction
management.
It provides a modular approach to separate and manage these concerns.
This helps in promoting code modularity reusability and maintainability.
In the spring frame framework it is seemingly integrated and provided robust
support for aspect oriented programming.
Aspect oriented programming in spring is primarily based on proxy based and it
is implemented using runtime proxies.

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.

Application runner and command line


runner
Springboard provides two interfaces application runner and command line
runner being functional interfaces both the runners have the single functional
method run.
When we implement one of these runner spring boot invokes the run method
after it starts the contest and before the application starts.
That means we can use spring boot command line runner or application runner
to execute a piece of code when launching an application or to create spring
boot non web applications.
Overall both command line and application runner asked Himmler and we can
use anyone of them to do the exact same thing.
The only difference between the application runner and command line runner is
that the application runner accepts the program argument wrapped in
application argument instances the application arguments provides convenient
method to access the program arguments.
While the command line runner receives the application of the program
argument as an array of strings.

Difference between Pojo and bean class


Aspect POJO JavaBean

No requirement for a Must have a no-argument (default)


Constructor
default constructor. constructor.

No restrictions; fields can


Field Access be public, protected, or Fields must be private.
private.

Optional, but common Must have public getter and setter


Getters/Setters
practice. methods.

Serializable Not required. Should implement Serializable interface.

Purpose General-purpose objects Standardized objects used in JavaBeans


with no specific architecture.

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:

Dependency Injection (DI): Simplifies the management of dependencies by


injecting them at runtime.

Aspect-Oriented Programming (AOP): Separates cross-cutting concerns


like logging and security from business logic.

Transaction Management: Provides a consistent programming model for


transaction management.

MVC Framework: Supports building web applications using the Model-


View-Controller pattern.

Integration with Other Technologies: Provides support for integrating with


various technologies like JPA, JMS, and more.

Configuration: Spring applications are typically configured using XML files or


Java configuration classes, which can be verbose and complex.

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:

Auto-Configuration: Automatically configures Spring and third-party


libraries based on the project's dependencies. This reduces the need for
manual configuration.

Embedded Servers: Provides embedded servers like Tomcat, Jetty, or


Undertow, allowing applications to be run as standalone applications

JAVA 72
without requiring a separate server installation.

Production-Ready Features: Includes features like metrics, health checks,


and application monitoring through the Actuator module.

Spring Boot Starters: Pre-configured templates for common functionalities


(e.g., web, data access) to simplify dependency management.

Spring Boot Initializr: A web-based tool to generate Spring Boot project


structures quickly.

Configuration: Spring Boot applications use a convention-over-configuration


approach and can be configured using [Link] or [Link] files. It
also supports externalized configuration, which makes it easier to manage
different environments.

Key Differences
Aspect Spring Spring Boot

Auto-configures based on
Requires extensive manual
Configuration dependencies and
configuration.
conventions.

Requires setting up and


Provides embedded servers
Setup configuring external servers and
and auto-configuration.
dependencies.

Can be complex to configure, Simplifies setup and reduces


Complexity
especially for new developers. boilerplate configuration.

Traditional WAR files or Typically packaged as


Application
standalone JAR files with standalone JAR files with
Structure
manual configuration. embedded servers.

Production-Ready Needs additional setup for Includes built-in production-


Features monitoring and metrics. ready features (Actuator).

Dependency Manual dependency Uses Spring Boot starters to


Management management. manage dependencies.

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.

Types of Spring Runners


1. CommandLineRunner

2. ApplicationRunner

3. SpringApplicationRunListener

4. @PostConstruct

CommandLineRunner : Executes code with command-line arguments after the


application starts.

ApplicationRunner : Similar to CommandLineRunner , but provides richer command-


line argument handling through ApplicationArguments .

: Provides hooks into the Spring Boot application


SpringApplicationRunListener

lifecycle for advanced use cases.

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:

Implement the CommandLineRunner interface in a Spring bean to execute code


after the application context is initialized.

Useful for running startup logic or initializing data.

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:

Implement the ApplicationRunner interface in a Spring bean to execute code


after the application context is initialized.

Useful when you need more detailed command-line argument processing.

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:

Implement SpringApplicationRunListener to add custom behavior before or after the


application starts.

Typically used in advanced scenarios or custom Spring Boot starters.

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.

Explain why Java does not support


multiple inheritance and how it can be
achieved
Java does not support multiple inheritance through classes to avoid the
complexity and ambiguity that arise from it. However, Java allows multiple
inheritance through interfaces, which provides the benefits of multiple
inheritance without its drawbacks.

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.

How Multiple Inheritance Can Be Achieved Using Interfaces


Java provides a way to achieve multiple inheritance through interfaces. A class
can implement multiple interfaces, allowing it to inherit the behavior specified
by multiple interfaces.

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");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}
//In this example, class C implements both interfaces A and B.
//This allows C to inherit the methods from both interfaces,
//achieving multiple inheritance.

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

public class Student {


// Private fields
private String name;
private int age;
private String course;

// Public no-argument constructor


public Student() {
}

// Parameterized constructor
public Student(String name, int age, String course) {
[Link] = name;
[Link] = age;
[Link] = course;
}

// Getters and Setters


public String getName() {
return name;
}

public void setName(String name) {


[Link] = name;
}

public int getAge() {


return age;

JAVA 78
}

public void setAge(int age) {


[Link] = age;
}

public String getCourse() {


return course;
}

public void setCourse(String course) {


[Link] = course;
}

// toString method (optional, useful for debugging)


@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", course='" + course + '\'' +
'}';
}
}

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

You might also like