0% found this document useful (0 votes)
17 views50 pages

JAVA LECTURES NOTE

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 50

JAVA LECTURES NOTE’s

Lecture 1: Java OOPS


Contents

 Introduction to Java Architecture: JDK, JRE, and JVM.


 Java OOPS Concepts: Object, Class, Inheritance, Polymorphism,
Abstraction, Encapsulation

Introduction to Java Architecture: JDK, JRE, and JVM

Java is one of the most widely used programming languages in the world,
known for its portability, scalability, and ease of use. Understanding its
architecture is crucial for effectively developing and running Java applications.
The Java architecture comprises three primary components: the Java
Development Kit (JDK), the Java Runtime Environment (JRE), and the Java
Virtual Machine (JVM). Each plays a distinct role in the lifecycle of a Java
application.

1. Java Development Kit (JDK)

The Java Development Kit (JDK) is a software development kit used to develop
Java applications. It provides the necessary tools and libraries to compile,
debug, and execute Java programs. The JDK includes:

 Compiler (javac): The compiler converts Java source code ( .java files)
into bytecode (.class files). Bytecode is a platform-independent code that
can be executed by the JVM.
 Java Runtime Environment (JRE): Included within the JDK, the JRE
provides the libraries and the JVM required to run Java applications. While
the JRE is essential for executing Java programs, it does not include
development tools.
 Development Tools: The JDK provides additional tools such
as javadoc for generating documentation, javap for disassembling class
files, and jar for packaging Java applications into JAR (Java ARchive) files.
 Debugger (jdb): This tool helps developers diagnose and fix issues in
their Java code by allowing them to set breakpoints, inspect variables,
and control execution flow.
In essence, the JDK is intended for developers who need to create and test Java
applications.

2. Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) is a runtime environment that provides


the resources needed to run Java applications. It is a part of the JDK but can
also be installed separately. The JRE includes:
 Java Virtual Machine (JVM): The core component responsible for
executing Java bytecode. It interprets or compiles bytecode into machine
code specific to the underlying hardware and operating system.
 Standard Libraries: A set of pre-written classes and methods
(e.g., java.lang, java.util, java.io) that developers can use to build Java
applications. These libraries provide functionality for data structures, file
handling, networking, and more.
 Runtime Environment: Includes everything necessary to run Java
applications, such as core libraries, Java class loaders, and garbage
collection mechanisms.
The JRE is designed for users who want to run Java applications but do not need
to develop or compile them.

3. Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is a crucial component of the Java architecture.
It provides a platform-independent execution environment for Java bytecode.
The key functions of the JVM include:

 Bytecode Execution: The JVM reads and executes Java bytecode, which
is a portable, intermediate representation of Java source code. This
allows Java applications to run on any device or operating system that
has a compatible JVM.
 Memory Management: The JVM handles memory allocation and
garbage collection. It manages the heap (where objects are allocated)
and the stack (where method calls and local variables are stored).
 Just-In-Time (JIT) Compilation: To improve performance, the JVM
employs JIT compilation, which compiles bytecode into native machine
code at runtime. This can lead to significant performance improvements
over interpretation alone.
 Class Loading: The JVM dynamically loads classes as needed. It uses
class loaders to find and load class files into memory.
 Exception Handling: The JVM manages exceptions and errors during
runtime. It provides mechanisms for throwing, catching, and handling
exceptions, ensuring that Java programs can recover from unexpected
conditions.

Interaction Between JDK, JRE, and JVM


 Development: When developers write Java code, they use the JDK,
which includes the compiler (javac). The compiler converts the source
code into bytecode.
 Execution: To run the compiled bytecode, users need the JRE. The JRE
contains the JVM, which executes the bytecode. The JVM converts the
bytecode into machine code that can be understood by the hardware.
 Runtime: During execution, the JVM manages memory, handles
exceptions, and performs JIT compilation to optimize performance.

Classes and Objects in Java

A CLASS is a user defined blueprint or prototype from which objects are


created. It represents the set of properties or methods that are common to all
objects of one type. In general, class declarations can include these
components, in order:

1. Modifiers: A class can be public or has default access


2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
6. Body: The class body surrounded by braces, { }.
CONSTRUCTORS : Constructors are used for initializing new objects. Fields
are variables that provides the state of the class and its objects, and methods
are used to implement the behavior of the class and its objects.

POINTS TO DISCUSS : Class , Abstract Class , Interface

An OBJECT is a basic unit of Object-Oriented Programming and represents real


life entities. A typical Java program creates many objects, which as you know,
interact by invoking methods.

An object consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Declaring Objects (Also called instantiating a class)

Code Example for Practice : https://ide.geeksforgeeks.org/yK1v1b9KLa

Ways to create object of a class

1. Using new keyword


2. Using Class.forName(String className) method
3. Using clone() method
4. Deserialization

Topics to discuss :
1. Static keyword in Java (https://www.geeksforgeeks.org/static-keyword-
java/)
2. Final keyword in Java (https://www.geeksforgeeks.org/final-keyword-in-
java/)
Access Modifier : Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access specifiers.

 public: accessible in all class in your application.


 protected: accessible within the package in which it is defined and in
its subclass(es)(including subclasses declared outside the
package)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier): accessible
within same class and package within which its class is defined.

Object Oriented Programming (OOPs) Concept in Java

Object-oriented programming aims to implement real-world entities like


inheritance, hiding, polymorphism etc in programming. The main aim of OOP is
to bind together the data and the functions that operate on them so that no
other part of the code can access this data except that function.

Let us now discuss 4 pillars of OOPS:

Pillar 1: Abstraction

Data Abstraction is the property by virtue of which only the essential details
are displayed to the user. The trivial or the non-essentials units are not
displayed to the user. Ex: A car is viewed as a car rather than its individual
components.

Code Example : https://ide.geeksforgeeks.org/btCYEwU3Mj

Point to discuss : Abstract classes and Abstract methods

Pillar 2: Encapsulation

Encapsulation is defined as the wrapping up of data under a single unit. It is


the mechanism that binds together code and the data it manipulates. Another
way to think about encapsulation is, it is a protective shield that prevents the
data from being accessed by the code outside this shield.
Code Example : https://ide.geeksforgeeks.org/wh3Iqv4eHx

