0% found this document useful (0 votes)
42 views174 pages

OOP CourseFile@BCS403 Final

The document outlines the course file for Object-Oriented Programming with Java (BCS-403) at B.S.A. College of Engineering & Technology, detailing the vision and mission of the college and department, course outcomes, syllabus, and academic calendar. It includes a comprehensive index of course materials, teaching methodologies, and assessment strategies, as well as a detailed syllabus covering Java programming concepts and the Spring framework. The document serves as a guide for both instructors and students to navigate the course structure and expectations.

Uploaded by

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

OOP CourseFile@BCS403 Final

The document outlines the course file for Object-Oriented Programming with Java (BCS-403) at B.S.A. College of Engineering & Technology, detailing the vision and mission of the college and department, course outcomes, syllabus, and academic calendar. It includes a comprehensive index of course materials, teaching methodologies, and assessment strategies, as well as a detailed syllabus covering Java programming concepts and the Spring framework. The document serves as a guide for both instructors and students to navigate the course structure and expectations.

Uploaded by

SHILPI BANSAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 174

B.S.A.

College of Engineering & Technology


Mathura (U.P.) - 281004

Department of Computer Sci. & Applications

Course File
on

OOP with Java


(BCS - 403)
Course:- B.Tech
Department:- CS&A(10)
Year/Semester:- 2nd/4th

Subject Teacher:
Shilpi Bansal
Asst. Prof.(CA)
Vision of the College
BSACET strives to impart a holistic knowledge centric environment to serve
humanity by providing research oriented technical education to nurture global
leaders and entrepreneurs.
Mission of the College
Create an ecosystem to foster a culture of innovation, research, academic excellence.
Format for Course File & Lab Manual BSACET, Mathura

Index
S.N. Content Remark
1 Academic Calendar
2 Syllabus with Course outcomes (COs)
3 Course outcome (CO) Program outcome (PO)
mapping
4 Course outcome (CO) Program specific outcome
(PSO) mapping
5 Class/Section Time Table
6 Individual Time Table
7 Lecture Plan and Lecture Plan Execution
8 University Question paper
9 Question Paper
10 Attendance Record
11 Unit Test- Question Papers with CO & Results
12 List of weak students and plan for weak students
13 Subject Notes (handwritten/ presentation)
13 Assignments
14 Tutorial Sheets
15 Sessional Marks breakups
16 Result of Subject (last 3 years)
B.S.A. College of Engineering & Technology, Mathura
Department of Computer Sci.& Application
Tentative Academic Calendar Even Sem 24-25
B.S.A. College of Engineering & Technology, Mathura
Department of Computer Sci.& Application
Date:- 25-07-25

Vision of the Department


The Vision of the Department is to develop the department as a center for academic excellence through
teaching and research that encourages and nurtures literary sensibilities, language competence and critical
thinking.

Mission of the Department


The Mission of the Department is to offer advanced, career-oriented post graduate and research programmers imparting
professional knowledge, employability and life skills, as well as inculcating a vision of community growth and development
and strong ethical values

PEOs
1.Engage in successful careers in industry, academia, and public service, by applying the acquired
knowledge of Science, Mathematics and Engineering, providing technical leadership for their business,
profession and community
2: Establish themselves as entrepreneur, work in research and development organization and pursue higher
education
PSOs
1: Exhibit attitude for continuous learning and deliver efficient solutions for emerging challenges in the
computation domain.
2: Apply standard software engineering principles to develop viable solutions for Information Technology
Enabled Services (ITES).

HOD- CSA
Object Oriented
Programming with Java
(BCS403)
Course Outcome (CO) Bloom’s Knowledge Level (KL)
At the end of course, the student will be able to:
Develop the object-oriented programming concepts using Java K3, K4
CO 1
Implement exception handling, file handling, and multi- K2,K4
CO 2 threading in Java
Apply new java features to build java programs. K3
CO 3

Analyse java programs with Collection Framework K4


CO 4

Test web and RESTful Web Services with Spring Boot using K5
CO 5 Spring Framework concepts
DETAILED 3-1-0
SYLLABUS
Unit Topic Proposed
Lecture
Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java
Source File Structure, and Compilation. Fundamental,
I
Programming Structures in Java: Defining Classes in Java, Constructors,
Methods, Access Specifies, Static Members, Final Members, Comments, 08
Data types, Variables, Operators, Control Flow, Arrays & String.

Object Oriented Programming: Class, Object, Inheritance Super Class,


Sub Class, Overriding, Overloading, Encapsulation, Polymorphism,
Abstraction, Interfaces, and Abstract Class.

Packages: Defining Package, CLASSPATH Setting for Packages, Making


JAR Files for Library Packages, Import and Static Import Naming
Convention For Packages
Exception Handling: The Idea behind Exception, Exceptions & Errors,
II Types of Exception, Control Flow in Exceptions, JVM Reaction to
Exceptions, Use of try, catch, finally, throw, throws in Exception Handling,
In-built and User Defined Exceptions, Checked and Un-Checked 08
Exceptions.

Input /Output Basics: Byte Streams and Character Streams, Reading and
Writing File in Java.

Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread


