0% found this document useful (0 votes)
3 views67 pages

Samarth Bhardwaj Report

This document is a training report submitted by Samarth Bhardwaj for the Bachelor of Technology degree in Computer Science Engineering, focusing on Java Fullstack Web Development. It outlines the importance of fullstack development, the tools and frameworks used, and provides a comprehensive overview of Java's capabilities in both backend and frontend development. The report includes chapters on setup, Java language fundamentals, object-oriented programming, and practical applications, culminating in a project walkthrough.
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)
3 views67 pages

Samarth Bhardwaj Report

This document is a training report submitted by Samarth Bhardwaj for the Bachelor of Technology degree in Computer Science Engineering, focusing on Java Fullstack Web Development. It outlines the importance of fullstack development, the tools and frameworks used, and provides a comprehensive overview of Java's capabilities in both backend and frontend development. The report includes chapters on setup, Java language fundamentals, object-oriented programming, and practical applications, culminating in a project walkthrough.
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/ 67

PYTHON

Training Report

submitted

in partial fulfilment

for the award of the Degree of

Bachelor of Technology

in

Department of Computer Science Engineering

(With Specialization In Computer Science & Engineering)

Supervisor: Submitted By:

Mrs. Amrata Pupneja Samarth Bhardwaj

Assistant Professor Roll No.22EMICS054

Department of Computer Science & Engineering


Modi Institute of Technology
Rajasthan Technical University
September, 2024 -2025
CANDIDATE’S DECLARATION

I hereby declare that the work, which is being presented in the Training Report, entitled
“Python” in partial fulfillment for the award of Degree of “Bachelor of Technology” in
Department of Computer Engineering with specialization in Computer Science and
Engineering, and submitted to the Department of Computer Science & Engineering, Modi
Institute of Technology, Rajasthan Technical University is a record of my own investigations
carried under the Guidance of Assistant Professor, Amrata Pupneja , Dept. of Computer Science
&Engineering.

I have not submitted the matter presented in this Training Report anywhere for the award of any
other Degree.

Samarth Bhardwaj

Computer Science and Engineering

Roll No.: 22EMICS054

Modi Institute of Technology, Kota

Counter Signed By:

Supervisor:

Mrs. Amrata Pupneja

Assistant Professor, CSE Dept.

i
Acknowledgment
I would also like to give my special thanks to the Principal, Dr. Vikas Soni, Modi
Institute of Technology, for providing the opportunity to me to undertake this work.

I would like to thank my guide Assistant Professor, Amrata Pupneja, for their valuable guidance.
I appreciate their presence for all the discussions, suggestions and their time whenever I needed
them.

Two Persons who deserves a First and Foremost mention are my Mother Mrs. Renu
mishra and My Father Mr. Rupesh Kumar Sharma, whose strong belief in my abilities and
moral support uplifted my spirits. Without their encouragement, I would have never imagined to
achieve this height in my career.

I cannot forget to mention the name of my best friends for her relentless help and
motivation all through.

Finally, I would like to thank everybody who was important to the successful realization
of this report, as well as expressing my apology that I could not mention them personally one by
one.

Samarth Bhardwaj

Computer Science and Engineering

ROLL No.: 22EMICS054

Modi Institute of Technology

ii
CERTIFICATE

This is to certify that this Training Report entitled “Java Full-Stack web development” has been
successfully carried out by Samarth Bhardwaj (Enrolment No.: 22EMICS054 ), under my
supervision and guidance, in partial fulfilment of the requirement for the award of Bachelor of
Technology Degree in Computer Science & Engineering from Modi Institute of Technology, Kota.

Supervisor:

Mrs. Amrata Pupneja

Assistant Professor, CSE Dept

Place: Kota

Date:

iii
iv
TABLE OF CONTENT
Title PageNo.
Abstract 1
CHAPTER 1. INTRODUCTION
1.1 Overview of java fullstack web development 2
1.2 Importance of Fullstack Development in Modern Industry 2
1.3 Tools and Frameworks Commonly Used 2
1.4 History 3

CHAPTER 2. DOWNLOADING & SETUP


2.1 Setting Up the Development Environment 4
2.2 Installing JDK 5
2.3 Installing Intellij IDEA 6
2.4 JAVA Code Execution 6

CHAPTER 3. JAVA LANGUAGE FUNDAMENTALS

3.1 Tokens 10
3.1.1 Keywords 10
3.1.2 Identifiers 10
3.1.3 Variables 10
3.1.4 Data types 11
3.1.5 Operators 13
3.2 Conditional Statements 13
3. 3.Loops
14
3.3.1 While loop 14
3.3.2Do/while loop 15
3.3.3 For loop 15

v
3.4 Arrays 16
3.4.1 Multidimensional Arrays 16
3.5 Methods 16
3.6 Return Values 18
CHAPTER 4. JAVA OOP (OBJECT ORIENTED PROGRAMING)
4.1 Definition 19
4.2 Object-oriented programming Advantages 19

4.3 Object 19
4.4 Class 19
4.5 Polymorphism 20
4.6 Abstraction 20
4.7 Inheritance in java 20
4.7.1 Types of Inheritance 21
4.8 Abstraction in Java 21
4.8.1 Abstract class in Java 21
4.9 Interface in Java 22
4.10 Polymorphism 23
4.11Method Overloading 24
4.11.1 Advantage of method overloading 24
4.12 Method overriding 25
4.13 Encapsulation 26

CHAPTER 5 : JAVA PACKAGE


5.1 Definition 28
5.2 Access Modifiers in Java 28

CHAPTER 6 : EXCEPTION HANDLING IN JAVA