Pillar 3: Inheritence

Inheritance is an important pillar of OOP(Object-Oriented Programming). It is


the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class.

Types of Inheritance in Java

1. Single Inheritance : https://ide.geeksforgeeks.org/iXpFHkh4rz


2. Multilevel Inheritance : https://ide.geeksforgeeks.org/tbBVCp8wQn
3. Hierarchical Inheritance : https://ide.geeksforgeeks.org/EXeCyyqZgY
4. Multiple Inheritance : https://ide.geeksforgeeks.org/W161yoraTO
5. Hybrid Inheritance(Through Interfaces)

Pillar 4: Polymorphism

The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.

Types of polymorphism :

In Java polymorphism is mainly divided into two types:

 Compile-time Polymorphism : https://ide.geeksforgeeks.org/cijtDcYUT2


 Runtime Polymorphism : https://ide.geeksforgeeks.org/4cgdWD1eJX
Lecture 2: Abstract Classes vs. Interfaces and
Exception Handling, Singleton Design Pattern
Contents

 Abstract Class, Interface (Example of Interface: Runnable Interface),


Anonymous Inner Class
 Exceptional Handling
 Singleton Design Pattern

ABSTRACT CLASS :

A class that is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

abstract class Shape


{
int color;

// An abstract function
abstract void draw();
}
Challenge 1 : Can we have a function in the abstract class with a body ?

References :

https://www.geeksforgeeks.org/abstract-classes-in-java/

INTERFACE :
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not the method body. It is used to
achieve abstraction and multiple inheritance in Java. In other words, you can
say that interfaces can have abstract methods and variables. It cannot have a
method body. Java Interface also represents the IS-A relationship . That means
all the methods in an interface are declared with an empty body and are public
and abstract and all fields are public, static, and final by default. A class that
implements an interface must implement all the methods declared in the
interface.

// A simple interface
interface Player
{
final int id = 10;
int move();
}
Challenge 1 : Can we have a function in the interface with a body ? ( HINT :
default function)

Challenge 2 : Can we override the default function in the implementing


class ? OR How do we call the default methods of an interface in the
implementation class ?

HINT : If two interfaces have same name default method , we need to override
that method in our implementation class . Its a rule .

We override the default function in the class and inside its body use the
<interfaceName>.super.<methodName>()

Challenge 3 : If we are overriding a default function in our implementation


class , then how can we call the default function of the interface ?

HINT : <InterfaceName>.super.<functionName>(x,y)

Challenge 4 : How to access the variables in our implementation class which


have been defined in the interface ? Can we change its value in the
implementation class and Why ? (HINT : All variables in interface are public,
final and static )

Challenge 5 : In the implementation class , in the implementation of an


abstract method ,can we give access modifier as protected ?
Challenge 6 : If a class A is implementing an interface I and extending a class
C . Which is correct ?

class A extends C implements I


OR
class A implements I extends C

Challenge 7 : If my class A extends interface B and interface C , both having


same default method “power” . Even if my object of class A does not call power
and does not overrides the default method power , will there be any issues and
why ?

Challenge 8 : Is it possible that in parent class , function A has protected


access modifier In child class which extends parent , while overriding , can we
give access modifier of A as :

(i) public

(ii) private

HINT : we can't assign weaker privileges while overriding methods .

References :

 https://www.geeksforgeeks.org/interfaces-in-java/
 https://www.geeksforgeeks.org/static-method-in-interface-in-java/
 https://www.geeksforgeeks.org/default-methods-java/

ANONYMOUS INNER CLASS :

An anonymous inner class can be useful when implementing an interface or


abstract class with certain “extras” such as overriding abstract methods of
interface/abstract class , without having to actually subclass a class.

Challenge 1 : Is multiple inheritance allowed in Java with (i) classes (ii)


interface ?

Challenge 2 : Is multiple inheritance allowed in Java ?

Challenge 3 : Does an interface implements other interface or extends other


interface ?

Challenge 4 : Can an interface extend a class and why?


Challenge 5 : What is the difference between Abstract Class and Interface ?

Challenge 6 : Can we override default methods of an interface in other


interface which extends it ?

HINT : https://www.geeksforgeeks.org/difference-between-abstract-class-and-
interface-in-java/

References :

 https://www.geeksforgeeks.org/nested-classes-java/
 https://www.geeksforgeeks.org/anonymous-inner-class-java/
 https://stackoverflow.com/questions/2515477/why-is-there-no-multiple-
inheritance-in-java-but-implementing-multiple-interfac
 https://www.geeksforgeeks.org/java-and-multiple-inheritance/

Exceptions in Java

Exception Handling in Java is one of the effective means to handle the runtime
errors so that the regular flow of the application can be preserved. Java
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

What is an Exception?

An exception is an unwanted or unexpected event, which occurs during the


execution of a program i.e at run time, that disrupts the normal flow of the
program’s instructions.

What is an Error?

Errors represent irrecoverable conditions such as Java virtual machine (JVM)


running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.

Errors are usually beyond the control of the programmer and we should not try
to handle errors.

Error vs Exception

 Error: An Error indicates a serious problem that a reasonable application


should not try to catch.
 Exception: Exception indicates conditions that a reasonable application
might try to catch.

Exceptions can be Categorized into 2 Ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception

2. User-Defined Exceptions

Points to discuss :
 Need of try-catch clause(Customized Exception
Handling) https://ide.geeksforgeeks.org/wWRSZ6gZVj
 throw, throws https://www.geeksforgeeks.org/throw-throws-java/
 finally https://www.geeksforgeeks.org/g-fact-24-finalfinally-and-finalize-
in-java/

SINGLETON DESIGN PATTERN :

Singleton pattern is a design pattern which restricts a class to instantiate its


multiple objects. It is nothing but a way of defining a class. Class is defined in
such a way that only one instance of the class is created in the complete
execution of a program or project. It is used where only a single instance of a
class is required to control the action throughout the execution.

Challenge 1 : We have a Person class . Our task is to make sure that when
we create objects of Person class , constructor gets called only once, i.e. all
objects have the same hashcode .

