Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

DESIGN PATTERNS

CO1
1.FACTORY PATTERN
UML DIAGRAMG
PROGRAM
ABSTRACT DESIGN PATTERNS
Same like factory pattern but factory of
factory

https://youtu.be/7g9S371qzwMhttps://
youtu.be/7g9S371qzwM

watch this you will understand


UML DIAGRAM
PROGRAM
SINGLETON DESIGN PATTERN
UML DIAGRAM
PROGRAM
Adapter design pattern
Imagine you have a toy car with a remote control that uses batteries, and you also
have a wall socket where you can plug in the charger for your phone. The problem is
that the toy car's remote control cannot directly connect to the wall socket. This is
where an adapter comes in.

An adapter is like a special connector that helps different things work together even
if they are not originally compatible. In our example, the adapter is a small device
that you can plug into the wall socket. It has a slot that fits the batteries from the
remote control. When you plug the adapter into the wall socket, it charges the
batteries and provides power to the remote control, allowing you to control the toy
car.

In programming, the Adapter design pattern works similarly. It helps two


incompatible classes work together by acting as a bridge between them. It converts
the interface of one class into another interface that the client (or code using the
classes) expects.
Uml diagram
Program
Decorator design pattern
Uml diagram
Program
Iterator design pattern

Uml diagram
Program
Uml diagram 2
Program2
Template Design Pattern
Uml diagram
Program
CO2
CLEAN
CODING
TECHNIQUES
Certainly! Here's a simplified explanation of the concepts mentioned in the provided
information:

1. Clean Coding: Clean coding means writing code that is easy to read,
understand, and maintain. It reduces the chances of errors and makes the
code more testable. Clean code is organized, readable, and follows certain
principles and techniques.
2. Characteristics of Clean Code:
• Simple: Clean code should be simple, without unnecessary complexity
or confusion.
• Maintainable: It should be easy to modify or update without causing
issues.
• Testable: Clean code is designed in a way that makes it easy to write
tests for it.
• Readable: Clean code is easy to read and understand by other
developers.
3. Unclean Code: Unclean code refers to code that is difficult to read,
unnecessarily complex, hard to test, or hard to modify. It lacks organization
and may lead to problems in the long run.
4. Clean Coding Techniques:
• Proper Naming: Giving meaningful names to variables, classes, and
methods.
• Source File Structure: Structuring the code file with a clear order of
package statements, import statements, class variables, instance
variables, constructors, and methods.
• Whitespaces and Indentation: Adding proper spaces and indentation
to make the code more readable.
• Method Parameters: Avoiding excessive parameters in methods to
maintain simplicity.
• Avoiding Hardcoding: Avoiding directly adding data into the code
and using external sources instead.
• Code Comments: Adding comments to explain the code's functionality
and purpose.
• Logging: Using logging techniques to track and debug code easily.
• SOLID Principles: Following a set of principles (Single Responsibility,
Open/Closed, Liskov Substitution, Interface Segregation, and
Dependency Inversion) to design clean and maintainable code.
• DRY and KISS Principles: DRY (Don't Repeat Yourself) emphasizes
code reusability, and KISS (Keep It Simple, Stupid) promotes simplicity
in code.

Now, here are some simplified terms you can use in your exam answers:

1. The role of whitespaces: Spaces used to make code more readable.


2. After using clean coding techniques, variable names begin with: Lowercase
alphabets.
3. Characteristics of clean code: Simple, maintainable, testable, readable code.
4. List of clean coding techniques: Proper naming, structure, whitespace usage,
method parameters, avoiding hardcoding, code comments, logging, SOLID
principles, DRY and KISS principles.
5. Refactoring: Restructuring existing code without changing its external
behavior.
6. Summary of clean coding: Clean coding is about writing code that is easy to
read, understand, and maintain. It follows specific techniques like proper
naming, structure, whitespace usage, and principles like SOLID, DRY, and KISS.

Remember, it's important to understand the concepts thoroughly and use your own
words to explain them in the exam.
Analyze refactoring with a program
of your choice in java
1. Refactoring means: Code change without behavior change. It involves improving the
structure, organization, and readability of code without changing what the code does.
2. Refactoring can be done on: Methods, Method calls, and Classes. You can refactor
individual methods, modify how methods are called, or reorganize and improve entire
classes.
TERMINAL QUESTIONS

1. Describe code smells

2. List out categories of code smells

3. Analyze refactoring with methods and method calls

4. Summarize refactoring techniques with an example program

And here are brief answers to the terminal questions:

1. Code smells are indicators of potential issues in code. They don't prevent the code from
working, but they make it harder to understand and maintain. Examples of code smells
include long methods, large classes, duplicate code, and unused code.
2. Categories of code smells include:
• Bloaters: Code, methods, and classes that have become overly large and complex.
• Object-Orientation Abusers: Incorrect or incomplete application of object-oriented
principles.
• Change Preventers: Code that makes modifications difficult and leads to a high degree of
coupling.
• Dispensable: Unnecessary or redundant code that can be removed.
• Couplers: Code that exhibits excessive coupling between classes or inappropriate
delegation.
3. Refactoring techniques with methods and method calls involve:
• Composing methods: Breaking down large methods into smaller, focused ones.
• Simplifying method calls: Removing unnecessary parameters, renaming methods, and
separating queries from modifications.
4. An example program illustrating refactoring techniques would require a specific code
snippet or scenario to demonstrate how code smells can be identified and refactored.
Without a specific example, it's challenging to provide a comprehensive summary.

Remember, refactoring is a practice that aims to improve code quality, maintainability, and
readability over time. It involves making small, incremental changes to the codebase to address
code smells and make the code more efficient and understandable.

GENERIC
CLASSES
Introduction to Generics:

In Java, generics allow us to create classes, interfaces, and methods that can work
with different types of data (objects). It provides type-safety and code reusability.

Why Use Generics:

• Type-safety: Generics ensure that we can only store and retrieve objects of a
specific type, preventing type-related errors.
• No explicit type casting: With generics, there's no need to cast objects to the
desired type, as the type is already known at compile-time.
• Compile-time checking: Generics are checked at compile-time, which helps in
detecting errors early and preventing runtime issues.
• Code reusability: Generics allow us to write code that can be reused with
different types of data.
• --------------------------------------------
• Java Generics allows us to create a single class, interface, and method
that can be used with different types of data (objects).
• Generics does not work with primitive types (int, float, char, etc).

Advantages

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t


allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.

3) Compile-Time Checking: It is checked at compile time so problem will not occur at


runtime.

4) Code Reusability
Type Parameters
-------------------------------------------------------------

The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are

1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V - Value

Generic class

A class that can refer to any type is known as a generic class.

We are using the T type parameter to create the generic class of specific type.

class Employee//concrete class

{
}

class Employee<T>//Generic class


{
}

Generic Class Example


Sum of three
Illustration: Sample Program to Illustrate Set interface
• Java

// Java program Illustrating Set Interface


// Importing utility classes

import java.util.*;

// Main class