Priorities, Synchronizing Threads, Inter-thread Communication.
Java New Features: Functional Interfaces, Lambda Expression, Method
III References, Stream API, Default Methods, Static Method, Base64 Encode 08
and Decode, For Each Method, Try-with resources, Type Annotations,
Repeating Annotations, Java Module System, Diamond Syntax with Inner
Anonymous Class, Local Variable Type Inference, Switch Expressions,
Yield Keyword, Text Blocks, Records, Sealed Classes
Java Collections Framework: Collection in Java, Collection Framework in
IV Java, Hierarchy of Collection Framework, Iterator Interface, Collection
Interface, List Interface, ArrayList, LinkedList, Vector, Stack, Queue 08
Interface, Set Interface, HashSet, LinkedHashSet, SortedSet Interface,
TreeSet, Map Interface, HashMap Class, LinkedHashMap Class, TreeMap
Class, Hashtable Class, Sorting, Comparable Interface, Comparator
Interface, Properties Class in Java.
Spring Framework: Spring Core Basics-Spring Dependency Injection
V concepts, Spring Inversion of Control, AOP, Bean Scopes- Singleton,
Prototype, Request, Session, Application, Web Socket, Auto wiring, 08
Annotations, Life Cycle Call backs, Bean Configuration styles

Spring Boot: Spring Boot Build Systems, Spring Boot Code Structure,
Spring Boot Runners, Logger, BUILDING RESTFUL WEB SERVICES, Rest
Controller, Request Mapping, Request Body, PathVariable, Request
Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications
Program and program specific outcome attainment calculation (2023-24)
B.S.A. College of Engineering & Technology, Mathura
Department of Computer Sci.& Application

Class Time Table for Even Sem 24-25


(Section -A)
B.S.A. College of Engineering & Technology, Mathura
Department of Computer Sci.& Application
Class Time Table for Odd Sem 24-25
(Section -B)
B.S.A. College of Engineering & Technology, Mathura

Near New Bus Stand


Mathura (U.P.) 281004
[email protected]

General Report

Unit Topic Periods


No.
1 Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java 08
Source File Structure, and Compilation. Fundamental,

Programming Structures in Java: Defining Classes in Java, Constructors,


Methods, Access Specifies, Static Members, Final Members, Comments,
Data types, Variables, Operators, Control Flow, Arrays & String.

Object Oriented Programming: Class, Object, Inheritance Super Class, Sub


Class, Overriding, Overloading, Encapsulation, Polymorphism, Abstraction,
Interfaces, and Abstract Class.

Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR


Files for Library Packages, Import and Static Import Naming Convention For
Packages
2 Exception Handling: The Idea behind Exception, Exceptions & Errors, Types 08
of Exception, Control Flow in Exceptions, JVM Reaction to Exceptions, Use of
try, catch, finally, throw, throws in Exception Handling, In-built and User
Defined Exceptions, Checked and Un-Checked Exceptions.

Input /Output Basics: Byte Streams and Character Streams, Reading and
Writing File in Java.

Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread


Priorities, Synchronizing Threads, Inter-thread Communication.
3 Java New Features: Functional Interfaces, Lambda Expression, Method 08
References, Stream API, Default Methods, Static Method, Base64 Encode
and Decode, For Each Method, Try-with resources, Type Annotations,
Repeating Annotations, Java Module System, Diamond Syntax with Inner
Anonymous Class, Local Variable Type Inference, Switch Expressions, Yield
Keyword, Text Blocks, Records, Sealed Classes
4 Java Collections Framework: Collection in Java, Collection Framework in 08
Java, Hierarchy of Collection Framework, Iterator Interface, Collection
Interface, List Interface, ArrayList, LinkedList, Vector, Stack, Queue
Interface, Set Interface, HashSet, LinkedHashSet, SortedSet Interface,
TreeSet, Map Interface, HashMap Class, LinkedHashMap Class, TreeMap
Class, Hashtable Class, Sorting, Comparable Interface, Comparator
Interface, Properties Class in Java.
5 Spring Framework: Spring Core Basics-Spring Dependency Injection 06
concepts, Spring Inversion of Control, AOP, Bean Scopes- Singleton,
Prototype, Request, Session, Application, Web Socket, Auto wiring,
Annotations, Life Cycle Call backs, Bean Configuration styles

Spring Boot: Spring Boot Build Systems, Spring Boot Code Structure, Spring
Boot Runners, Logger, BUILDING RESTFUL WEB SERVICES, Rest Controller,
Request Mapping, Request Body, PathVariable, Request Parameter, GET,
POST, PUT, DELETE APIs, Build Web Applications
Topic Covered

L. No. Date Topic Reference

Unit 1: Introduction: Why Java, History of Java, JVM,


1 JRE, Java Environment
2 Java Source File Structure, and Compilation. Fundamental
3 Defining Classes in Java, Constructors, Methods, Access
Specifies
4 Static Members, Final Members, Comments
5 Data types, Variables, Operators, Control Flow, Arrays & String.

6 Class, Object, Inheritance Super Class, Sub Class, Overriding,