Challenge 2 : Why do we need Singleton classes ? (HINT : Driver Class for


making connections to the database .)

Challenge 3 : Why does the newly created getPerson function in Person needs
to be static ?

References :

 https://www.geeksforgeeks.org/singleton-design-pattern-introduction/
 https://www.geeksforgeeks.org/singleton-design-pattern/
 https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-
examples/

FUNCTIONAL INTERFACE :

A functional interface is an interface that contains only one abstract method.


They can have only one functionality to exhibit. From Java 8 onwards, lambda
expressions can be used to represent the instance of a functional interface. A
functional interface can have any number of default methods. Runnable,
ActionListener, Comparable are some of the examples of functional interfaces.

Challenge 1 : Lets checkout Runnable Interface

Challenge 2 : Let us now create an object of Runnable interface using


Anonymous Inner Class
Challenge 3 : Lets now try to write our first lambda by trying to do the
Challenge 2 using Lambda .

Challenge 4 : Now we have our object of Function Interface (Runnable ) . How


do we know which function to call ?

Challenge 5 : Lets now create a custom Function Interface with a function


taking 2 argos . And now lets create object of this custom functional interface
using (i) Anonymous Inner Class (ii)Lambda

Challenge 6 : Convert the following to Lambda :

Challenge 7 : If the interface for which we want to write lambda contains 2


abstract methods . Is there a problem ?

Challenge 8 : If the interface for which we want to write lambda contains 2


default methods and a single abstract . Is there a problem ? How can we call
the default methods ?

Challenge 9 : Why do we use @FunctionalInterface annotation ? Is it


mandatory ?

HINT : @FunctionalInterface tells users that this interface is intended to be a


functional interface and if there is more than one abstract methods added ,
then it throws at the interface level at compile time .

Challenge 10 : Is Comparator Interface a Functional Interface ?

HINT : equals method is coming from Object class .


Challenge 11 : If we are creating lambda for a Functional Interface in a class .
Does that class need to implement the interface?

References :

 https://www.geeksforgeeks.org/functional-interfaces-java/
 https://stackoverflow.com/questions/50892117/why-to-use-
functionalinterface-annotation-in-java-8
 https://piyush5807.medium.com/functional-interfaces-in-a-nutshell-for-
java-developers-54268e25324

GENERICS :

Generics means parameterized types. The idea is to allow type (Integer, String,
… etc., and user-defined types) to be a parameter to methods, classes, and
interfaces. Using Generics, it is possible to create classes that work with
different data types. An entity such as class, interface, or method that operates
on a parameterized type is a generic entity.

Challenge 1 : Can we convert our custom Functional Interface to be a generic


interface with input type as T and return type as R .

HINT : We need to also convert our abstract method accordingly .

Now when we create the lambda for this functional interface , we will also need
to accommodate the generic types we want . Below are 2 examples of how we
can use the same Interface with different lambdas because our input type and
output type data types are generics .
References :

 https://www.geeksforgeeks.org/generics-in-java

STREAMS :

A stream is a sequence of objects that supports various methods which can be


pipelined to produce the desired result. stream() is sequential processing one
by one and parallelStream is multithreading .

Intermediate Operations:

1. map: The map method is used to returns a stream consisting of the


results of applying the given function to the elements of this stream.
2. filter: The filter method is used to select elements as per the Predicate
passed as argument.
3. sorted: The sorted method is used to sort the stream.
Terminal Operations:

1. collect: The collect method is used to return the result of the


intermediate operations performed on the stream.
2. forEach: The forEach method is used to iterate through every element of
the stream.
3. reduce: The reduce method is used to reduce the elements of a stream
to a single value. The reduce method takes a BinaryOperator as a
parameter. Reduce does not return a Stream .

Challenge 1 : Given a list of city names .We have to find out which cities start
with a vowvel and return a list with cities which start with vowels and are in
uppercase .

Challenge 2 : You have a list of integers, you need to find the sum of squares
of even numbers [1, 2, 3, 4, 5, 6, 7, 8] = [4 + 16 + 36 + 64 = 120]

Challenge 3 : You have a list of cities , you need to concatenate them .


Challenge 4 : You have a list of cities, you need to concatenate them but with
a space in between .

Challenge 5 : In the last scenario , what will be the result if we use identity as
null ?

Challenge 6 : You have a list of cities, you need to sort them in :

(i)ascending order (ii)descending order (iii) Increasing order of String length (iv)
decreasing order of String length

Challenge 7 : What is the difference between IntStream and


Stream<Integer>?

HINT : https://stackoverflow.com/questions/64974871/what-is-the-difference-
between-intstream-and-streaminteger

ASSIGNMENT : Assignment 2 (Streams)

MUST Watch Resources for Lambda and Streams :

 https://www.youtube.com/watch?v=F73kB4XZQ4I
 https://www.youtube.com/watch?v=1OpAgZvYXLQ

References :

 https://piyush5807.medium.com/declarative-programming-in-java-using-
streams-and-lambdas-3f71edcd7a74 IMP
 https://stackify.com/streams-guide-java-8/
 https://www.geeksforgeeks.org/stream-in-java/
 https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
 https://www.geeksforgeeks.org/parallel-vs-sequential-stream-in-java/
 https://www.geeksforgeeks.org/streams-arrays-java-8/
Lecture 5: Multithreading
Contents

 Multithreading (Thread, Thread Group , Ways of Thread Creation,


Sequential vs Parallel Stream , Thread.Join )

MULTITHREADING:

Multithreading is a Java feature that allows concurrent execution of two or


more parts of a program for maximum utilization of CPU. Each part of such
program is called a thread. So, threads are light-weight processes within a
process.
Challenge 1 : What is the Main thread ?

HINT: default thread initialised by JVM on running main function . This is the
thread in which all of your code runs .

Challenge 2 : Why multithreading : Parallelism ? or Sequential processing ?

Challenge 3 : How to print the name of the current running thread ?

HINT : Thread.currentThread().getName()

Challenge 4 : If we call a function , do we launch a new thread ? Lets now


create our own custom thread named MyThread and spawn it .

HINT : Threads can be only be created by using two mechanisms :