6.1 Defination 30

vi
6.1.1 What is Exception in Java? 30
6.1.2 What is Exception Handling in Java 30

6.2 Types of Exception 30

CHAPTER 7: RDBMS (Relational database concepts)


7.1 Definition 32
7.2 Database tables 32

CHAPTER 8 : SQL AND DATABASE QUERIES


8.1 Definition 35
8.2 SQL(STRUCTURED QUERY LANGUAGE) 35
8.2.1 What is a Database 36
8.2.2 Why to Learn SQL? 36
8.2.3 Application of SQL 36
8.3 JDBC 37
8.3.1 Why Should we use JDBC? 38

CHAPTER 9: FRONTEND 39
9.1 HTML 39
9.2 Java Script 39
9.2.1 Application of Java Script
CHAPTER 10: BACKEND 41
10.1 Servlets 41
10.2 Hibernate 42
10.2.1 What is JPA? 42
10.2.2 Advantages of Hibernate Framework 42

vii
10.3 Spring Boot 43
10.3.1 Why should we use Spring Boot Framework? 44
CHAPTER 11: JAVA CHAT APPLICATION 45
11.1 Chat Server 45
11.2 Chat Client 47
11.3 Chat App GUI 48
CONCLUSION
FUTURE SCOPE
REFERENCE

viii
LIST OF FIGURES

Figure Title Page No..

Fig.2.1 Downloading page of python 4


Fig.2.2 Run python software 5
Fig.2.3 completion of installation 5
Fig.2.4 Diagram of execution 6
Fig.2.5 Code for hello program 7
Fig.2.6 result of hello program 7
Fig.8.1 File handing Example 40
Fig.8.2 Result of example 40
Fig.9.1 Code (a) 41
Fig.9.2 Code (b) 41
Fig.9.3 Code (c) 42
Fig.9.4 Weather app 42

ix
LIST OF TABLES

Table Title Page No.

Table .3.1 keyword in python 8


Table .3.2 if else statement 12
Table .3.3 List function 15
Table .3.4 List methods 16
Table .3.5 Dictionary function 18
Table .3.6 String methods 22
Table .5.1 Math function 29
Table .8.1 Access mode 38

x
ABSTRACT
The evolution of web development has led to the demand for professionals skilled in both frontend
and backend technologies, commonly referred to as fullstack developers. This report explores the
realm of Java Fullstack Web Development, a robust and versatile approach to building scalable,
efficient, and user-friendly web applications. Java, with its "Write Once, Run Anywhere" capability,
forms the backbone of this development stack, complemented by powerful frameworks such as
Spring Boot for backend development and modern frontend frameworks like Angular or React.

The objective of this report is to provide a comprehensive understanding of the tools, technologies,
and methodologies involved in Java Fullstack Web Development. Starting with an overview of Java's
history, its unique features, and its role in enterprise solutions, the report delves into the essentials of
setting up a development environment. It explains the integration of Java technologies with databases,
APIs, and frontend frameworks to create dynamic, end-to-end solutions.

The backend section focuses on Spring Boot, a framework known for simplifying microservice
architecture and REST API development, and Hibernate, which streamlines database interactions
using Object-Relational Mapping (ORM). On the frontend, frameworks like Angular and React are
discussed for their ability to build responsive and interactive user interfaces. Together, these
technologies enable developers to bridge the gap between user experience and server-side
functionality.

This report also covers advanced topics such as deploying fullstack applications on cloud platforms,
integrating security measures, optimizing performance, and implementing Continuous
Integration/Continuous Deployment (CI/CD) pipelines. Real-world examples and a project
walkthrough provide practical insights into building Java-based fullstack applications from scratch.

Java Fullstack Web Development stands out for its ability to handle the complexities of modern web
applications while ensuring cross-platform compatibility, performance, and maintainability. This
report aims to guide developers and enthusiasts through every aspect of this development stack,
enabling them to build scalable, secure, and user-centric web solutions for a variety of industries.

1
CHAPTER 1

INTRODUCTION

1.1 Overview of Java Fullstack Web Development:-

Java Fullstack Web Development involves designing and implementing software applications
that encompass both backend and frontend functionalities. The backend focuses on server-
side logic, including API creation, database management, and application security, while the
frontend deals with user interface design, interaction, and data visualization. Java's versatility,
combined with its vast library support, makes it a preferred choice for fullstack development.
Tools like Spring Boot simplify backend development, while modern frontend frameworks
like Angular and React provide a rich user experience.

1.2 Importance of Fullstack Development in Modern Industry:-

Fullstack developers are increasingly in demand as they possess the ability to handle both
sides of web application development. Their skillset contributes to:

 Faster Development Cycles: One developer can manage multiple layers of an


application, reducing coordination overhead.

 Cost Efficiency: Companies save resources by hiring fewer specialists.

 Adaptability: Developers gain exposure to a variety of technologies, making them


more versatile and valuable to organizations.

Enhanced Collaboration: Fullstack knowledge bridges the gap between frontend and
backend teams, fostering better communication and integration.

1.3 Tools and Frameworks Commonly Used:-

The Java fullstack ecosystem includes several tools and frameworks designed to
streamline development:

 Backend Frameworks: Spring Boot for microservices, Hibernate for ORM,


JPA for database interactions.

2
 Frontend Technologies: Angular and React for dynamic, responsive web
interfaces.

 Database Systems: MySQL, PostgreSQL for relational data; MongoDB for


NoSQL.

 Version Control: Git for source code management and collaboration

1.4 History:-