Overloading, Encapsulation
7 Polymorphism, Abstraction, Interfaces, and Abstract Class.
Defining Package
8 CLASSPATH Setting for Packages, Making JAR Files for
Library Packages, Import and Static Import Naming Convention
For Packages
9 Unit 2:- The Idea behind Exception, Exceptions & Errors, Types
of Exception
10 AdditionFlow
Control and in
subtraction of JVM
Exceptions, signed numbers,
Reaction to Exceptions, Use of
try, catch, finally,
11 throw, throws in Exception Handling, In-built and User Defined
Exceptions, Checked and Un-Checked Exceptions
Input /Output Basics: Byte Streams and Character Streams,
12 Reading and Writing File in Java.
13 Thread, Thread Life Cycle,
14 Creating Threads, Thread Priorities
15 Synchronizing
16 Threads,
Inter-thread Communication.
17 Unit 3: Java New Features: Functional Interfaces, Lambda
Expression
18 Method References, Stream API,Default Methods, Static
Method
19 Base64 Encode and Decode, ForEach Method
20 Try-with resources,Type Annotations
21 Repeating Annotations, Java Module System
22 Diamond Syntax with Inner Anonymous Class
23 Local Variable Type Inference, Switch Expressions
24 Yield Keyword, Text Blocks, Records, Sealed Classes
25 Unit 4:- Java Collections Framework : Collection in Java,
Collection Framework in Java
26 Hierarchy of Collection Framework, Iterator Interface,
Collection Interface
27 List Interface, ArrayList, LinkedList,Vector, Stack, Queue
Interface, Set Interface, HashSet, LinkedHashSet
28 SortedSet Interface,TreeSet, Map Interface, HashMap Class
29 LinkedHashMap Class, TreeMap Class
30 Hashtable Class,Sorting, Comparable Interface
31 Comparator Interface, Properties Class in Java.

32 Comparator Interface, Properties Class in Java.


33 Unit-V Spring Framework: Spring Core Basics-Spring
Dependency Injection concepts
34 Spring Inversion of Control, AOP, Bean Scopes- Singleton,
Prototype, Request, Session, Application
35 Web Socket, Auto wiring, Annotations, Life Cycle Call
backs, Bean Configuration styles
36 Spring Boot: Spring Boot Build Systems, Spring Boot Code
Structure
37 Spring Boot Runners, Logger,
BUILDING RESTFUL WEB SERVICES, Rest Controller
38 Request Mapping, Request Body, Path
Variable, Request Parameter
39 GET, POST, PUT, DELETE APIs

40 Build Web Applications

Text Books
1. Herbert Schildt, "Java The complete reference", McGraw Hill Education
2. Craig Walls, “Spring Boot in Action” Manning Publication
1. Steven Holzner, “Java Black Book”, Dreamtech.
2. Balagurusamy E, “Programming in Java”, McGraw Hill
3. Java: A Beginner’s Guide by Herbert Schildt, Oracle Press
4. Greg L. Turnquist “Learning Spring Boot 2.0 - Second Edition”, Packt
Publication
5. AJ Henley Jr (Author), Dave Wolf, “Introduction to Java Spring Boot: Learning by
Coding”,
Independently Published

University Question Paper


Question Bank
Questio
n Bank

UNIT-1
1. What are some key features of Java that make it popular for software
development?
2. What is JVM. Explain the architecture of JVM.
3. Define the Java Runtime Environment (JRE) and its components.
4. Describe the components of the Java environment necessary for Java
development.
5. Explain java source file structure and compilation.
6. Explain Constructor in Java.
7. Explain Constructor Overloading with java. Illustrate with a suitable example.
8. Outline the use of constructor and use this keyword in java.
9. Explain Method Overloading with java. Illustrate with a suitable example.
10. Explain in detail the different access specifier in Java.
11. Explain how to declare, initialize, and manipulate arrays and strings.
12. Explain in detail the static member in java.
13. How does the final keyword affect variables, methods, and classes?
14. Write a short note on ‘Java comments’
15. Explain following: 1. Java Variables 2. Java Literals 3. Different operators in
java
16. Define super class and sub class in the context of inheritance.
17. Define polymorphism and its types in Java. Provide examples demonstrating
compile-time and
runtime polymorphism.
18. What is method overriding in Java? Explain the rules and conditions for
method overriding.
19. Discuss the differences between method overloading and method
overriding
Is there any alternative solution for Inheritance? If so explain the advantages and
disadvantages
of it.
20.Is there any alternative solution for Inheritance? If so explain the advantages
and disadvantages
of it.
21. What is abstraction, and why is it important in Java? Discuss how abstraction
is achieved in
Java through abstract classes and interfaces.
22. What are the types of inheritances in java? Explain each of them in detail
23. Write a java program to implement various types of inheritance. i. Single ii.
Multi-Level iii.
Hierarchical iv. Hybrid
24. Create an abstract class Media (id, description). Derive classes Book
(pagecount) and CD
(playtime). Define parameterized constructors. Create one object of Book and CD
each and
display the details.
25. What is interface? Write a program to demonstrate how interfaces can be
extended.
26. Write a java program to implement the following a. Creation of simple
package b. Accessing a
package
27. What is package? How do you create a package? Explain about the access
protection in
packages?
28. Define package? What is the significance of CLASS PATH variable?
29. What is a JAR file, and how is it used in Java? Describe the steps involved in
creating a JAR
file for a library package.
30. What is the import statement used for in Java? Explain the difference
between regular import
and static import.
31. Discuss the naming conventions for packages in Java. What are some best
practices to follow
when naming packages?
Explain about final classes, final methods and final variables?