(i) Extending the Thread class

(ii) Implementing the Runnable Interface

Challenge 5 : What is a native function ?

HINT : currentThread() inside Thread class gets its definition from Hardware OS
library .

Challenge 6 : How to get the number of processors available in your


machine ?

How many max threads can run simultaneously in your system ?

HINT :

System.out.println(Runtime.getRuntime().availableProcessors());
System.out.println(“Total memory available to JVM ”+
Runtime.getRuntime().totalMemory()
System.out.println(“Total bytes of memory used by JVM :
“+Runtime.getRuntime().totalMemory() -
Runtime.getRuntime().freeMemory());
Challenge 7 : In Thread class definition , why is start0 a private function and
start a public function ?

Challenge 8 : Although we are overriding the run function in our custom


thread class . If you put a print statement to check the name of a thread in
your run function , on calling start we see its a new thread . Then why do we
call the start method and not the run method ?

Challenge 9 : Create 2 custom threads and using debugger lets check which
spawns faster .

Challenge 10 : https://ide.geeksforgeeks.org/NY98CbN0vk

Which line out 15 and line 28 be executed first ?

HINT : Think if they are executing sequentially or parallely by two different


threads . You can check for multithreading by putting debug point at line 15
and 28 .

Challenge 11 : Can the same thread object call start() twice ? HINT :
IllegalThreadStateException . We can check this by putting debug points and
observing the threadstatus property .If thread status is not 0 , this means
thread has already started so it throws the exception simply .

Challenge 12 : Which out of the two ways ( extending Thread vs


implementing Runnable ) is better way to create Threads ?

Challenge 13 : You are given an array of integers and you need to calculate
the factorial of all these .

int[] numbers = {15000, 52000, 80000, 60000, 70000, 6000, 80000,


24000,
40000, 300, 400, 5000, 6000};
Way 1 : Sequential
Way 2 : Using parallel streams ( check the order this time while
printing
and while collecting in list )
Way 3 : Multithreading

Challenge 14 : Consider the following code :


int[] num = {1,2,3,6,60,72};
int number = Arrays.stream(num).parallel().filter(n -> n
%6==0).findFirst().orElse(-1);
System.out.println(number);
The parallel streams ignore order while processing , then do we get the actual
first element which is a multiple of 6 or not . Give reason to support your
answer .

HINT : Before terminal operation ( findFirst here ) , the numbers in the stream
get ordered according to their position in the array which was streamed .

Challenge 15 : What is the issue with the below Multithreaded solution for the
above challenge ?

Incorrect Solution https://ide.geeksforgeeks.org/yIQPkKOXnD

Corrected Solution https://ide.geeksforgeeks.org/5YeOHNzLj4

Challenge 16 : The correct solution has used thread.join() . Does this makes
our solution to be parallel or is it still multithreading and the thread.join() call is
not blocking ?

HINT : When we are waiting for a thread to die , are we stopping the processing
for the other threads? Execution cant go ahead until the thread on which join is
called dies , but are we stopping other threads processing ? ( think about it )
Thread.join is waiting for a thread to die while other threads are also
processing . It's just other threads can't proceed ahead in execution of code
until that thread is alive . This is 50% faster than sequential .
HINT 2 : Please have a look at the debug Thread trace with debug point at
thread.join() in this
image
: https://drive.google.com/file/d/19bWesFSJha8aEyOeS93IrfLvDpomr8uK/view?
usp=sharing

Challenge 17 : Is parallelStreams always faster than sequential streams ?

HINT : Find the first even number in an array of one million items .

Challenge 18 : Thread vs Process

HINT : https://www.geeksforgeeks.org/difference-between-process-and-thread/

Challenge 19 : User Threads vs Daemon Threads

HINT : https://www.geeksforgeeks.org/difference-between-daemon-threads-
and-user-threads-in-java/?ref=rp

Challenge 20 : (Homework ) Print even and odd numbers in increasing order


using two threads in Java

HINT : First learn about wait() and notify()


concept https://www.geeksforgeeks.org/difference-between-wait-and-notify-in-
java/

https://www.geeksforgeeks.org/print-even-and-odd-numbers-in-increasing-
order-using-two-threads-in-java/?ref=rp

Challenge 21 : Is Concurrency same as Parallelism ?

HINT : Concurrency is the task of running and managing the multiple


computations at the same time .While parallelism is the task of running
multiple computations simultaneously.

Then what is sequential ?

https://www.geeksforgeeks.org/difference-between-concurrency-and-
parallelism/
Challenge 22 : What is the volatile keyword in Java ?

HINT : Volatile keyword is used to modify the value of a variable by different


threads. It is also used to make classes thread safe. It means that multiple
threads can use a method and instance of the classes at the same time without
any problem. https://www.geeksforgeeks.org/volatile-keyword-in-java/

References :

 https://www.geeksforgeeks.org/multithreading-in-java/
 https://www.geeksforgeeks.org/lifecycle-and-states-of-a-thread-in-java/ I
MP
 https://www.geeksforgeeks.org/difference-between-thread-start-and-
thread-run-in-java/ IMP
 https://stackoverflow.com/questions/8052522/why-we-call-thread-start-
method-which-in-turns-calls-run-method#:~:text=It's%20due%20to
%20the%20design,not%20start%20a%20new%20Thread.
 https://www.geeksforgeeks.org/joining-threads-in-java/ IMP
 https://www.geeksforgeeks.org/java-lang-threadgroup-class-java/
 https://www.geeksforgeeks.org/biginteger-class-in-java/
 https://www.geeksforgeeks.org/biginteger-intvalue-method-in-java/
 https://www.interviewbit.com/multithreading-interview-questions/#is-it-
possible-that-each-thread-can-have-its-stack-in-multithreaded-
programming
 https://www.baeldung.com/java-concurrency-interview-questions
 https://www.journaldev.com/1162/java-multithreading-concurrency-
interview-questions-answers
 https://pediaa.com/what-is-the-difference-between-serial-and-parallel-
processing-in-computer-architecture/ IMP
 https://www.baeldung.com/java-volatile
Lecture 6: Maven
Contents

 Maven, Need of Maven , POM.xml, Maven Repository and Types, Maven


Lifecycle.

MAVEN : Maven is a powerful project management tool based on the Project


Object Model (POM). It is used for project building, managing dependencies,
and documentation. It simplifies the build process, much like ANT, but it is
much more advanced than ANT.

In short, we can say that Maven is a tool that can be used for building and
managing any Java-based project. Maven makes the day-to-day work of Java
developers easier and generally helps with the comprehension of any Java-
based project.

Let us have a brief look at the very informative article :

https://www.geeksforgeeks.org/introduction-apache-maven-build-automation-
tool-java-projects/

What are the shortcomings of not using Maven?


Challenge 1: Let's create a Java project without Maven and try to execute a
'create table' query using the JDBC protocol. Suppose you have a database with
the name 'test_db_jbdl.' What would happen if you run this code?

public static void main(String[] args) throws SQLException {


Connection connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test_db_jbdl",
"root", "");

Statement statement = connection.createStatement();


statement.execute("create table maven_dummy(id int, name
varchar(30), count int)");
}
Will there be any (i) compilation error or (ii) runtime error ?