Java, one of the most popular programming languages today, was created by
James Gosling and his team at Sun Microsystems in 1995. Initially designed as a
language for interactive television, Java quickly evolved into a robust, platform-
independent programming language. Its motto, "Write Once, Run Anywhere"
(WORA), enabled applications written in Java to run on any device equipped
with a Java Virtual Machine (JVM).

Over the years, Java has undergone several upgrades, each adding new features
to keep up with modern programming trends. Major milestones include:

 Java 1.0 (1995): The first version, which focused on applet development and
basic object-oriented programming.

 Java 2 (1998): Introduced the Swing library for GUI development and
improvements to collections.

 Java SE 8 (2014): Brought in lambdas, streams, and functional programming


capabilities.

 Java SE 11 (2018) and beyond: Focused on modularity, security, and


performance enhancements, making it a strong contender for enterprise-level
development.

3
CHAPTER 2

INSTALLATION AND SETUP

2.1 Setting Up the Development Environment:-

Before starting any development, it is crucial to set up a well-structured environment:

 Install Java Development Kit (JDK) to enable Java compilation and execution.
Ensure compatibility with your IDE.

 Recommended IDEs include IntelliJ IDEA, Eclipse, and Visual Studio Code with
Java extensions for seamless coding.

( Java Downloads | Oracle )( Download IntelliJ IDEA – The Leading Java and Kotlin IDE )

Fig:2.1: downloading page of JDK

Now after downloading JDK , we will install IntelliJ IDEA,

( Download IntelliJ IDEA – The Leading Java and Kotlin IDE )

Fig:2.1: downloading page of JDK

4
2.2 Installing JDK:-

Once you have downloaded the Java development kit, simply navigate to the download
location on your computer, double clicking the file and pressing Run when the dialog box
pops up.

Fig:2.2: run JDK setup file

Now that you have completed the installation process, click on “close”.

Fig:2.3.completion of installation

5
2.3 Installing IntelliJ IDEA:-

Once you have downloaded the IntelliJ IDEA, simply navigate to the download location on
your computer, double clicking the file and pressing Run when the dialog box pops up.

Fig:2.2: run Intellij IDEA setup file

After pressing next chose the location of the file then again press next.

Now that you have completed the installation process, click on “close”.

2.4 JAVA Code Execution:-

Java programs follow a structured execution process to ensure platform independence and
performance:

1. Writing Code: Developers write source code in .java files using text editors or IDEs
like IntelliJ IDEA or Eclipse.

2. Compilation: The Java Compiler (javac) converts the source code into platform-
independent bytecode, stored in .class files.

3. Class Loading: The JVM's ClassLoader loads the required .class files into memory,
handling core, extension, and application-level classes.

4. Bytecode Verification: The JVM verifies the bytecode for security and correctness,
preventing execution of harmful code.

6
5. Execution: The JVM uses the Just-In-Time (JIT) compiler to translate bytecode into
machine code at runtime, ensuring efficient execution on any platform with a JVM.

This process enables Java's "Write Once, Run Anywhere" capability.

Fi
g:2.4 Diagram of execution

7
Eg:

Fig:2.5. Code for hello program

Execution Steps:

1. Writing the Code:

o The program is written in a file named HelloWorld.java since the class


name is” HelloWorld”.

2. Compilation:

o The Java Compiler (javac) compiles the source code into bytecode.

o Command:

Fig:2.6. Command for executing a file

o Output: A file named HelloWorld.class containing the bytecode is created.


3. Class Loading:

 The Java Virtual Machine (JVM) loads the HelloWorld.class file into memory
using its ClassLoader.

8
4. Bytecode Verification:

 The JVM verifies the bytecode to ensure it is valid and does not violate Java’s
security constraints.

5. Execution:

 The JVM invokes the main method in the HelloWorld class.

 The System.out.println("Hello, World!") statement is executed, printing


"Hello, World!" to the console.

6. Output:

 The console displays:

Fig:2.6. result of hello program

9
CHAPTER 3

JAVA LANGUAGE FUNDAMENTALS

3.1 Tokens:-

In Java, a token is the smallest element of a program that is meaningful to the compiler. Java
source code is composed of a sequence of these tokens, which are categorized as follows:

3.1.1 Keywords:-

in Java are reserved words that have predefined meanings and serve specific purposes in a
program. These words cannot be used as identifiers (such as variable names, class names, or
method names). Keywords are fundamental to defining the structure and syntax of Java
programs.

3.1.2 Identifiers:-

• Java identifiers are names given to variables, methods, classes, and other program elements
in Java programming language.

• Java identifiers must start with a letter, a currency character "$", or an underscore "_". The
first character cannot be a digit.

• Java identifiers can contain letters, digits, underscores, and currency characters. The name
can be of any length.

• Java is case-sensitive, which means that "name" and "Name" are two different identifiers.

• Identifiers should not be a Java keyword, which are reserved words in Java that have a
specific meaning and cannot be used as an identifier.

• Examples of valid identifiers in Java are "myVariable", "_count", "MAX_VALUE",


"calculateSum", "MyClass"..

3.1.3 Variables :-
 Variables are containers for storing data values.

10
 In Java, there are different types of variables, for example: String - stores text, such as
"Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or 19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false.
 To create a variable, you must specify the type and assign it a value.
Syntax: type variableName = value;
 All Java variables must be identified with unique names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
 The general rules for naming variables are:
Names can contain letters, digits, underscores, and dollar signs
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain whitespace
Names can also begin with $ and _ .
Names are case sensitive ("myVar" and "myvar" are different variables).
Reserved words (like Java keywords, such as int or boolean) cannot be used as names.

3.1.3 Data Types:-


 Data types are divided into two groups:

Primitive data types –