UNIT-2
1. Give the classification of exceptions
2. Differentiate between exceptions and errors in Java.
3. Describe the different types of exceptions in Java (checked exceptions,
unchecked exceptions,
runtime exceptions).
4. Define exception? Explain about various keywords used in handling the
exceptions
5. What happens when an exception occurs during program execution in Java?
Describe how the
JVM reacts to exceptions and errors.
6. In Java, is exception handling implicit or explicit or both? Explain with the help
of example
Java programs
7. Discuss the concept of exception handling and its significance in software
development.
8.Discuss the roles of Checked and Unchecked Exceptions with your supporting
examples.
9. Discuss the role of the throw and throws keywords in exception handling.
10.Explain the purpose of the try-catch-finally blocks in Java
exception handling.
11.What are in-built exceptions in Java, and how are they used?
12.How can you define custom (user-defined) exceptions in Java?
13.Explain the concept of command- line argument with suitable program.
14. What are byte streams and character streams in Java I/O? Explain the
difference between byte
streams and character streams.
15. How can you read data from a file using byte streams in Java? Provide an
example of reading a
text file using FileInputStream and BufferedInputStream.
16. How can you write data to a file using byte streams in Java? Provide an
example of writing to a
text file using FileOutputStream and BufferedOutputStream.
17. Provide examples of reading and writing text files using FileReader,
FileWriter,
BufferedReader, and BufferedWriter.
18. Explain creation of thread using run able interface with an example
19. Explain about inter –thread Communication with an example
20. Explain the life cycle of a thread and multithreading
21. Explain about thread interrupts with an example
22. Implementing Run able interface and extending Thread, which method you
prefer for
multithreading and why?
23. With the help of an example, explain multithreading by extending Thread
class ?
24. What are daemon threads, and how are they different from user threads?
25. Write a Java program that creates three threads. First thread displays OOPS,
the second thread
displays Through and the third thread Displays JAVA by using Runnable interface
26. Write a java program which accepts withdraw amount from the user and
throws an exception
In Sufficient Funds when withdraw amount more than available amount. Write a
java program
to illustrate finally block.

UNIT-3
1. What Is a Functional Interface? What Are the Rules of Defining a Functional
Interface?
2. Describe Some of the Functional Interfaces in the Standard Library. What Is a
Lambda
Expression and What Is It Used For?
3. What is a default method? What is a static method?
4. Explain the Syntax and Characteristics of a Lambda Expression
5. What Is a Stream? How Does It Differ From a Collection?
6.Is is possible to define our own Functional Interface? What is
@FunctionalInterface? What are
the rules to define a Functional Interface
7. When do we go for Stream API? Why do we need to use Stream API in our
projects?
8. Explain basic Type Base64 Encoding and Decoding in Java
9. Encode simple String into Basic Base 64 format
10. Explain Java Type and Repeating Annotations

UNIT-4
1. Explain the hierarchy of the Collection Framework in Java.
2. What is the purpose of the Iterator interface in Java's Collection Framework?
3. Differentiate between the Collection interface and the Collections class in Java.
4. Compare and contrast ArrayList, LinkedList, and Vector in Java.
5. What is the role of the Set interface in Java, and how does it differ from other
collection types?
6. Discuss the differences between HashSet, LinkedHashSet, and TreeSet in Java.
7. How does the TreeMap class differ from HashMap and LinkedHashMap in Java?
8. What is the Comparable interface, and how is it used for sorting objects in
Java?
9. Discuss the properties and applications of the Properties class in Java.
10. How does the Hashtable class differ from HashMap in Java, and when would
you prefer to use
each?
11. Describe the Properties class in Java and its common use cases.
12. What is the ordering of elements in a LinkedHashSet?
13. Write a Java program that demonstrates sorting an ArrayList of custom
objects using the
Comparable interface.
14. Write a Java program to demonstrate basic operations (addition, removal,
and iteration) on a
HashSet containing strings.
15. Implement a Java program to create a TreeSet of integers and perform
operations like addition,
removal, and printing in sorted order.

UNIT-5
1. Explain the concept of dependency injection in Spring.
2. Compare constructor injection and setter injection in Spring.
3. What is Inversion of Control in the context of Spring? How does Spring
implement IoC?
4. Explain the different bean scopes in Spring (Singleton, Prototype, Request,
Session,
Application).
5. What is autowiring in Spring. Explain different types of autowiring modes in
Spring
6. List and explain some commonly used annotations in Spring. How do
annotations reduce the
need for XML configuration?
7. Describe the life cycle of a Spring bean
8. Compare XML-based and annotation-based bean configuration styles.
9. What are the popular build systems supported by Spring Boot?
10. Describe the typical code structure of a Spring Boot application
11. What are Spring Boot runners? How can you create a custom runner in a
Spring Boot
application?
12. How do you configure logging in a Spring Boot application? Name some
popular logging
frameworks used in Spring Boot.
13. What is REST, and how does it relate to Spring Boot? Explain the concept of a
RESTful
controller in Spring Boot.
14. What is the @RestController annotation used for?
15. Explain the usage of the @RequestMapping annotation in Spring Boot.
16. Describe the usage of @RequestBody, @PathVariable, and @RequestParam
annotations.
17. Explain the usage of HTTP methods GET, POST, PUT, and DELETE in Spring
Boot.
18. How can you build web applications using Spring Boot?
19. Describe the components typically involved in a Spring Boot web application.
Class Test Paper
B.S.A. COLLEGE OF ENGG. & TECHNOLOGY, MATHURA

B.Tech. 2nd Year (IV sem) Examination: 2024-25

CT-1
OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS403)

Time- 1.5 hr Max Marks -20


SECTION-A

Q (1).Attempt all parts. All parts carry equal marks. (1*5=5)


(a) Explain difference between JDK and JRE in Java.
(b) Object is an instance of class, justify your answer.
(c) What are access modifiers in JAVA?
(d) When do we declare a method or class final?
(e) Why JAVA does not support Multiple Inheritance?
SECTION-B
Note: - Attempt any two questions. (5*2=10)
Q(2) Explain Interfaces in Java with suitable example.
Q(3) Illustrate polymorphism and its types in Java. Differentiate between run-time and compile-time
polymorphism. Write super class Shape with method Display Area and subclass Rectangle.
Demonstrate method overriding with this example.