HINT : Click on the execute method of statement object for its implementation .

Challenge 2 : How to manage dependencies without Maven ?

HINT : We can download the dependency as a jar and deploy it in our project
structure .

File > ProjectStructure > Library > Add New > Java

HOW TO ADD DEPENDENCIES USING MAVEN

Challenge 1 : What is groupId , ArtifactId and version in a maven project?

HINT : https://maven.apache.org/guides/mini/guide-naming-conventions.html

groupId: A unique identifier for an entity or organization.


ArtifactId: A unique identifier for a project.

Challenge 2 : Create a maven project and add the following dependencies


using spring initializer :

-Lombok
Now, let's create a Person class with properties such as id, name, and age.
Then, we'll use the Lombok dependency to create a Person object to test if the
dependency works.

Challenge 3 : Maven automatically adds any child dependencies for the


dependencies we need to add to our project. If we manually place the JAR files
in the project's library path, will the child dependencies, if any, still be fulfilled?

Challenge 4 : What is pom.xml, and how do we add dependencies to


pom.xml?
HINT: A Project Object Model, or POM, is the fundamental unit of work in
Maven. It is an XML file that contains information about the project and
configuration details used by Maven to build the project. It provides default
values for most projects.

Challenge 5 : Does the dependency get downloaded just by adding it to


pom.xml ?

HINT :

Through this button , we have to load the changes and download the
dependency from central repository .

https://repo.maven.apache.org/maven2/

Challenge 6 : What is the difference between the 'External Libraries' in a Java


project and the 'External Libraries' in a Maven project?

HINT: The combination of groupId, artifactId, and version forms an archetype,


and a Maven project's dependency is also a Maven project.

Challenge 7 : Where are the parent/child dependencies of any dependency


you add in pom.xml defined?

HINT: In your project's pom.xml, click on the artifactId of the dependency for
which you need to know the parent/child dependencies. .

Challenge 8 : Why do we need the parent dependencies for our dependency


in pom.xml? Is it really necessary?

Challenge 9 : What is the scope tag inside a dependency in pom.xml?

HINT : https://stackoverflow.com/questions/26975818/what-is-scope-under-
dependency-in-pom-xml-for
Challenge 10 : How do you search for the mysql-connector-java dependency
in the Official Central repository?

HINT : Go to https://repo.maven.apache.org/maven2/

First search for group id and then artifact id and then the (latest) version .

MAVEN REPOSITORY

Maven Repository

Maven repositories are directories of packaged JAR files with accompanying


metadata. The metadata includes POM files related to the projects to which
each packaged JAR file belongs. It also indicates the external dependencies
associated with each packaged JAR. This metadata enables Maven to download
dependencies, including transitive dependencies, until all required components
are downloaded and stored on your local machine.

Maven has three types of repository :

1. Local repository (for storing dependencies downloaded to your local


computer)
2. Central repository (contains public dependencies available on the
internet)
3. Remote repository (typically private to an organization and accessible on
the internet)

Maven searches for dependencies in these repositories. It first looks in the


Local repository, then the Central repository, and, if specified in the POM, the
Remote repository.
Local repository- A local repository is a directory on the developer's machine.
This repository contains all the dependencies that Maven downloads. Maven
only needs to download the dependencies once, even if multiple projects
depend on them (e.g., JDBC).

By default, the Maven local repository is located in the user's home directory,
for example:

C:\Users\asingh.m2.

Central repository- The central Maven repository is created by the Maven


community. Maven checks this central repository for any dependencies needed
but not found in your local repository. Maven then downloads these
dependencies into your local repository.

Official Maven Central Repository ~ https://repo.maven.apache.org/maven2/

Remote repository-A remote repository is a repository on a web server from


which Maven can download dependencies. It is often used for hosting projects
internal to an organization. Maven fetches these dependencies and stores
them in your local repository.

Challenge 1 : Lets explore the local repository in your .m2 folder of your
computer
Challenge 2 : What will happen if I delete a dependency version which my
maven project is currently using ?

HINT : It does not give an error immediately, but we will notice that the
dependency is no longer present in the 'External Libraries.' When we run the
Java class, it throws a SQL exception: 'No suitable driver found.'

Challenge 3 : If we change the directory inside the terminal and navigate to


our Maven project, then run 'mvn package,' what will happen?

HINT: To understand this, we need to consider the Maven Build Lifecycle:

 validate: Validates that the project is correct and that all necessary
information is available.
 compile: Compiles the source code of the project.
 test: Tests the compiled source code using a suitable unit testing
framework. These tests should not require the code to be packaged or
deployed.
 package: Takes the compiled code and packages it in its distributable
format, such as a JAR.
 verify: Runs any checks on the results of integration tests to ensure that
quality criteria are met.
 install: Installs the package into the local repository for use as a
dependency in other local projects.
 deploy: Performed in the build environment, it copies the final package
to the remote repository for sharing with other developers and projects.
Maven Commands

mvn clean: Cleans the project and removes all files generated by the previous
build.

mvn validate : (intermediary phase )Validates the src folder to check if code
files are placed correctly .