public class GFG {

// Main driver method

public static void main(String[] args)

// Demonstrating Set using HashSet

// Declaring object of type String

Set<String> hash_Set = new HashSet<String>();

// Adding elements to the Set

// using add() method

hash_Set.add("Geeks");

hash_Set.add("For");

hash_Set.add("Geeks");

hash_Set.add("Example");

hash_Set.add("Set");

// Printing elements of HashSet object


System.out.println(hash_Set);

Output
[Set, Example, Geeks, For]
Operations on the Set Interface
The set interface allows the users to perform the basic mathematical operation
on the set. Let’s take two arrays to understand these basic operations. Let
set1 = [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0, 7, 5]. Then the possible
operations on the sets are:
1. Intersection: This operation returns all the common elements from the
given two sets. For the above two sets, the intersection would be:
Intersection = [0, 1, 3, 4]
2. Union: This operation adds all the elements in one set with the other. For
the above two sets, the union would be:
Union = [0, 1, 2, 3, 4, 5, 7, 8, 9]
3. Difference: This operation removes all the values present in one set from
the other set. For the above two sets, the difference would be:
Difference = [2, 8, 9]
Now let us implement the following operations as defined above as follows:
What is thread and multithreading in Java?
In Java, Multithreading refers to a process of executing two or more threads
simultaneously for maximum utilization of the CPU. A thread in Java is a lightweight
process requiring fewer resources to create and share the process resources.
Is alive and join method
JDBC SQL AND MY SQL

Imagine you have a toy store where you keep all your toys neatly organized in
different shelves. You want to keep track of which toys are in the store, how many of
each toy you have, and maybe even some details about each toy, like its name, price,
and color. To do that, you use a special notebook where you write down all this
information.

In the world of computers, databases are like your notebook. They are used to store
and organize lots of data in a structured way. SQL (Structured Query Language) is a
language that allows us to interact with databases. It's like a set of special commands
that we can use to read and write data from and to the database.

Now, imagine you have a friend who wants to know how many red cars you have in
your toy store. Instead of going through the entire store and counting all the red cars
manually, you can use your notebook and search for the information quickly. JDBC
(Java Database Connectivity) is like a magical tool that helps Java programs
communicate with databases, just like your notebook helps you keep track of your
toys.

With JDBC, a Java program can send special instructions (SQL queries) to the
database to ask for specific information or to update the data stored in it. For
example, you can ask the database to give you a list of all the red cars or to add a
new toy to the store. JDBC takes care of all the complex details of connecting to the
database, sending the queries, and retrieving the results, so you can focus on writing
your Java program.

In the case of MySQL, it's a popular type of database that stores data in tables, just
like how you might have different shelves in your toy store. Each shelf represents a
table, and each toy is a row in that table. JDBC provides the tools to connect to a
MySQL database, send SQL queries to retrieve or modify the data in those tables,
and get the results back to your Java program.

So, in simple terms, JDBC is like a special tool that helps Java programs talk to
databases like MySQL using a language called SQL, allowing you to store and
retrieve data efficiently, just like you would manage your toys using your notebook in
your toy store.
DELETE
1. Importing necessary classes: The code begins with importing the required
classes from the java.sql package, which provides classes and interfaces for
JDBC operations.
2. Defining the class and main method: The code defines a class named DBDelete
and the main method, which serves as the entry point for the program.
3. Loading the Oracle JDBC driver: The line
Class.forName("oracle.jdbc.driver.OracleDriver"); loads the Oracle JDBC driver
into memory. It enables Java to communicate with the Oracle database.
4. Establishing a database connection: The next few lines define the URL,
username, and password to establish a connection with the Oracle database.
Here, the URL specifies the location of the database, and the username and
password are used to authenticate the connection.
5. Checking the connection: The code checks if the connection to the database
was successful by using the getConnection method from the DriverManager class.
If the connection is established, it prints "connected," otherwise it prints "not
connected."
6. Creating a statement: A statement object ( stmt) is created using the
createStatement method on the Connection object. This statement will be used
to execute SQL queries on the database.
7. Executing a delete query: The code defines a SQL query string ( sql1) to delete
a row from a table named PRODUCT where the PID column value is 200. The
executeUpdate method is called on the Statement object with this query to
delete the specified row from the table.
8. Executing a select query: Another SQL query string ( sql2) is defined to select
data from the PRODUCT table. The executeQuery method is called on the Statement
object with this query to retrieve the specified data.
9. Retrieving and printing the result: The code uses a ResultSet object (rs) to
store the results obtained from the select query. It iterates over the rows in the
result using a while loop and prints the values of the PNAME and PCOST columns
from each row.
10. Closing the connection: Finally, the code closes the connection to the
database using the close method on the Connection object.
INSERT
UPDATE
Cooperation among threads -
producer consumer program -
Runnable interface
Java Servlets LIFE CYCLE
Life Cycle of a Servlet (Servlet Life Cycle)
1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in
new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In
the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts
to the end state.
JSP - Overview What is JavaServer Pages?

Certainly! JavaServer Pages (JSP) is a technology used in web development that


allows you to create dynamic web pages using the Java programming language. It's a
way to combine Java code with HTML to generate web content that can change
based on different conditions or user interactions.

In traditional web development, HTML is used to define the structure and layout of
web pages, while server-side programming languages like Java are used to handle
the logic and processing on the server. JSP bridges the gap between these two by
providing a way to embed Java code directly into HTML pages.

With JSP, you can write regular HTML code for the presentation of the web page, just
like you would in a static HTML file. However, you can also include special tags called
JSP tags that allow you to embed Java code within the HTML. These tags provide a
way to execute Java statements, perform calculations, access databases, and interact
with other server-side components.

When a user requests a JSP page, the web server recognizes it as a JSP file and
passes it to the JSP engine. The JSP engine processes the Java code and generates a
corresponding servlet (a Java class that handles the request) behind the scenes. This
servlet is then compiled, executed, and generates the final HTML output that is sent
back to the user's web browser.

The advantage of using JSP is that it allows for dynamic content generation. You can
use Java code to fetch data from databases, process user input, make decisions, and
dynamically generate HTML content. This flexibility enables you to create interactive
web applications, personalized web pages, and respond to user actions in real-time.

In summary, JSP is a technology that combines Java code with HTML to create
dynamic web pages. It allows you to embed Java code within HTML files, enabling
you to generate dynamic content and interact with server-side components. It's a
powerful tool in web development for creating interactive and personalized web
applications.
JSP Elements in Short:

Scriptlet: Contains Java code within <% ... %> tags.

Declaration: Defines variables, methods, or classes using <%! ... %> tags.

Expression: Evaluates and inserts a Java expression using <%= ... %> tags.

Comment: Ignored by the JSP engine, can be written as <%-- ... --%>.

Directives: Provide instructions to the container.

Page directive,
Include directive
Taglib directive

Actions: Perform specific actions using XML-like syntax.

jsp:include

jsp:useBean

jsp:setProperty

jsp:getProperty

jsp:forward

jsp:plugin

jsp:element

jsp:attribute

jsp:body

jsp:text

Implicit Objects: Predefined variables accessible in JSP pages.

Control-Flow Statements: Use decision-making (if...else, switch) and looping (for, while)
statements.

Operators: Support logical and arithmetic operators as in Java.

Literals: Represent Boolean, integer, floating-point, string, null values.


These are the key elements and concepts of JSP, which allow developers to combine Java code
with HTML to create dynamic web pages.

JDBC ARCHITECHRE AND JDBC DRIVERS

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −

• JDBC API: This provides the application-to-JDBC Manager connection.


• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
Common JDBC Components

Certainly! Here are some real-time examples of using JDBC components:

1. DriverManager: Imagine you want to connect to a MySQL database in your


Java application. You would use the DriverManager to load the MySQL driver,
establish a connection by providing the database URL, username, and
password.
2. Connection: Once you have established a connection to the database, you can
perform various operations. For example, you might create a connection to an
Oracle database and execute SQL statements to insert, update, or retrieve
data from database tables.
3. Statement: Let's say you want to retrieve all the customers from a "Customers"
table in a database. You would create a Statement object, execute an SQL
SELECT query using the Statement's executeQuery method, and obtain a
ResultSet. You can then iterate over the ResultSet to access the customer data
row by row.
4. ResultSet: Continuing the previous example, you can use the ResultSet to
access the retrieved customer data. You can retrieve individual column values
using methods like getInt, getString, etc. You can also iterate over the
ResultSet using a loop to process all the retrieved rows.
5. SQLException: During database operations, various exceptions can occur, such
as connection failures, invalid SQL syntax, or integrity constraint violations. The
SQLException class helps handle these exceptions by providing information
about the error, such as error codes or error messages, allowing you to handle
them gracefully in your application.

Overall, JDBC components provide the necessary tools to connect to a database,


execute SQL queries, retrieve data, and handle any errors that may occur during
these operations.

You might also like