Q(4) What is Package? How do you create a package? Explain about the access protection in
packages.

SECTION-C
Q-5 Attempt any One part. (5*1=5)
a) What are the concepts of OOP? Explain the compilation and execution process of JAVA program
with proper diagram.
b) Illustrate Constructors and their applications in Java. Describe the types of constructors used in
Java. Write a class with name Student with attributes roll_number, name, branch and email. Write all
argument constructor for class Student and create two objects with this constructor.
B.S.A. COLLEGE OF ENGG. & TECHNOLOGY, MATHURA

B.Tech. 2nd Year (IV sem) Examination: 2024-25

CT-2
OBJECT ORIENTED PROGRAMMING WITH JAVA (BCS403)

Time- 1.5 hr Max Marks -20


SECTION-A

Q (1).Attempt all parts. All parts carry equal marks. (1*5=5)


(a) Explain difference between throws and throw keyword in JAVA.
(b) Explain types of ways to create thread in Java.
(c) Write a java program to demonstrate Arithmetic exception handling.
(d) What is multithreading?
(e) What is default method?
SECTION-B
Note: - Attempt any two questions. (5*2=10)
Q(2) Describe how thread synchronization takes place in java? Explain with suitable example?
Q(3) What do you mean by exception handling. Describe its keywords?
Q(4) Explain the functional interfaces in java. Describe lambda expressions with the help of
functional interfaces.

SECTION-C
Q-5 Attempt any One part. (5*1=5)
a) Differentiate between with suitable example:
i) Character Streams & Byte Streams
ii) Wait() and notify()
b) Describe various states achieved by thread in its life cycle.
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the shared
resource.

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
. }
. class MyThread1 extends Thread{
. Table t;
. MyThread1(Table t){
. this.t=t;
. }
. public void run(){
. t.printTable(5);
. }
.
. }
. class MyThread2 extends Thread{
. Table t;
. MyThread2(Table t){
. this.t=t;
. }
. public void run(){
. t.printTable(100);
. }
. }
.
. class TestSynchronization1{
. public static void main(String args[]){
. Table obj = new Table();//only one object
. MyThread1 t1=new MyThread1(obj);
. MyThread2 t2=new MyThread2(obj);
. t1.start();
. t2.start();
. }
. }
5
100
10
200
15
300
20
400
25
500

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

. }
. }
. class MyThread1 extends Thread{
. Table t;
. MyThread1(Table t){
. this.t=t;
. }
. public void run(){
. t.printTable(5);
. }
.
. }
. class MyThread2 extends Thread{
. Table t;
. MyThread2(Table t){
. this.t=t;
. }
. public void run(){
. t.printTable(100);
. }
. }
. public class TestSynchronization2{
. public static void main(String args[]){
. Table obj = new Table();//only one object
. MyThread1 t1=new MyThread1(obj);
. MyThread2 t2=new MyThread2(obj);
. t1.start();
. t2.start();
. }
. }

Synchronized block can be used to perform synchronization on any specific resource of the
method.

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such
cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.
o A Java synchronized block doesn't allow more than one JVM, to provide access control to a
shared resource.
o The system performance may degrade because of the slower working of synchronized
keyword.
o Java synchronized block is more efficient than Java synchronized method.

class Table
{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
. }
. }
. }

Java provides a convenient way to group multiple threads in a single object. In such a way, we can
suspend, resume or interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class.

A ThreadGroup represents a set of threads. A thread group can also include the other thread
group. The thread group creates a tree in which every thread group except the initial thread
group has a parent.

A thread is allowed to access information about its own thread group, but it cannot access the
information about its thread group's parent thread group or any other thread groups.

readGroup tg1 = new ThreadGroup("Group A");


read t1 = new Thread(tg1,new MyRunnable(),"one");
read t2 = new Thread(tg1,new MyRunnable(),"two");
read t3 = new Thread(tg1,new MyRunnable(),"three");
w we can interrupt all threads by a single line of code only.
read.currentThread().getThreadGroup().interrupt();

blic class ThreadGroupDemo implements Runnable{


public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one");
t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();

}
}
Unit 4
0

:ミ.ミに 0

ミ0