mvn compile: Compiles source code of the project into target

mvn test-compile: Compiles the test source code.

mvn test: Runs tests for the project.

mvn package: compiles , runs tests and Creates JAR or WAR file for the
project to convert it into a distributable format.

mvn verify: checks if the jar is created .

mvn install: Deploys the packaged JAR/ WAR file to the local repository.
mvn deploy: Copies the packaged JAR/ WAR file to the remote repository after
compiling, running tests and building the project.

(Contd ) Challenge 3 : We deleted the dependency using the terminal from


local repository . If we change the directory inside the terminal and go to our
maven project and then run the mvn package, what will happen ?

HINT : It will download from central .

Challenge 4 : Now if we run the maven package once again , will it again
download from the central repository or refer to the dependency in the local
repository (.m2 folder) ?

Challenge 5 : Does mvn package or mvn install also perform mvn clean ?

HINT : Generally when we run any of the above commands, we add the mvn
clean step so that the target folder generated from the previous build is
removed before running a newer build. This is how the command would look on
integrating the clean step with install phase: mvn clean install .

Challenge 6 : What is the difference between "mvn package" and "mvn


install"?

HINT: mvn install also installs your current project in your .m2/repository folder
so other projects can use it as an archetype or dependency. (Source:
https://stackoverflow.com/questions/16602017/how-are-mvn-clean-package-
and-mvn-clean-install-different)

Challenge 7: If we have no compile-time errors in classes inside the


src/main/java folder but we have a compile-time error in a class inside the
src/test/java folder:
(i) When we run mvn compile, will we get a compile-time error, or will our
src/main/java code be successfully compiled and put into the target folder?

(ii) Will the JAR file be created inside the target folder?

(iii) Will we get an error if we run mvn test instead of mvn compile?

Challenge 8: If we have a compile-time error in the src/main/java folder and


no compile-time error in the src/test/java folder:

What will happen if we run mvn test?

HINT: Maven lifecycle phases are sequential. If you run mvn test, then mvn
validate and mvn compile will also run.

Challenge 9: Create a new Maven project called 'Calculator.' Inside


src/main/java, create a class 'Calcy' with function definitions for addition,
multiplication, division, and subtraction of two numbers. Now, your task is to
use this 'Calculator' Maven project as a dependency in your previous Maven
project and find out what 4 times 80 is.

HINT : mvn install


Challenge 10: If you create another Maven project named 'Business' and
include the dependency of your original Maven project in its POM, will the
'Business' project also contain the dependency of the 'Calculator' project?
(Assuming you have run the mvn install command for the original Maven basics
project)

Challenge 11: What if you delete the 'Calculator' dependency from the local
repository? Then:

(i) If there is code using the 'Calci' class in the 'Business' project or the original
project's class files, will they throw a compile-time error?

(ii) How can you remediate it?

HINT: Run the mvn install command for the 'Calculator' project to install it in
the local repository.

Challenge 12: If you go to your 'Calculator' project and add a new method
called 'calculatePower' inside the 'Calci' class, your task is to find 3^4 by
calling Calci.power(3, 4) inside the 'Business' Project.

(i) Will you be able to call this new function inside the 'Business' project?

(ii) If you run mvn package, will you be able to use this function inside the
'Business' project?
(iii) If you run mvn install, will you be able to use this function inside the
'Business' project?

Challenge 13: What is the difference between mvn package and mvn clean
package?

Challenge 14: If you have a Maven project A with a dependency on mysql-


connector-java version 10 and another Maven project B with a dependency on
mysql-connector-java version 12, and in your Maven project C, you have
projects A and B as parent dependencies. Which version of mysql-connector-
java will be present in the external libraries of Project C?

HINT: Consider the position of defining dependencies A and B in the POM. In the
case of the same dependencies, the version will be of whichever is listed first in
the POM of C. If you don't want to rely on the position in the POM, you can use
exclusions. If you want to use the version of mysql-connector-java from Project
A, you can use an exclusion tag while defining the dependency of B in the POM
of C.

Challenge 15 : How to rename the target folder to new?

HINT : In the pom.xml, add the following code after your 'dependencies' tag:

<build>
<directory>/Users/aadhar/Desktop/JBDL-master/L4_maven-basics/new</
directory>
</build>

Challenge 16 : (Homework) How can you change the path of the .m2 folder
using the pom.xml?

References :
 https://www.geeksforgeeks.org/introduction-apache-maven-build-
automation-tool-java-projects/ IMP
 Official Maven Documentation by Apache : https://maven.apache.org/
 https://repo.maven.apache.org/maven2/ Official Maven Central
Repository
 https://mvnrepository.com/ Unofficial Maven Central Resource
 https://stackoverflow.com/questions/39185798/what-is-the-difference-
between-artifactid-and-groupid-in-pom-xml IMP
 https://stackoverflow.com/questions/14725316/what-is-the-use-of-pom-
xml-in-maven
 https://maven.apache.org/guides/introduction/introduction-to-
repositories.html
 https://www.geeksforgeeks.org/maven-lifecycle-and-basic-maven-
commands/ IMP
 https://maven.apache.org/guides/introduction/introduction-to-the-
lifecycle.html
 https://stackoverflow.com/questions/6028534/how-to-exclude-
dependency-in-a-maven-plugin IMP Exclusions
https://maven.apache.org/guides/introduction/introduction-to-optional-and-
excludes-dependencies.html IMP Exclusions
Lecture 8: Intro to Spring Boot
Contents

 Introduction to Server and Client Model


 Introduction to Spring Boot
 How to run application as a Server
 What are Embedded Servers ( Jetty , Tomcat )
 Logging Levels In Spring Boot
 Running Spring Boot applications in different spring profiles
 Running Spring Boot applications on terminal

INTRODUCTION TO SERVER AND CLIENT MODEL : The Client-server model


is a distributed application structure that partitions task or workload between
the providers of a resource or service, called servers, and service requesters
called clients. In the client-server architecture, when the client computer sends
a request for data to the server through the internet, the server accepts the
requested process and deliver the data packets requested back to the client.
Clients do not share any of their resources. Examples of Client-Server Model
are Email, World Wide Web, etc.