includes byte, short, int, long, float, double, boolean and char.

Non-primitive data types –

such as String, Arrays and Classes.

 Primitive number types are divided into two groups:

11
Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should use,
depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more
decimals. There are two types: float and double.

 Integer Types:
The byte data type can store whole numbers from -128 to 127.
This can be used instead of int or other integer types to save memory
when you are certain that the value will be within -128 and 127.
The short data type can store whole numbers from -32768 to 32767.
The int data type can store whole numbers from -2147483648 to 2147483647.
In general, the int data type is the preferred data type when we create variables with a
numeric value.
The long data type can store whole numbers from - 9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L".
 Floating Point Types:
The float and double data types can store fractional numbers. Note that you should end
the value with an "f" for floats and "d" for doubles.
A floating point number can also be a scientific number with an "e" to indicate the power
of 10.
• Type casting is when you assign a value of one primitive data type to another type.
• In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size byte -
> short -> char -> int -> long -> float -> double
Example:
int myInt = 9;
double myDouble = myInt;
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Example:

12
double myDouble = 9.78d;
int myInt = (int) myDouble;

13
3.1.4 Operators :
 Operators are used to perform operations on variables and values.
 Java divides the operators into the following groups: Arithmetic operators

Assignment operators

Comparison operators

Logical operators

Bitwise operators

3.1.5 Conditional Statements:-

 Java has the following conditional statements:


Use if to specify a block of code to be executed, if a specified condition is true.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
Use else to specify a block of code to be executed, if the same condition is false.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Use else if to specify a new condition to test, if the first condition is false.

if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {

14
// block of code to be executed if the condition1 is false and condition2 is
false
}
Use switch to specify many alternative blocks of code to be executed.
Syntax:
switch(expression) { case
x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional.

3.2 Loops:-

• Loops can execute a block of code as long as a specified condition is reached.

• Loops are handy because they save time, reduce errors, and they make code more
readable.

While Loop:

The while loop loops through a block of code as long as a specified condition is true.
Syntax:

while (condition) {

// code block to be executed

15
}

Do/While Loop:

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.

Syntax:

do {

// code block to be executed

while(condition);

For Loop:

When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop.

Syntax:

for (statement 1; statement 2; statement 3)

{ // code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

16
3.2 Arrays:-
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
 To declare an array, define the variable type with square brackets: Example: String[]
cars;
 You can access an array element by referring to the index number.
 This statement accesses the value of the first element in cars:
Example:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
// Outputs Volvo
3.2.1 Multidimensional Arrays:
 A multidimensional array is an array of arrays.
 Multidimensional arrays are useful when you want to store data as a tabular form,
like a table with rows and columns.
 To create a two-dimensional array, add each array within its own set of curly braces.
Example:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; System.out.println(myNumbers[1]


[2]); // Outputs 7

3.3 Methods:

A method is a block of code which only runs when it is called.

• You can pass data, known as parameters, into a method.

• Methods are used to perform certain actions, and they are also known as functions.

• Why use methods? To reuse code: define the code once, and use it many times.

• A method must be declared within a class. It is defined with the name of the method,
followed by parentheses ( ).

Example:

public class Main {

17
static void myMethod() {

// code to be executed

}}

myMethod() is the name of the method.

static means that the method belongs to the Main class and not an object of the Main
class. You will learn more about objects and how to access methods through objects.
void means that this method does not have a return value.

 To call a method in Java, write the method's name followed by two parentheses ()
and a semicolon;
 Information can be passed to methods as parameter. Parameters act as variables
inside the method.
 Parameters are specified after the method name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma.

• The following example has a method that takes a String called fname as parameter. When
the method is called, we pass along a first name, which is used inside the method to print the
full name:

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

18
}

3.3 Return Values:-


The void keyword, used in the examples above, indicates that the method should not return a
value. If you want the method to return a value, you can use a primitive data type (such as int,
char, etc.) instead of void, and use the return keyword inside the method:
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}

19
CHAPTER 4

JAVA OOP (OBJECT ORIENTED PROGRAMING)

4.1 Definition:-

 OOP stands for Object-Oriented Programming.


 Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating objects
that contain both data and methods.

4.2 Object-oriented programming Advantages:-

 OOP is faster and easier to execute.


 OOP provides a clear structure for the programs.
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug.
 OOP makes it possible to create full reusable applications with less code and shorter
development time
4.2 Object:-
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be defined
as an instance of a class. An object contains an address and takes up some space in
memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example:
A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
4.3 Class:-
Collection of objects is called class. It is a logical entity. A class can also be defined
as a blueprint from which you can create an individual object.
Class doesn't consume any space. Inheritance:

20
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
4.5 Polymorphism:-
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc
4.6 Abstraction:-
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing. In Java, we use abstract class and interface
to achieve abstraction. Encapsulation Binding (or wrapping) code and data together into a
single unit are known as encapsulation. For example, a capsule, it is wrapped with different
medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
4.7Inheritance in Java:-
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent- child
relationship.
 Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. •
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class. •
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class. •

21
 Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
4.7.1 Types of Inheritance:
 Single Inheritance
 Multiple Inheritance
 Multi-Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
4.8 Abstraction in Java:-

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery. Abstraction lets you focus on what the object
does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
4.8.1 Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.

22
• It cannot be instantiated.
• It can have constructors and static methods also.
• It can have final methods which will force the subclass not to change the body of the
method.
Example: abstract
class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new
Honda4(); obj.run();
}
}

4.9 Interface in Java:

• An interface in Java is a blueprint of a class. It has static constants and abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not 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.
• It cannot be instantiated just like the abstract class.
• Since Java 8, we can have default and static methods in an interface. • Since Java 9, we
can have private methods in an interface.
• There are mainly three reasons to use interface. They are given below. It is used to
achieve abstraction. By interface, we can support the functionality of multiple
inheritance. It can be used to achieve loose coupling.
• An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the fields

23
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.
Syntax:
Interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
4.10 Polymorphism:-
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods
from another class. Polymorphism uses those methods to perform different tasks. This
allows us to perform a single action in different ways. For example, think of a superclass
called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs,
Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig
oinks, and the cat meows, etc.):

Example:

class Animal {

public void animalSound() { System.out.println("The

animal makes a sound");

class Pig extends Animal { public void

animalSound() { System.out.println("The pig

says: wee wee");

24
}

class Dog extends Animal { public void

animalSound() { System.out.println("The dog

says: bow wow");

4.11 Method Overloading:-

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

4.11 .1 Advantage of method overloading

Methodoverloading increases the readability of the program.Different ways to overload the


method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Example:

class Adder{

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

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

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11))

; System.out.println(Adder.add(11,11,11));

}}

4.12 Method Overriding:-

If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

oMethod overriding is used to provide the specific implementation of a

method which is already provided by its superclass.

oMethod overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class

2. The method must have the same parameter as in the parent class.

3. There must be an IS-A relationship (inheritance).

Example:

class Vehicle{

26
void run(){System.out.println

("Vehicle is running");}

class Bike extends Vehicle{

public static void main(String args[]){

Bike obj = new Bike();

obj.run();

4.13 Encapsulation:-

Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class. Advantage of
Encapsulation in Java

By providing only a setter or getter method, you can make the class read-only or write-only.
In other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id which
should be greater than 100 only, you can write the logic inside the setter method. You can
write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

27
The standard IDE's are providing the facility to generate the getters and setters.

So, it is easy and fast to create an encapsulated class in Java.

28
CHAPTER 5

JAVA PACKAGE

5.1 Definition:-

A java package is a group of similar types of classes, interfaces and sub- packages.Package in
java can be categorized in two form, built-in package and user- defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package:

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision. There are three ways to access the package from
outside the package

1. import package.*;
2. import package.classname;
3. fully qualified name.

5.2 Access Modifiers in Java:

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it. There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

29
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc

30
CHAPTER 6

Exception Handling in Java

6.1 Definition:-

The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

6.1.1 What is Exception in Java?

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

6.1.2 What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc. The core
advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.

6.2 Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

1. Checked Exception

2. Unchecked Exception

3. Error

1. The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException,
etc. Checked exceptions are checked at compile-time.

31
2. The classes that inherit the RuntimeException are known as unchecked exceptions.
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3. Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Java provides five keywords that are used to handle the exception. •

 The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally. •
 The “catch” block is used to handle the exception. It must be preceded by try block which
means we can’t use catch block alone. •
 The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not. •
 The “throw” keyword is used to throw an exception. •
 The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Example:
public class JavaExceptionExample{
public static void main(String args[]){
try{
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);
} System.out.println("rest of the code...");
}}

32
CHAPTER 7

RDBMS (Relational database concepts)

7.1 Definition:-

A relational database management system (RDBMS) stores and retrieves data that is
represented in tables. A relational database consists of a collection of tables that store
interrelated data.

This section introduces some of the terms and concepts that are important in talking about
relational databases.

7.2 Database tables

In a relational database, all data is held in tables, which are made up of rows and columns.
Each table has one or more columns, and each column is assigned a specific datatype, such
as an integer number, a sequence of characters (for text), or a date. Each row in the table has a
value for each column.

A typical fragment of a table containing employee information may look as follows:

emp_ID emp_lname emp_fname emp_phone

1 Hu Zh 10
0 on an 96
0 g g
5
7

10693 Donaldson Anne 7821

The tables of a relational database have some important characteristics:

33
 There is no significance to the order of the columns or rows.
 Each row contains one and only one value for each column.
 Each value for a given column has the same type.

The following table lists some of the formal and informal relational database terms describing
tables and their contents, together with their equivalent in other nonrelational databases. This
manual uses the informal terms.

Formal Informal Equivalent


relationa relational nonrelational
l term term term

Relation Table File

Attribute Column Field

Tuple Row Record

When you are designing your database, make sure that each table in the database holds
information about a specific thing, such as employees, products, or customers.

By designing a database this way, you can set up a structure that eliminates redundancy and
inconsistencies. For example, both the sales and accounts payable departments may look up
information about customers. In a relational database, the information about customers is
entered only once, in a table that both departments can access.

A relational database is a set of related tables. You use primary and foreign keys to describe
relationships between the information in different tables. Primary and foreign keys Primary
and foreign keys define the relational structure of a database. These keys enable each row in
the database tables to be identified, and define the relationships between the tables.

Tables have a primary key

34
All tables in a relational database should have a primary key. The primary key is a column,
or set of columns, that allows each row in the table to be uniquely identified. No two rows in
a table with a primary key can have the same primary key value.

If no primary key is assigned, all the columns together become the primary key. It is good
practice to keep your primary key for each table as compact as possible.

Examples:

In a table holding information about employees, the primary key may be an ID number
assigned to each employee.

In the sample database, the table of sales order items has the following columns:

 An order number, identifying the order the item is part of


 A line number, identifying each item on any order
 A product ID, identifying the product being ordered
 A quantity, showing how many items were ordered
 A ship date, showing when the order was shipped

To find the name of a particular employee's department, there is no need to put the name of
the employee's department into the employee table. Instead, the employee table contains a
column holding the department ID of the employee's department. This is called a foreign key
to the department table. A foreign key references a particular row in the table containing the
corresponding primary key. In this example, the employee table (which contains the foreign
key in the relationship) is called the foreign table or referencing table. The department table
(which contains the referenced primary key) is called the primary table or the referenced
table.

35
CHAPTER 8

SQL AND DATABASE QUERIES

8.1 QUERIES:-

Retrieve data from a database using the SELECT statement. The basic query operations in a
relational system are projection, restriction, and join. The SELECT statement implements all
of these operations.

A projection is a subset of the columns in a table. A restriction (also called selection) is a


subset of the rows in a table, based on some conditions. For example, the following SELECT
statement retrieves the names and prices of all products that cost more than $15:

SELECT name,

unit_price FROM product

WHERE unit_price > 15

This query uses both a restriction (WHERE unit_price > 15) and a projection (SELECT
name, unit_price)

A JOIN links the rows in two or more tables by comparing the values in key columns and
returning rows that have matching values. For example, you may want to select the item
identification numbers and product names for all items for which more than a dozen has been
shipped: SELECT sales_order_items.id, product.name

FROM product KEY JOIN

sales_order_items WHERE

sales_order_items.quantity > 12

The product table and the sales_order_items table are joined together based on the foreign
key relationships between them.

8.2 SQL(STRUCTURED QUERY LANGUAGE):-

36
SQL is a standard database language used to access and manipulate data in databases. SQL
stands for Structured Query Language. SQL was developed by IBM Computer Scientists in
the 1970s. By executing queries SQL can create, update, delete, and retrieve data in databases
like MySQL, Oracle, PostgreSQL, etc. Overall SQL is a query language that communicates
with databases.

8.2.1 What is a Database?

Data is the new fuel of this world but only data is unorganized information, so to organize
that data we make a database. A database is the organized collection of structured data which
is usually controlled by a database management system (DBMS). Databases help us with
easily storing, accessing, and manipulating data held on a computer.

8.2.2 Why to learn SQL?

 SQL helps you to easily get information from data at high efficiency. To manipulate
the data in databases like Create, Read, Edit, and delete we use SQL queries. Users
can interact with data stored in relational database management systems. Anyone who
knows the English language can easily write SQL queries. Some of the key features of
SQL are given below:
 Without a lot of coding knowledge we can manage a database with SQL. ▪ SQL
works with database systems from Oracle, IBM, Microsoft, etc.
 Simple and easy to learn.
 SQL is ANSI and ISO standard language for database manipulations.
 SQL retrieves large amounts of data very fast.

8.2.3 Applications of SQL

In data-driven industries where managing databases is very important in regular, Here are
some important SQL applications.
 To support client/server architecture, software engineers use SQL to establish the
connection between back-end and front-end. •
 SQL can also be used in the 3-tier architecture of a client, an application server, and a
database. •

37
 SQL is used as a Data Definition Language(DDL) in which we can independently create a
database, define the structure, use it, and discard it when its work is done. •
 SQL is used as a Data Manipulation Language(DML) in which we can enter data, modify
data, extracting data. •
 SQL is used as a Data Control Language(DCL) it specifies how we can protect our
database against corruption and misuse.

8.3 JDBC

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

 JDBC-ODBC Bridge Driver, •


 Native Driver,
 Network Protocol Driver, and
 Thin Driver
 We have discussed the above four drivers in the next chapter.
 We can use JDBC API to access tabular data stored in any relational database. By the help
of JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

Fig:9.3 Diagram of execution

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:

38
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
A list of popular classes of JDBC API are given below:
 DriverManager class
 Blob class
 Clob class
 Types class

8.3.1 Why Should We Use JDBC

 Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
 We can use JDBC API to handle database using Java program and can perform the following
activities:
 Connect to the database
 Execute queries and update statements to the database
 Retrieve the result received from the database.

39
CHAPTER 9

Frontend

9.1 HTML:-

 HTML is an acronym which stands for Hyper Text Markup Language which is used
for creating web pages and web applications. Let's see what is meant by Hypertext
Markup Language, and Web page.
 Hyper Text: HyperText simply means "Text within Text." A text has a link within it,
is a hypertext. Whenever you click on a link which brings you to a new webpage, you
have clicked on a hypertext. HyperText is a way to link two or more web pages
(HTML documents) with each other.
 Markup language: A markup language is a computer language that is used to apply
layout and formatting conventions to a text document. Markup language makes text
more interactive and dynamic. It can turn text into images, tables, links, etc.
 Web Page: A web page is a document which is commonly written in HTML and
translated by a web browser. A web page can be identified by entering an URL. A
Web page can be of the static or dynamic type. With the help of HTML only, we can
create static web pages.
 Hence, HTML is a markup language which is used for creating attractive web pages
with the help of styling, and which looks in a nice format on a web browser. An
HTML document is made of many HTML tags and each HTML tag contains different
content.
9.2 Java script:-
 JavaScript (js) is a light-weight object-oriented programming language which is used
by several websites for scripting the webpages. It is an interpreted, full-fledged
programming language that enables dynamic interactivity on websites when applied
to an HTML document. It was introduced in the year 1995 for adding programs to the
webpages in the Netscape Navigator browser. Since then, it has been adopted by all
other graphical web browsers. With JavaScript, users can build modern web
applications to interact directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and simplicity.

40
 Although, JavaScript has no connectivity with Java programming language. The name
was suggested and provided in the times when Java was gaining popularity in the market.
In addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript
as their scripting and query language.
Application of JavaScript
 JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
 Displaying clocks etc.
 JavaScript is used to create interactive websites. It is mainly used for: Client-side
validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),.

41
CHAPTER 10

BACKEND

10.1 Servlets

 Servlet technology is used to create a web application (resides at server side and generates
a dynamic web page).
 Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology. We
have discussed these disadvantages below.
 There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

Servlet can be described in many ways, depending on the context.

 Servlet is a technology which is used to create a web application.


 Servlet is an API that provides many interfaces and classes including documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a dynamic web page.

42
Fig10.1 Servlet flow

10.2 Hibernate:-

 Hibernate is a Java framework that simplifies the development of Java application to


interact with the database. It is an open source, lightweight, ORM (Object Relational
Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API)
for data persistence.
ORM Tool
 An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.

 The ORM tool internally uses the JDBC API to interact with the database.

10.2.1 What is JPA?


 Java Persistence API (JPA) is a Java specification that provides certain functionality
and standard to ORM tools. The javax.persistence package contains the JPA classes
and interfaces.
10.2.2 Advantages of Hibernate Framework
 Following are the advantages of hibernate framework: Open Source and Lightweight ▪
Hibernate framework is open source under the LGPL license and lightweight. Fast
Performance
 The performance of hibernate framework is fast because cache is internally used in
hibernate framework. There are two types of cache in hibernate framework first level
cache and second level cache. First level cache is enabled by default. Database
Independent Query

43
 HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries.
Before Hibernate, if database is changed for the project, we need to change the SQL
query as well that leads to the maintenance problem. Automatic Table Creation
 Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually. Simplifies
Complex Join
 Fetching data from multiple tables is easy in hibernate framework. Provides Query
Statistics and Database Status
 Hibernate supports Query cache and provide statistics about query and database status.

10.3 Spring Boot :-

 Spring Boot Tutorial provides basic and advanced concepts of Spring Framework.
Our Spring Boot Tutorial is designed for beginners and professionals both.
 Spring Boot is a Spring module that provides the RAD (Rapid Application
Development) feature to the Spring framework.
 Our Spring Boot Tutorial includes all topics of Spring Boot such, as features, project,
maven project, starter project wizard, Spring Initializr, CLI, applications, annotations,
dependency management, properties, starters, Actuator, JPA, JDBC, etc.
 Spring Boot is a project that is built on the top of the Spring Framework. It provides
an easier and faster way to set up, configure, and run both simple and web-based
applications.
 It is a Spring module that provides the RAD (Rapid Application Development)
feature to the Spring Framework. It is used to create a stand-alone Spring-based
application that you can just run because it needs minimal Spring configuration

44
 In short, Spring Boot is the combination of Spring Framework and Embedded Servers.
 In Spring Boot, there is no requirement for XML configuration (deployment descriptor).
It uses convention over configuration software design paradigm that means it decreases
the effort of the developer.
 We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java applications.

10.3.1 Why should we use Spring Boot Framework?

 We should use Spring Boot Framework because:


 The dependency injection approach is used in Spring Boot.
 It contains powerful database transaction management capabilities.
 It simplifies integration with other Java frameworks like JPA/Hibernate ORM, Struts, etc.
▪ It reduces the cost and development time of the application.
 Along with the Spring Boot Framework, many other Spring sister projects help to build
applications addressing modern business needs. There are the following Spring sister
projects are as follows:
 Spring Data: It simplifies data access from the relational and NoSQL databases.
 Spring Batch: It provides powerful batch processing.
 Spring Security: It is a security framework that provides robust security to applications.
 Spring Social: It supports integration with social networking like LinkedIn.
 Spring Integration: It is an implementation of Enterprise Integration Patterns. It facilitates
integration with other enterprise applications using lightweight messaging and declarative
adapters. Conclusion In conclusion, a Java Full Stack Developer requires a diverse range
of technical and soft skills to develop and maintain web-based applications. They need to
be proficient in both front-end and back-end development, understand security protocols,
testing and debugging methodologies, design patterns, cloud technologies, and be
customer-focused.

45
CHAPTER 11

JAVA CHAT APPLICATION

11.1 CHAT SERVER :-

import java.io.*;

import java.net.*;

import java.util.*;

public class ChatServer {

private static List<ClientHandler> clients = new ArrayList<>();

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

ServerSocket serverSocket = new ServerSocket(5000);

System.out.println("Server started. Waiting for clients...");

while (true) {

Socket clientSocket = serverSocket.accept();

System.out.println("Client connected: " + clientSocket);

ClientHandler clientThread = new ClientHandler(clientSocket, clients);


clients.add(clientThread); new Thread(clientThread).start();

}}}

class ClientHandler implements Runnable {

private Socket clientSocket; private List<ClientHandler> clients;

private PrintWriter out; private BufferedReader in;

46
public ClientHandler(Socket socket, List<ClientHandler> clients) throws IOException
{ this.clientSocket = socket;

this.clients = clients;

this.out = new PrintWriter(clientSocket.getOutputStream(), true);

this.in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

public void run() {

try {

String inputLine;

while ((inputLine = in.readLine()) != null)

for (ClientHandler aClient : clients) { aClient.out.println(inputLine);

}}

catch (IOException e) {

System.out.println("An error occurred: " + e.getMessage());

finally {

try {

in.close();

out.close();

clientSocket.close();

} catch (IOException e) { e.printStackTrace();

47
}}}}

11.2 Chat Client:-

import java.io.*;

import java.net.*;

import java.util.function.Consumer;

public class ChatClient {

private Socket socket;

private BufferedReader in;

private PrintWriter out;

private Consumer<String> onMessageReceived;

public ChatClient(String serverAddress, int serverPort, Consumer<String>


onMessageReceived) throws IOException {

this.socket = new Socket(serverAddress, serverPort);

this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

this.out = new PrintWriter(socket.getOutputStream(), true);

this.onMessageReceived = onMessageReceived;

} public void sendMessage(String msg) { out.println(msg);

public void startClient() {

new Thread(() -> {

try { String line; while ((line = in.readLine()) != null)

48
{

onMessageReceived.accept(line);

}}

catch (IOException e) {

e.printStackTrace(); } }).start();

}}

11.3 Chat Client GUI

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class ChatClientGUI extends JFrame {

private JTextArea messageArea;

private JTextField textField;

private JButton exitButton;

private ChatClient client;

public ChatClientGUI() {

super("Chat Application");

49
setSize(400, 500);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Color backgroundColor = new Color(240, 240, 240);

Color buttonColor = new Color(75, 75, 75);

Color textColor = new Color(50, 50, 50);

Font textFont = new Font("Arial", Font.PLAIN, 14);

Font buttonFont = new Font("Arial", Font.BOLD, 12);

messageArea = new JTextArea();

messageArea.setEditable(false);

messageArea.setBackground(backgroundColor);

messageArea.setForeground(textColor);

messageArea.setFont(textFont);

JScrollPane scrollPane = new JScrollPane(messageArea);

add(scrollPane, BorderLayout.CENTER);

String name = JOptionPane.showInputDialog(this, "Enter your name:", "Name Entry",


JOptionPane.PLAIN_MESSAGE);

this.setTitle("Chat Application - " + name);

textField = new JTextField(); textField.setFont(textFont);

textField.setForeground(textColor);

textField.setBackground(backgroundColor);

textField.addActionListener(new ActionListener()

50
public void actionPerformed(ActionEvent e)

String message = "[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] " +


name + ": " + textField.getText(); client.sendMessage(message); textField.setText("");

});

exitButton = new JButton("Exit");

exitButton.setFont(buttonFont);

exitButton.setBackground(buttonColor);

exitButton.setForeground(Color.WHITE);

exitButton.addActionListener(e -> { String departureMessage = name + " has left the chat.";
client.sendMessage(departureMessage);

try {

Thread.sleep(1000);

} catch (InterruptedException ie) {

Thread.currentThread().interrupt();

System.exit(0);

});

JPanel bottomPanel = new JPanel(new BorderLayout());


bottomPanel.setBackground(backgroundColor);

bottomPanel.add(textField,

51
BorderLayout.CENTER);

bottomPanel.add(exitButton,

BorderLayout.EAST);

add(bottomPanel, BorderLayout.SOUTH);

try {

this.client = new ChatClient("127.0.0.1", 5000, this::onMessageReceived);


client.startClient();

} catch (IOException e) {

e.printStackTrace();

JOptionPane.showMessageDialog(this, "Error connecting to the server", "Connection error",


JOptionPane.ERROR_MESSAGE);

System.exit(1);

} } private void onMessageReceived(String message) {

SwingUtilities.invokeLater(() -> messageArea.append(message + "\n"));

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> { new ChatClientGUI().setVisible(true); });

52
Output:-

Fig11 : output Chat application

53
CONCLUSION

I believe the trial has shown conclusively that it is both possible and desirable to use Python
as the principal teaching language:

• It is Free (as in both cost and source code).

• It is trivial to install on a Windows PC allowing students to take their interest further.


For many the hurdle of installing a Pascal or C compiler on a Windows machine is
either too expensive or too complicated;

• It is a flexible tool that allows both the teaching of traditional procedural


programming and modern OOP; It can be used to teach a large number of transferable
skills.

• It is a real-world programming language that can be and is used in academia and the
commercial world;

• It appears to be quicker to learn and, in combination with its many libraries, this
offers the possibility of more rapid student development allowing the course to be
made more challenging and varied; and most importantly, its clean syntax offers
increased understanding and enjoyment for students.

• With a vast collection of libraries, Python allows students to explore fields like data
science, machine learning, web development, and more without needing additional
programming languages. This versatility also means students can see practical
applications of their skills early on.

• Python is cross-platform, meaning code written on one operating system (Windows,


macOS, or Linux) can typically run on another with little to no modification. This
flexibility allows students to collaborate and work on various devices, fostering a
more inclusive learning environment.

54
FUTURE SCOPE

The future of Python looks extremely promising due to several factors. Here are a few key
areas where Python is expected to continue making significant strides:

1. Artificial Intelligence and Machine Learning

Python has established itself as the go-to language for AI and ML, thanks to its simplicity and
the powerful libraries available, such as TensorFlow, Keras, and Scikit-learn. As these fields
grow, Python's role in them will likely expand, driving innovation in technology and various
industries.

2. Data Science and Analytics

With the exponential growth of data, the need for efficient data analysis tools is greater than
ever. Python, with libraries like Pandas, NumPy, and Matplotlib, is a favorite among data
scientists for its ability to handle complex data sets and perform data visualization. The
demand for data scientists proficient in Python will continue to rise.

3. Web Development

Frameworks like Django and Flask have made Python a popular choice for web development.
The simplicity of the language and the robustness of these frameworks ensure that Python
remains a preferred language for building scalable and secure web applications.

4. Automation

Python's ease of use and powerful scripting capabilities make it an excellent choice for
automation tasks. From simple scripts to complex workflows, Python is used to automate
repetitive tasks across various domains, including network automation, testing, and data
processing

5. IoT (Internet of Things)

55
Python's role in IoT is growing as well, with libraries like MicroPython and frameworks that
support hardware interaction.

56

You might also like