UNIT 3: Intelligent Systems and Web Technologies for E-Commerce
A. Artificial Intelligence Fundamentals
1. Problem Solving and Search Algorithms
Uninformed Search
Searches without domain-specific knowledge.
| Algorithm | Strategy | Data Structure | Completeness | Optimality | Time/Space Complexity |
|---|---|---|---|---|---|
| Breadth-First Search (BFS) | Explores all neighbors at current depth before moving deeper. | Queue (FIFO) | Yes (if branching factor finite) | Yes (if all step costs equal) | Time: $$\displaystyle O(b^d) $$, Space: $$\displaystyle O(b^d) $$ |
| Depth-First Search (DFS) | Explores as far as possible along a branch before backtracking. | Stack (LIFO) | No (may get stuck in infinite paths) | No | Time: $$\displaystyle O(b^m) $$, Space: $O(bm)$ |
Where $b$ = branching factor, $d$ = solution depth, $m$ = maximum depth.
[!TIP] Exam Focus: BFS is complete and optimal for uniform-cost trees but memory-intensive. DFS is memory-efficient but not complete/optimal. Compare them directly in 7-mark questions.
Informed Search (Heuristic Search)
Uses heuristic function $h(n)$ to guide search.
A Algorithm:*
-
Evaluates nodes using $$\displaystyle f(n) = g(n) + h(n) $$.
-
$g(n)$: Actual cost from start to node $n$.
-
$h(n)$: Estimated cost from $n$ to goal (admissible & consistent heuristic).
-
-
Optimal & Complete if $h(n)$ is admissible (never overestimates true cost).
-
Uses a priority queue (min-heap) ordered by $f(n)$.
[!TIP] 8-Puzzle Problem: For given initial/final states, calculate $g(n)$ (depth) and $h(n)$ (misplaced tiles) for each node, expand node with lowest $f(n)$.
Heuristic Example: Manhattan Distance
-
For grid-based problems (like mouse in maze).
-
$$\displaystyle h(n) = |x_{current} - x_{goal}| + |y_{current} - y_{goal}| $$.
-
Sum of horizontal & vertical distances, ignoring obstacles.
Local Search
-
Used for optimization problems where path to goal is irrelevant.
-
Hill Climbing: Greedy algorithm; moves to neighbor with best heuristic value.
-
Problems in Hill Climbing:
-
Local Maxima: Peak higher than neighbors but not global max.
-
Plateau: Flat area where all neighbors have same value.
-
Ridge: Sequence of local maxima; hard to navigate.
-
Local Minima: (for minimization) Valley not global min.
-
2. Production Systems
Production Rule: IF <condition> THEN <action>.
-
Characteristics:
-
Modular: Rules independent, easy to add/remove.
-
Incremental: Rules can be added without restructuring.
-
Uniform: All rules use same syntax.
-
Declarative: Knowledge (condition) separate from control (action).
-
Water Jug Problem (4-gallon & 3-gallon jugs, target: 2 gallons in 4-gallon jug):
Operators (Rules):
-
Fill 4G jug: $$\displaystyle (x, y) \rightarrow (4, y) $$
-
Fill 3G jug: $$\displaystyle (x, y) \rightarrow (x, 3) $$
-
Empty 4G jug: $$\displaystyle (x, y) \rightarrow (0, y) $$
-
Empty 3G jug: $$\displaystyle (x, y) \rightarrow (x, 0) $$
-
Pour 4G → 3G until 3G full or 4G empty.
-
Pour 3G → 4G until 4G full or 3G empty.
One Solution Path:
(0,0) → Fill 4G → (4,0)
→ Pour 4G→3G → (1,3)
→ Empty 3G → (1,0)
→ Pour 4G→3G → (0,1)
→ Fill 4G → (4,1)
→ Pour 4G→3G → (2,3) → **Goal: (2,3)**
3. Knowledge Representation
Properties of Good KR System:
-
Representational Adequacy: Express required knowledge.
-
Inferential Adequacy: Derive new knowledge efficiently.
-
Inferential Efficiency: Guide inference process.
-
Acquisitional Efficiency: Acquire new knowledge easily.
Representation Techniques:
| Technique | Description | Example |
|---|---|---|
| Predicate Logic | Formal logic using predicates, variables, quantifiers. | Loves(Ram, Everyone) → ∀x Loves(Ram, x) |
| Semantic Nets | Graphical; nodes=concepts, edges=relations. | Ram --loves--> Everyone (directed graph) |
| Frames | Structured objects with slots & default values. | Person: name, age, job |
| Scripts | Sequence of events in a context. | Restaurant script: enter, order, eat, pay |
4. Reasoning Methods
| Forward Chaining (Data-Driven) | Backward Chaining (Goal-Driven) | |
|---|---|---|
| Start | From known facts | From goal/hypothesis |
| Process | Apply rules whose conditions are satisfied → derive new facts | Find rules whose conclusion matches goal → check conditions |
| Example | IF A AND B THEN C; given A,B → infer C |
To prove C, look for rule with C in THEN; need A & B |
| Use Case | Monitoring, control systems | Diagnosis, problem-solving (e.g., MYCIN) |
| Efficiency | May generate irrelevant facts | Focused on goal, but may backtrack |
Monotonic vs Non-Monotonic Reasoning:
-
Monotonic: Adding knowledge never retracts conclusions. Classical logic.
- Example:
Socrates is a man,All men are mortal→Socrates is mortal. Always true.
- Example:
-
Non-Monotonic: Adding knowledge can retract conclusions. Handles incomplete/uncertain info.
- Example:
Bird(X)typically impliesFlies(X). ButPenguin(Tweety)→ retractFlies(Tweety).
- Example:
5. Fuzzy Logic
Fuzzy Set: $$\displaystyle A = \mu_A(x_1)/x_1 + \mu_A(x_2)/x_2 + ... $$
where $$\displaystyle \mu_A(x_i) \in [0,1] $$ is membership degree.
Operations on Fuzzy Sets A & B:
| Operation | Formula | Example (Given $A$, $B$) |
|---|---|---|
| Union | $$\displaystyle \mu_{A \cup B}(x) = \max[\mu_A(x), \mu_B(x)] $$ | $$\displaystyle A \cup B = 1/x_1 + 0.4/x_2 + 0.5/x_3 + 1/x_4 $$ |
| Intersection | $$\displaystyle \mu_{A \cap B}(x) = \min[\mu_A(x), \mu_B(x)] $$ | $$\displaystyle A \cap B = 0.5/x_1 + 0.3/x_2 + 0.1/x_3 + 0.2/x_4 $$ |
| Complement | $$\displaystyle \mu_{\bar{A}}(x) = 1 - \mu_A(x) $$ | $$\displaystyle \bar{A} = 0/x_1 + 0.7/x_2 + 0.5/x_3 + 0.8/x_4 $$ |
| Difference $A - B$ | $$\displaystyle \mu_{A-B}(x) = \min[\mu_A(x), 1-\mu_B(x)] $$ | $$\displaystyle A-B = 0.5/x_1 + 0.6/x_2 + 0.4/x_3 + 0/x_4 $$ |
6. Game Playing
Min-Max Algorithm:
-
Used in two-player, zero-sum games (e.g., chess, tic-tac-toe).
-
Max player aims to maximize score; Min player minimizes.
-
Search tree: nodes = game states, edges = moves.
-
Procedure:
-
Generate game tree to a fixed depth (or terminal state).
-
Assign utility values to terminal nodes (win=+1, loss=-1, draw=0).
-
Back up values:
-
Max node: value = $\max$(child values).
-
Min node: value = $\min$(child values).
-
-
At root, choose move leading to child with highest min-max value.
-
[!TIP] Alpha-Beta Pruning: Optimizes Min-Max by pruning branches that won't affect final decision.
7. Machine Learning
Neural Networks:
-
Computing systems inspired by biological neurons.
-
Structure: Input layer → Hidden layer(s) → Output layer.
-
Each connection has weight; neurons apply activation function.
Types of Learning:
-
Supervised: Labeled data; learn mapping input→output.
- Example: Classification (spam filter), Regression (price prediction).
-
Unsupervised: Unlabeled data; find hidden patterns.
- Example: Clustering (customer segmentation), Dimensionality reduction.
-
Reinforcement: Agent learns via rewards/penalties from environment.
- Example: Game playing (AlphaGo), Robotics.
-
Semi-supervised: Mix of labeled & unlabeled data.
-
Self-supervised: Generate labels from data itself (e.g., predicting image rotation).
8. Natural Language Processing (NLP)
Components of Natural Language Understanding:
-
Morphological Analysis: Break words into base forms (lemmatization/stemming).
-
Syntactic Analysis (Parsing): Analyze sentence structure (grammar).
-
Semantic Analysis: Extract meaning; resolve word sense ambiguity.
-
Pragmatic Analysis: Interpret meaning in context (speaker intent, sarcasm).
-
Discourse Analysis: Understand relationships between sentences.
9. Expert Systems
Definition: AI program that mimics human expert's decision-making in a specific domain.
-
Components:
-
Knowledge Base: Facts & rules (IF-THEN) about domain.
-
Inference Engine: Applies rules to derive conclusions (forward/backward chaining).
-
User Interface: Interacts with user.
-
Explanation Facility: Explains reasoning (why/how).
-
Knowledge Acquisition: Tools to add knowledge.
-
-
Example: MYCIN (medical diagnosis), DENDRAL (chemical analysis).
10. Probabilistic Reasoning
Bayes' Theorem:
$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$
-
$P(A|B)$: Posterior probability of A given B.
-
$P(B|A)$: Likelihood.
-
$P(A)$: Prior probability.
-
$P(B)$: Marginal likelihood (normalizing constant).
Application: Naive Bayes classifier for spam detection.
Resolution Technique (Propositional Logic):
-
Rule inference for proving theorems.
-
Steps:
-
Convert all statements to Conjunctive Normal Form (CNF): AND of ORs.
-
To prove goal $G$, assume $\neg G$ and add to knowledge base.
-
Repeatedly resolve pairs of clauses containing complementary literals.
-
If empty clause
□derived → contradiction → $G$ is true.
-
-
Example:
-
KB: $A \lor B$, $\neg B$, $$\displaystyle A \rightarrow C $$
-
Goal: $C$
-
Convert: $A \lor B$, $\neg B$, $\neg A \lor C$
-
Resolve $A \lor B$ & $\neg B$ → $A$
-
Resolve $A$ & $\neg A \lor C$ → $C$ ✓
-
B. Java Programming for E-Commerce Applications
1. Java Fundamentals
Iteration Statements (Loops):
// for loop
for(int i=0; i<5; i++) { System.out.println(i); }
// while loop
int i=0;
while(i<5) { System.out.println(i); i++; }
// do-while (executes at least once)
int i=0;
do { System.out.println(i); i++; } while(i<5);
Jump Statements:
-
break: Exit loop/switch immediately. -
continue: Skip current iteration, proceed to next. -
return: Exit method, optionally return value.
Constructors:
-
Special method called on object creation; same name as class.
-
Types:
-
Default: No parameters; sets default values.
-
Parameterized: Accepts arguments to initialize fields.
-
Copy Constructor: Takes object of same class, copies values.
-
Example: Area of Circle using Constructor
class Circle {
double radius;
Circle(double r) { radius = r; } // Parameterized constructor
double area() { return Math.PI * radius * radius; }
}
Keywords:
-
static: Belongs to class, not instance. One copy shared.static int count; // Class variable static void method() {} // Class method -
`final:** Variable (constant), method (cannot override), class (cannot inherit).
final double PI = 3.14; // Constant final void show() {} // Cannot override
2. Object-Oriented Programming in Java
Polymorphism:
-
Method Overloading: Same method name, different parameters (compile-time).
void add(int a, int b) { ... } void add(double a, double b) { ... } -
Method Overriding: Subclass redefines superclass method (runtime).
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } // Override -
Dynamic Method Dispatch: Runtime resolution of overridden method.
Animal a = new Dog(); a.sound(); // Calls Dog's sound() (runtime binding)
Abstraction:
-
Abstract Class: Cannot instantiate; may have abstract methods (no body).
abstract class Shape { abstract double area(); // Abstract method void display() { System.out.println("Shape"); } // Concrete method } class Circle extends Shape { double area() { return Math.PI*r*r; } // Must implement } -
Interface: Pure abstraction; all methods abstract (pre-Java 8), now can have default/static methods.
interface Drawable { void draw(); // Implicitly public abstract } class Rectangle implements Drawable { public void draw() { ... } // Must implement all }
3. Graphical User Interface (Swing)
Simple Swing App: Sum of Two Numbers
import javax.swing.*;
import java.awt.event.*;
public class SumApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Sum Calculator");
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton btn = new JButton("Add");
JLabel result = new JLabel("Result: ");
btn.addActionListener(e -> {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
result.setText("Result: " + (a+b));
});
JPanel panel = new JPanel();
panel.add(t1); panel.add(t2); panel.add(btn); panel.add(result);
frame.add(panel);
frame.setSize(300,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. Applets
Applet Life Cycle:
-
init(): Called once when applet first loads. Initialize resources. -
start(): Called afterinit(), also when applet becomes active (e.g., browser tab selected). -
stop(): Called when applet is inactive (e.g., browser tab hidden). -
destroy(): Called once before applet is unloaded. Cleanup resources. -
paint(Graphics g): Called to render UI (also on resize/refresh).
[!TIP] Modern Java deprecates Applets; use Java Web Start or other technologies.
5. Memory Management
Garbage Collection (GC):
-
Automatic memory management; reclaims memory from unused objects.
-
How it works:
-
JVM identifies unreachable objects (no references).
-
GC thread (daemon) runs periodically.
-
Common algorithms: Mark-and-Sweep, Generational (Young/Old Gen).
-
-
System.gc(): Suggestion to run GC; not guaranteed. -
Finalize(): Deprecated; called before object is collected (unreliable).
6. Multithreading
Thread Creation:
-
Extend
Threadclass:class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } new MyThread().start(); -
Implement
Runnableinterface (preferred):class MyRunnable implements Runnable { public void run() { ... } } new Thread(new MyRunnable()).start();
Thread Synchronization:
-
Prevent race conditions when multiple threads access shared resource.
-
Use
synchronizedkeyword:synchronized void method() { ... } // Method-level synchronized(obj) { ... } // Block-level
Inter-Thread Communication:
-
wait(),notify(),notifyAll()(must be called within synchronized context). -
Example: Producer-Consumer problem.
Example: Three Threads with Different Delays
class MyThread extends Thread {
String msg; int interval;
MyThread(String m, int i) { msg=m; interval=i; }
public void run() {
while(true) {
System.out.println(msg);
try { Thread.sleep(interval*1000); } catch(InterruptedException e){}
}
}
}
// In main:
new MyThread("Hello!", 1).start();
new MyThread("Wear Mask!", 2).start();
new MyThread("Use Sanitizer!", 5).start();
7. JavaBeans
Introspection: Ability to discover properties, events, methods of a bean at runtime.
-
BeanInfoInterface: Provides explicit bean information.public class MyBeanInfo extends SimpleBeanInfo { public PropertyDescriptor[] getPropertyDescriptors() { PropertyDescriptor pd = new PropertyDescriptor("propertyName", MyBean.class); return new PropertyDescriptor[]{pd}; } } -
Tools (e.g., IDE builders) use introspection to manipulate beans visually.
8. JNDI (Java Naming and Directory Interface)
Key Methods (Context interface):
| Method | Purpose | Syntax |
|---|---|---|
bind(String name, Object obj) |
Bind object to name | ctx.bind("java:comp/env/jdbc/MyDB", ds); |
rebind(String name, Object obj) |
Rebind (overwrite if exists) | ctx.rebind("jdbc/MyDB", newDS); |
createSubcontext(String name) |
Create new sub-context (folder) | ctx.createSubcontext("apps"); |
getAttributes(String name) |
Get attributes of named object | Attributes attrs = ctx.getAttributes("jdbc/MyDB"); |
modifyAttributes(String name, int mods, Attributes attrs) |
Modify attributes | ctx.modifyAttributes("jdbc/MyDB", DirContext.REPLACE_ATTRIBUTE, attrs); |
9. Exception Handling
Mechanisms:
-
try: Block containing code that may throw exception. -
catch: Handles specific exception type. -
throw: Explicitly throw an exception. -
throws: Declare exceptions that method may throw (compile-time checking). -
Assertions:
assert condition;orassert condition : message;; enabled with-eaflag.
Example:
try {
int result = 10 / 0; // ArithmeticException
throw new IOException("File error"); // Explicit throw
} catch (ArithmeticException e) {
System.out.println("Divide by zero: " + e.getMessage());
} catch (IOException e) {
System.out.println(e);
} finally {
System.out.println("Always executes"); // Cleanup
}
10. Database Connectivity (JDBC)
Steps to Connect & Query:
-
Load Driver:
Class.forName("com.mysql.cj.jdbc.Driver"); -
Establish Connection:
Connection conn = DriverManager.getConnection(url, user, pass); -
Create Statement:
Statement stmt = conn.createStatement(); -
Execute Query:
ResultSet rs = stmt.executeQuery("SELECT * FROM table"); -
Process Result:
while(rs.next()) { rs.getInt("id"); } -
Close Resources:
rs.close(); stmt.close(); conn.close();(Use try-with-resources in Java 7+).
JDBC-ODBC Bridge: (Legacy, removed in Java 8)
-
sun.jdbc.odbc.JdbcOdbcDriverallowed JDBC to access ODBC data sources. -
Replaced by pure Java JDBC drivers.
11. I/O Streams
| Byte Streams | Character Streams |
|---|---|
| Handle raw binary data (8-bit bytes). | Handle text data (16-bit Unicode). |
Classes: InputStream, OutputStream |
Classes: Reader, Writer |
Subclasses: FileInputStream, BufferedInputStream |
Subclasses: FileReader, BufferedReader, FileWriter |
Copy File using Character Streams:
try (BufferedReader br = new BufferedReader(new FileReader("source.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("dest.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
}
12. Packages
Create Package:
// File: com/mypackage/MyClass.java
package com.mypackage;
public class MyClass { ... }
Compile: javac -d . MyClass.java (creates directory structure).
Access Protection Levels:
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | ✗ |
| (default) | ✓ | ✓ | ✗ | ✗ |
private |
✓ | ✗ | ✗ | ✗ |
13. Event Handling
Event Sources: Objects that generate events (e.g., JButton, JTextField).
Event Listeners: Interfaces that handle events (e.g., ActionListener, MouseListener).
Example: Button Click
JButton btn = new JButton("Click");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
Java 8+ Lambda: btn.addActionListener(e -> System.out.println("Clicked"));
14. Networking
Client-Server Communication (TCP): Server:
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept(); // Wait for client
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String msg = in.readLine();
out.println("Echo: " + msg);
s.close(); ss.close();
Client:
Socket s = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Hello Server");
System.out.println(in.readLine());
s.close();
15. Multiple Inheritance in Java
Implemented via Interfaces:
-
A class can
implementmultiple interfaces. -
Interfaces can have
defaultmethods (Java 8+); conflicts resolved by overriding.
Example:
interface A { default void show() { System.out.println("A"); } }
interface B { default void show() { System.out.println("B"); } }
class C implements A, B {
public void show() { A.super.show(); } // Resolve conflict
}
[!TIP] Java does not support multiple class inheritance (to avoid diamond problem), but interfaces with default methods require explicit resolution.