Challenge 1 : What is an application server ?


When an application runs as a server , it becomes an entity which runs
continuously which you can make requests to get some output out of it . eg :
amazon.in

Challenge 2 : When we type amazon.in in the url window of Google , does this
request hit Amazon server or Google server ?

Challenge 3 : Let's explore Google Chrome Developer Tools and inspect the
requests in the Network tab .

HINT : When we search MS Dhone in google.in . Basically the frontend is


converting your search into a GET API request .The server returns a response
inform of json object . This json response from the backend gets parsed on the
frontend .

Challenge 4 : What is an API and why Rest api is called Idempotent while
SOAP is not ?

HINT : API is just cient b/w client and server to communicate and get a
response .

https://www.geeksforgeeks.org/application-programming-interfaces-api-and-its-
types/

Challenge 5 : What are the components of an API ?

HINT : https://www.bigcommerce.com/blog/what-is-an-api/#what-about-rest-
soap-apis

Challenge 6 : What is the meaning of HTTP request ? Is rest api request not
HTTP request ?

HINT : HTTP is a protocol . HTTP request is a way to communicate with the


server following the rules of HTTP protocol . This request is stateless . REST
refers to a set of attributes of a particular architectural style, while HTTP is a
well-defined protocol that happens to exhibit many features of a RESTful
system.
Challenge 7 : What is the difference b/w web API and web service ?

HINT : https://www.geeksforgeeks.org/differences-between-web-services-and-
web-api/

https://stackoverflow.com/questions/808421/api-vs-webservice

Challenge 8 : Find the ip address of google.com .

HINT : host google.com

Now put the ip address of google.com in the url bar and press enter .

This ip address is not of google server , it is of load balancer . ( distributor


which routes the request to an application server )

Challenge 9 : What is scaling and its types ?

HINT : https://www.cloudzero.com/blog/horizontal-vs-vertical-scaling

Challenge 10 : What is load balancer and how is it helpful in horizontal scaling


?

HINT : https://www.geeksforgeeks.org/load-balancer-system-design-interview-
question/

Challenge 11 : What means when we say Restful API is stateless ?

HINT : response will be the same irrespective of how many times we make the
request .

References :

 https://www.geeksforgeeks.org/client-server-model/
 https://medium.com/@maneesha.wijesinghe1/what-happens-
when-you-type-an-url-in-the-browser-and-press-enter-
bb0aa2449c1a
 https://www.geeksforgeeks.org/introduction-to-apis/
 https://stackoverflow.com/questions/19336347/what-is-the-
difference-between-a-web-api-and-a-web-service
 https://blog.uptrends.com/technology/the-anatomy-of-an-api-
call/
 https://blog.yellowant.com/rest-api-calls-made-easy-
7e620e4d3e82
 https://www.geeksforgeeks.org/proxy-server/
 https://www.nginx.com/resources/glossary/reverse-proxy-vs-
load-balancer
 https://www.geeksforgeeks.org/state-the-core-components-of-
an-http-response/
 https://www.smashingmagazine.com/2018/01/understanding-
using-rest-api/

INTRODUCTION TO SPRING BOOT

Spring is widely used for creating scalable applications. For web applications
Spring provides Spring MVC which is a widely used module of spring which is
used to create scalable web applications. But the main disadvantage of spring
projects is that configuration is really time-consuming and can be a bit
overwhelming for the new developers. Making the application production-ready
takes some time if you are new to the spring. Solution to this is Spring Boot.
Spring Boot is built on the top of the spring and contains all the features of
spring.

Challenge 1 : What is an embedded server ?

HINT : It gives you low level code that helps to start the server . An embedded
server is embedded as part of the deployable application. If we talk about Java
applications, that would be a JAR. The advantage with this is you don’t need
the server pre-installed in the deployment environment. With SpringBoot, the
default embedded server is Tomcat (built by Apache) . Other options available
are Jetty(built by Eclipse) and UnderTow(built by Redhat) .

Challenge 2 : What is the difference b/w Web server and Application server ?

HINT : For static websites we call it a web server and for dynamic websites ,we
have an application server .

https://www.geeksforgeeks.org/difference-between-web-server-and-application-
server/
Challenge 3 : What is a database server ?

HINT : Application server uses database server to persist data . App server has
code logic running and does not have much space to store all data , thus , we
need the Database server .

Challenge 4 : What is a virtual machine ?

HINT : https://azure.microsoft.com/en-in/overview/what-is-a-virtual-machine/