( ミご~
YO
/ ク ノ ノ

膨イ厖丿. クンル

の ら,るしン
9.
[ ・~


1
Unit 5

What is Spring Framework?

Spring is a lightweight and popular open-source Java-based framework developed by Rod Johnson in
2003.

It is used to develop enterprise-level applications.

It provides support to many other frameworks such as Hibernate, Tapestry, EJB, JSF, Struts etc, so it is
also called a framework of frameworks.

It’s an application framework and IOC (Inversion of Control) container for the Java platform. The spring
contains several modules like IOC, AOP, DAO, Context, WEB MVC, etc.

Spring Framework is a Java platform that provides comprehensive infrastructure support for developing
Java applications. Spring handles the infrastructure so you can focus on your application.

Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise
services non-invasively to POJOs. This capability applies to the Java SE programming model and to full and
partial Java EE.

Examples of how you, as an application developer, can use the Spring platform advantage:

 Make a Java method execute in a database transaction without having to deal with transaction APIs.
 Make a local Java method a remote procedure without having to deal with remote APIs.
 Make a local Java method a management operation without having to deal with JMX APIs.
 Make a local Java method a message handler without having to deal with JMS APIs.
The Spring framework is modular and consists of several modules that provide different functionalities to
help build enterprise applications. The modules can be broadly categorized into four main areas: Core
Container, Data Access/Integration, Web, and Miscellaneous. Let’s take a closer look at each area and its
corresponding modules:

Core Container

The Core Container provides the fundamental functionality of the Spring framework, including the Inversion
of Control (IoC) container and the ApplicationContext. It includes the following modules:

Spring Core: This module provides the fundamental functionality of the Spring framework, including IoC
and DI. The IoC container is the heart of the Spring Framework, responsible for creating and managing
instances of JavaBeans. It uses dependency injection to wire the beans together.

Spring Beans: This module provides the BeanFactory, which is the basic building block of the IoC container,
and the BeanWrapper, which is responsible for managing the lifecycle of a bean. The Bean Factory is the core
interface for accessing the IoC container. It provides methods for retrieving beans.
Spring Context: This module provides the ApplicationContext, which is an advanced version of the
BeanFactory and provides additional features, such as internationalization and resource loading, and the
ability to publish and consume events.

Spring Expression Language (SpEL): This module provides a powerful expression language for querying
and manipulating objects during runtime. SpEL supports a wide range of features, including property access,
method invocation, conditionals, loops, and type conversion. It also provides support for accessing variables
and functions defined in the application context, as well as support for defining custom functions and
variables.

Data Access/Integration

The Data Access/Integration area provides support for integrating with databases and other data sources. It
includes the following modules:

Spring JDBC: This module provides a simple JDBC abstraction layer that reduces the amount of boilerplate
code required to work with JDBC. Spring JDBC provides support for transaction management, allowing
developers to manage database transactions declaratively using Spring’s transaction management.

Spring ORM: This module provides integration with Object-Relational Mapping (ORM) frameworks, such
as Hibernate and JPA. Spring ORM provides a higher-level abstraction layer on top of ORM frameworks,
allowing developers to write less boilerplate code and more easily integrate ORM technologies with other
Spring features, such as transaction management and caching.

Spring Data: This module provides a consistent and easy-to-use programming model for working with data
access technologies, including databases, NoSQL, and cloud-based data services. Spring Data provides a
wide range of features, including automatic CRUD (Create, Read, Update, Delete) operations, query
generation from method names, support for pagination and sorting, integration with Spring’s transaction
management, and more. Additionally, Spring Data provides support for common data access patterns, such as
repositories and data access objects (DAOs).

Spring Transaction: This module provides support for declarative transaction management in Spring
applications. Spring Transaction provides support for various transaction propagation and isolation levels,
allowing developers to manage transactions at different levels of granularity. Additionally, Spring
Transaction provides support for different transaction management strategies, such as using a JTA transaction
manager or a simple JDBC transaction manager.

Web

The Web area provides support for building web applications. It includes the following modules:

Spring MVC: This module provides a Model-View-Controller (MVC) framework for building web
applications. Spring MVC provides a range of features, including support for handling HTTP requests and
responses, form handling, data binding, validation, and more. It also provides support for different view
technologies, such as JSP (JavaServer Pages), Thymeleaf, and Velocity, allowing developers to choose the
view technology that best suits their needs.

Spring WebFlux: This module provides a reactive programming model for building web applications that
require high concurrency and scalability. Spring WebFlux provides support for building reactive web
applications using a range of technologies, such as Netty, Undertow, and Servlet 3.1+ containers. It also
provides a range of features, including support for reactive data access, reactive stream processing, and
reactive HTTP clients.
Spring Web Services: This module provides support for building SOAP-based and RESTful web services.
Spring Web Services provides support for generating WSDL (Web Services Description Language) from
Java classes, and for generating Java classes from WSDL. This allows developers to define the contract (i.e.,
the interface) of their web service using WSDL, and to generate the Java classes that implement the web
service from the WSDL.

Miscellaneous

The Miscellaneous area includes other modules that provide additional functionality, such as:

Spring Security: This module provides authentication and authorization features for Spring applications.
Spring Security provides a range of authorization mechanisms, such as role-based access control and
expression-based access control. It also provides support for securing different parts of the application using
different security configurations, allowing developers to apply fine-grained security policies.

Spring Integration: This module provides support for building message-driven and event-driven
architectures. Spring Integration provides a range of integration patterns, such as messaging, routing, and
transformation. It provides support for a range of messaging systems, such as JMS, AMQP, and Apache
Kafka. It also provides support for integrating with different protocols, such as FTP, HTTP, and TCP.

Spring Batch: This module provides support for batch processing and integration with enterprise systems.
Spring Batch provides a range of tools and utilities for building and managing batch processing applications,
such as support for testing and debugging batch jobs, logging and monitoring, and integration with other
Spring modules, such as Spring Data and Spring Integration.

Spring Cloud: This module provides support for building cloud-native applications using Spring
technologies. Spring Cloud provides a range of features for building cloud-native applications, such as service
discovery, configuration management, and load balancing. It provides support for integrating with different
cloud platforms, such as AWS and GCP, and for using different cloud-native technologies, such as containers
and serverless computing.

Overall, the Spring framework modules provide developers with a powerful set of tools to build robust,
scalable, and maintainable enterprise applications. The modular architecture of the Spring framework allows
developers to select only the necessary modules for their specific needs, reducing unnecessary overhead and
complexity in the application.

Dependency Injection in Spring


Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be
easy to manage and test the application. Dependency Injection makes our programming code loosely coupled. To
understand the DI better, Let's understand the Dependency Lookup (DL) first:

Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the
resource for example:

A obj = new AImpl();

In such way, we get the resource(instance of A class) directly by new keyword.

Another way is factory method:


2. A obj = A.getA();

This way, we get the resource (instance of A class) by calling the static factory method getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

Context ctx = new InitialContext();


Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");

There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.

Problems of Dependency Lookup

There are mainly two problems of dependency lookup.

o Tight coupling: The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform
a lot of modification in the code.
o Not easy for testing: This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the
information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such
case we write the code as:

s Employee{
dress address;

ployee(Address address){
.address=address;

lic void setAddress(Address address){


.address=address;

In such case, instance of Address class is provided by external source such as XML file either by constructor or setter
method.

Two ways to perform Dependency Injection in Spring framework


Spring framework provides two ways to inject dependency

o By Constructor
o By Setter method

What Is Inversion of Control?


Inversion of Control is a principle in software engineering which transfers the control of objects or portions of
a program to a container or framework. We most often use it in the context of object-oriented programming.
In contrast with traditional programming, in which our custom code makes calls to a library, IoC enables a
framework to take control of the flow of a program and make calls to our custom code. To enable this,
frameworks use abstractions with additional behavior built in.

If we want to add our own behavior, we need to extend the classes of the framework or plugin our own
classes.
The advantages of this architecture are:

 decoupling the execution of a task from its implementation


 making it easier to switch between different implementations
 greater modularity of a program
 greater ease in testing a program by isolating a component or mocking its dependencies, and allowing
components to communicate through contracts

We can achieve Inversion of Control through various mechanisms such as: Strategy design pattern, Service
Locator pattern, Factory pattern, and Dependency Injection (DI).

Dependency Injection by
Constructor Example
1. Dependency Injection by constructor
2. Injecting primitive and string-based values

We can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is


used for constructor injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values


Let's see the simple example to inject primitive and string-based values. We have created three
files here:

o Employee.java
o applicationContext.xml
o Test.java
Employee.java

It is a simple class containing two fields id and name. There are four constructors and one method
in this class.

package com.javatpoint;

public class Employee {


private int id;
private String name;

public Employee() {System.out.println("def cons");}

public Employee(int id) {this.id = id;}

public Employee(String name) { this.name = name;}

public Employee(int id, String name) {


this.id = id;
this.name = name;
}

void show(){
System.out.println(id+" "+name);
}

applicationContext.xml

We are providing the information into the bean by this file. The constructor-arg element invokes
the constructor. In such case, parameterized constructor of int type will be invoked. The value
attribute of constructor-arg element will assign the specified value. The type attribute specifies
that int parameter constructor will be invoked.

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="e" class="com.javatpoint.Employee">


<constructor-arg value="10" type="int"></constructor-arg>
</bean>

</beans>

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e"); //for retrieving a bean instance from the Spring container.
s.show();

}
}

Output:10 null

Injecting string-based values


If you don't specify the type attribute in the constructor-arg element, by default string type
constructor will be invoked.

....
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="10"></constructor-arg>
</bean>
....

If you change the bean element as given above, string parameter constructor will be invoked and
the output will be 0 10.

Output:0 10
You may also pass the string literal as following:

....
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

Output:0 Sonoo

You may pass integer literal and string both as following

....
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="10" type="int" ></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

Output:10 Sonoo

Bean Scopes in Java Spring

Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will
be instantiated, how long does that object live, and how many objects will be created
for that bean throughout. Basically, it controls the instance creation of the bean and it
is managed by the spring container.

Bean Scopes in Spring

The spring framework provides five scopes for a bean. We can use three of them only
in the context of web-aware Spring ApplicationContext and the rest of the two is
available for both IoC container and Spring-MVC container. The following are the
different scopes provided for a bean:

1. Singleton: Only one instance will be created for a single bean definition per Spring
IoC container and the same object will be shared for each request made for that
bean.
2. Prototype: A new instance will be created for a single bean definition every time a
request is made for that bean.
3. Request: A new instance will be created for a single bean definition every time an
HTTP request is made for that bean. But only valid in the context of a web-aware
Spring ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But
only valid in the context of a web-aware Spring ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP
Session. It is also only valid in the context of a web-aware Spring
ApplicationContext.

Let’s us see some of them in detail:

Singleton Scope:

If the scope is a singleton, then only one instance of that bean will be instantiated per
Spring IoC container and the same instance will be shared for each request. That is
when the scope of a bean is declared singleton, then whenever a new request is made
for that bean, spring IOC container first checks whether an instance of that bean is
already created or not. If it is already created, then the IOC container returns the same
instance otherwise it creates a new instance of that bean only at the first request. By
default, the scope of a bean is a singleton.
Let’s understand this scope with an example.

 Step1: Lets first create a bean (i.e.), the backbone of the application in the spring
framework.
Java

// Java program to illustrate a bean

// created in the spring framework

package bean;

public class HelloWorld {

public String name;

// Create a setter method to


// set the value passed by user

public void setName(String name)

this.name = name;

// Create a getter method so that

// the user can get the set value

public String getName()

return name;

 Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure
the bean defined above.
XML

<!DOCTYPE beans PUBLIC

"-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!--configure the bean HelloWorld.java

and declare its scope-->

< bean

id = "hw"

class= "bean.HelloWorld"
scope = "singleton" / >

</beans>

 Step 3: Finally, write a driver class “Client.java” to request the above bean.
Java

// Java program to illustrate

// the client to perform the

// request to the defined bean

package driver;

import org.springframework

.context.ApplicationContext;

import org.springframework

.context.support

.ClassPathXmlApplicationContext;

import bean.HelloWorld;

// Client Class to request the

// above defined bean

public class Client {

public static void main(String[] args)


{

// Load the Spring XML configuration

// file into IoC container

ApplicationContext ap = new ClassPathXmlApplicationContext(resources/spring.xml");

// Get the "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks1

= (HelloWorld)ap.getBean("hw");

// Set the name

Geeks1.setName("Geeks1");

System.out.println(

"Hello object (hello1)"

+ " Your name is: "

+ Geeks1.getName());

// Get another "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks2

= (HelloWorld)ap.getBean("hw");

System.out.println(

"Hello object (hello2)"

+ " Your name is: "


+ Geeks2.getName());

// Now compare the references to see

// whether they are pointing to the

// same object or different object

System.out.println("'Geeks1' and 'Geeks2'" + " are referring"+

"to the same object: " + (Geeks1 == Geeks2));

// Print the address of both

// object Geeks1 and Geeks2

System.out.println("Address of object Geeks1: "+ Geeks1);

System.out.println("Address of object Geeks2: "+ Geeks2);

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: Geeks1
'Geeks1' and 'Geeks2' are referring to the same object: true
Address of object Geeks1: bean.HelloWorld@627551fb
Address of object Geeks2: bean.HelloWorld@627551fb
 Explanation: When we call the getName() method by using the reference of
‘Geeks1’ and ‘Geeks2’, then we are getting the same outputs. This means that both
the reference is calling the getName() method of the same object. Furthermore,
when we are comparing the reference ‘Geeks1’ and ‘Geeks2’ then output is “true”
which means the same object is shared between ‘Geeks1’ and ‘Geeks2’. So it is
clear that a new instance of bean (HelloWorld) is created when we made the request
the first time and for each new request, the same object is being shared.
Prototype Scope:

If the scope is declared prototype, then spring IOC container will create a new instance of that
bean every time a request is made for that specific bean. A request can be made to the bean
instance either programmatically using getBean() method or by XML for Dependency Injection of
secondary type. Generally, we use the prototype scope for all beans that are stateful, while the
singleton scope is used for the stateless beans.
Let’s understand this scope with an example:

 Step 1: Let us first create a bean (i.e.), the backbone of the application in the spring
framework.

Java

// Java program to illustrate a bean

// created in the spring framework

package bean;

public class HelloWorld {

public String name;

// Create a setter method to

// set the value passed by user

public void setName(String name)

this.name = name;

// Create a getter method so that

// the user can get the set value


public String getName()

return name;

 Step 2: Now, we write a Spring XML configuration file “spring.xml” and configure the bean
defined above.

XML

<!DOCTYPE beans PUBLIC

"-//SPRING//DTD BEAN 2.0//EN"

"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

< beans>

<!--configure the bean HelloWorld.java

and declare its scope-->

< bean

id = "hw"

class = "bean.HelloWorld"

scope = "prototype" / >

</ beans>

 Step 3: Finally, write a driver class “Client.java” to request the above bean.

Java

// Java program to illustrate

// the client to perform the


// request to the defined bean

package driver;

import org.springframework

.context.ApplicationContext;

import org.springframework.context.support

.ClassPathXmlApplicationContext;

import bean.HelloWorld;

public class Client {

public static void main(String[] args)

// Load the Spring XML configuration

// file into IoC container

ApplicationContext ap

= new ClassPathXmlApplicationContext(

"resources/spring.xml");

// Get the "HelloWorld" bean object

// and call getName() method


HelloWorld Geeks1

= (HelloWorld)ap.getBean("hw");

// Set the name

Geeks1.setName("Geeks1");

System.out.println(

"Hello object (hello1)"

+ " Your name is: "

+ Geeks1.getName());

// Get another "HelloWorld" bean object

// and call getName() method

HelloWorld Geeks2

= (HelloWorld)ap.getBean("hw");

System.out.println(

"Hello object (hello2)"

+ "Your name is: "

+ Geeks2.getName());

// Now compare the references to see

// whether they are pointing to the

// same object or different object


System.out.println(

"'Geeks1' and 'Geeks2'"

+ "are referring "

+ "to the same object: "

+ (Geeks1 == Geeks2));

// Print the address of both

// object Geeks1 and Geeks2

System.out.println(

"Address of object Geeks1: "

+ Geeks1);

System.out.println(

"Address of object Geeks2: "

+ Geeks2);

 Output:
Hello object (hello1) Your name is: Geeks1
Hello object (hello2) Your name is: null
'Geeks1' and 'Geeks2' are referring to the same object: false
Address of object Geeks1: bean.HelloWorld@47ef968d
Address of object Geeks2: bean.HelloWorld@23e028a9
 Explanation: When we call getName() method by using the reference ‘Geeks1’ and ‘Geeks2’,
then we get different outputs that means both the reference is calling getName() method of a
different object. Furthermore, when we are comparing the reference ‘Geeks1’ and ‘Geeks2’
then output is “false” which means both references is referring to a different object. So it is
clear that a new instance of bean (HelloWorld) is being created at each request made for this
bean.

Difference between Singleton and Prototype


Singleton Prototype

Only one instance is created for a single bean definition per A new instance is created for a single bean definition
Spring IoC container every time a request is made for that bean.

Same object is shared for each request made for that bean. For each new request a new instance is created. i.e.
i.e. The same object is returned each time it is injected. A new object is created each time it is injected.

By default scope of a bean is singleton. So we don’t need to By default scope is not prototype so you have to
declare a bean as singleton explicitly. declare the scope of a bean as prototype explicitly.

While prototype scope is used for all beans that are


Singleton scope should be used for stateless beans.
stateful.

You might also like