Challenge 5 : Let's make our first spring boot project with maven using
start.spring.io . ( Don't add any dependencies yet )

Challenge 6 : What are the two dependencies that are added to the POM.xml
by default by start.spring.io and why ?

HINT : spring-boot-starter is needed to simply run your Spring Boot


Application . ( we are not even talking about running as server )
Challenge 7 : Which dependency to add to POM.xml to allow our spring boot
application to run as a server ?

HINT : spring-boot-starter-web ( note : The moment we add this to POM.xml


and load changes , spring-boot-starter dependency disappears . Why : because
spring-boot-starter-web has spring-boot-starter as a parent dependency so no
need to have it separately )

Challenge 8 : Now how to load our downloaded spring boot project into IntelliJ
IDE ?

Challenge 9 : Let's explore the POM of our project and check the parent POM
of each dependency by clicking on artifact id .

Challenge 10 : Let's explore the structure of our spring boot project and
External Libraries .

Challenge 11 : Run the application . Now lets see the difference between
spring-boot-starter and spring-boot-starter-web by replacing spring-boot-
starter-web from our POM.xml with spring-boot-starter . Run the application
once again after loading the changes .

HINT : On exploration of the parent POM of spring-boot-starter-web , we can


see that it has an embedded server TOMCAT as a parent dependency which
allows the spring boot application to run as a server .

Challenge 12 : Now add spring-boot-starter-web back again and remove


spring-boot-starter from our POM . Run the application . This time ,let us read
the logs and observe together .
Challenge 13 : Is it possible to use any other embedded servers for running
our spring boot application as a server ? How ?

HINT : Once added and changes are loaded , we can see Jetty in the External
Libraries. Run.

Challenge 14 : What is a port ? Which port does TOMCAT run on ?

HINT : https://www.geeksforgeeks.org/tcp-ip-ports-and-its-applications/

Supposedly you own a building. The street address corresponds to the IP


address. Also, the way there is a port number, each building also has a building
number.

Challenge 15 : What will happen if we don't exclude Tomcat and also add
Jetty as a dependency in our POM.xml . Now which port will be used and which
server will run the spring boot application ?

HINT : As Tomcat is default embedded server and if it's present , other


embedded server dependencies become redundant .
Challenge 16 : (HomeWork) Explore the class
ServletWebserverApplicationContext by doing Ctrl+Shift+F and click on
Scope .

HINT : This is the class responsible for loading the web server into application
context .

Challenge 17 : How to change the port on which your tomcat application


server runs ?

HINT : server.port = 8081 ( application.properties )

Search for server.port by Ctrl + Shift + F and look in scope to check where the
default value 8080 is defined for it . While Spring Boot is able to override its
default values in autoconfigure jar by using application.properties .This
functionality is missing in Spring .

Challenge 18 : (HomeWork) If we exclude Tomcat from our project and add


Jetty and Undertow dependencies in POM.xml in no specific order . When we
run the application , which server will run ? Why ?

HINT : Jetty will run in every case . Order does not matter .

Challenge 19 : If we have all three embedded servers in our POM.xml . Which


server will the application run on ?

HINT : Tomcat is default .

Challenge 20 : (HomeWork) Which embedded server takes the least time to


start among Jetty , Tomcat and Undertow ?

References :

 https://www.geeksforgeeks.org/difference-between-spring-and-spring-
boot/ IMP
 https://www.geeksforgeeks.org/introduction-to-spring-boot/ IMP
 https://www.educative.io/edpresso/web-server-vs-application-server
 https://www.baeldung.com/java-jar-war-packaging IMP
 https://stackoverflow.com/questions/39632667/how-do-i-kill-the-process-
currently-using-a-port-on-localhost-in-windows

LOGGING LEVELS IN SPRING BOOT : A good logging infrastructure is


necessary for any software project as it not only helps in understanding what’s
going on with the application but also to trace any unusual incident or error
present in the project.

Challenge 1 : Why do we need a logger when we have System.out.println() ?

HINT : Debugging (debug) , checking threads and heartbeat of servlets (Trace )

Challenge 2 : What do we mean by Logging Levels ?

HINT : In terms of severity : Error > Warning > Info > Debug > Trace

Challenge 3 : What is the by default logging level and how to change it ?

HINT : Default logging level is INFO . We can change it by defining property in


the application.properties file : logging.level.<package_name> = debug
Example : logging.level.root = debug where root stands for applying the
logging level to all packages in the application

Challenge 4 : If logging level is debug , what all levels of logs will be printed ?

HINT : All logging levels above and over debug in terms of severity will be
printed ie Error , Warning , Info , Debug . Trace logs will not be printed .

Challenge 5 : Which logging level will have the most number of logs ?

HINT : Trace

Challenge 6 : For the below code , if my logging level is error in the


application.properties file . Then how many logs will be printed ?

Challenge 7 : Can we log something from the run function of a thread ?


HINT :

Challenge 8 : Can we have logging level as Trace / Debug in Production ?

HINT : Cost of storing such a huge number of logs is high and memory
requirements are high .Not suitable for debugging .

Challenge 9 : How can we specify different levels of logging for different


environments (dev ,qa , sit , preprod , prod ) ?

HINT : We can have a separate config file ( application.properties ) file for each
environment .
Step 1 - Create the application-<env>.properties file and define the port
number and the logging level you require when the application runs in that
environment .

Step 2 - Open Edit Configuration for the project as shown below and define
which spring profile should the application run as out of all spring profiles we

have in our application.properties


When we run our application now , we can see that its running on dev profile
and thus trace and greater severity logs are getting printed in the console .
This is how we can maintain different profiles for different environments .

Challenge 10 : If I have three spring profiles i.e. have three application-


<env>.properties files defined . These are for dev , prod and preprod . Now

when I edit configurations , I give spring.profiles.active=production . Below is


my application.properties .

Answer the following questions :

(i)Instead of application-dev.properties , can we have a file with the name


dev.properties ?

(ii) At which port will my app run ?

(iii) What is the logging level ?

HINT : As active spring profile is not found , so it follows the


application.properties file

https://dzone.com/articles/spring-boot-profiles-1

Challenge 11 : How to run a spring boot application from terminal ?

HINT : jar -jar <path of jar in target folder>


java -jar
/Users/aadhar/Desktop/JBDL-23-master/L5_spring-demo/target/spring-
demo-0.0.1-SNAPSHOT.jar
Challenge 12 : Can we run spring boot project from terminal in any desired
spring profile that we have defined an application-<env>.properties for ?

HINT :

java -jar -Dspring.profiles.active=preprod


/Users/aadhar/Desktop/JBDL-23-master/L5_spring-demo/target/spring-
demo-0.0.1-SNAPSHOT.jar

Challenge 13 : Can we run the same spring boot application on different


profiles at the same time ?

HINT : port in use is different

Challenge 14 : Can we have different types of databases in different profiles ?

Challenge 15 : Can we define different logging levels for different packages ?

Challenge 16 : What is the utility of the @SpringBootApplication ?

HINT : This annotation is used to mark the main class of a Spring Boot
application. It encapsulates @SpringBootConfiguration,
@EnableAutoConfiguration, and @ComponentScan annotations with their
default attributes.

https://www.geeksforgeeks.org/spring-boot-annotations/

https://learnjava.co.in/the-springbootapplication-annotation-explained/
References :

 https://www.geeksforgeeks.org/spring-boot-logging/
 https://www.youtube.com/watch?v=lGrcZsw-hKQ
 https://stackoverflow.com/questions/5817738/how-to-use-log-
levels-in-java
 https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/
reference/html/boot-features-logging.html
 https://dzone.com/articles/spring-boot-profiles-1 IMP
 https://www.geeksforgeeks.org/http-headers/ V Good for
Request and Response Headers

You might also like