Web Note (1-8)
Web Note (1-8)
1. HTML Structure
The structure of an HTML document follows a specific syntax. An HTML document typically starts with a DOCTYPE
declaration, followed by the <html>, <head>, and <body> tags.
<!DOCTYPE html> <!-- Declares the document type as HTML5 -->
<html> <!-- The root element of the document -->
<head>
<title>Page Title</title> <!-- The title of the page displayed in the browser tab -->
</head>
<body>
<!-- Content goes here -->
</body>
</html>
• <!DOCTYPE html>: This declaration specifies that the document is an HTML5 document.
• <html>: The root element that encapsulates the whole document.
• <head>: Contains metadata about the document, such as the title, links to stylesheets, and scripts.
• <body>: Contains the content of the page, such as text, images, links, and forms.
2. HTML Tags
HTML tags are used to define elements on a web page. Tags come in pairs, like <tag> and </tag>, where the opening tag
defines the element, and the closing tag marks the end of that element.
Common Tags:
• <h1> to <h6>: Header tags used for headings.
<h1>This is a Heading 1</h1>
<h2>This is a Heading 2</h2>
• <p>: Paragraph tag used for text.
<p>This is a paragraph of text.</p>
• <a>: Anchor tag used for hyperlinks.
<a href="https://www.example.com">Click here to visit Example</a>
• <img>: Image tag used to display images.
<img src="image.jpg" alt="Description of Image" width="500" height="600">
• <ul>: Unordered list (bulleted).
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
• <ol>: Ordered list (numbered).
<ol>
<li>First item</li>
<li>Second item</li>
</ol>
• <li>: List item used inside <ul> or <ol>.
• <div>: Block-level element used to group content.
<div>
<p>Content inside a div block</p>
</div>
• <span>: Inline element used to group content without breaking the flow.
<span>This is a span element</span>
3. Lists
Lists are used to group related items together.
Unordered List (<ul>):
Displays items with bullet points.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Ordered List (<ol>):
Displays items with numbered order.
<ol>
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
</ol>
Definition List (<dl>):
Used to define a list of terms and their descriptions.
<dl>
<dt>HTML</dt>
<dd>A markup language for web pages</dd>
<dt>CSS</dt>
<dd>A style sheet language used for designing web pages</dd>
</dl>
4. Table
Tables are used to display data in a grid format, with rows and columns.
Table Structure:
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
<td>Data 4</td>
</tr>
</table>
• <table>: The table element.
• <tr>: Table row.
• <th>: Table header (usually bold and centered).
• <td>: Table data (cells).
• border: Attribute to define the border around the table (this is deprecated in modern HTML; CSS should be used for
styling).
6. Images
The <img> tag is used to embed images in HTML pages.
<img src="image.jpg" alt="Image description" width="400" height="300">
• src: Specifies the image source (URL or local path).
• alt: Provides alternate text for the image if it fails to load.
• width and height: Specify the dimensions of the image.
7. Forms
Forms allow users to input data and send it to the server.
Form Structure:
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
8. Frames
Frames allow you to divide the web page into multiple sections, each capable of displaying different content. However,
frames are now discouraged in modern web design, and newer techniques like CSS Grid or Flexbox are used instead.
Basic Example of a Frame:
<iframe src="page.html" width="600" height="400"></iframe>
• <iframe>: Embeds another HTML document within the current document.
Summary
• HTML Structure: HTML documents consist of the DOCTYPE, <html>, <head>, and <body> tags.
• Common Tags: Use tags like <h1>, <p>, <a>, <img>, <ul>, <ol>, <table>, etc., for structuring content.
• Forms and Tables: Forms collect user input, and tables display tabular data.
• Links: Links allow navigation between pages using the <a> tag.
• Stylesheets: Define the visual style of a web page using CSS, which can be applied inline, internally, or externally.
UNIT-2: Introduction to Java
4. Bytecode
Bytecode is the intermediate, platform-independent code generated by the Java compiler (javac).
• It is stored in .class files.
• The JVM interprets or compiles this bytecode into platform-specific machine code for execution.
Advantages of Bytecode:
• Platform independence (Write Once, Run Anywhere - WORA).
• Security and portability.
5. Characteristics of Java
Java is a widely used programming language known for its unique features:
a. Simple
Java syntax is easy to learn, especially for programmers familiar with C or C++.
b. Object-Oriented
Follows an OOP paradigm with concepts like classes, objects, inheritance, and polymorphism.
c. Platform-Independent
Java programs run on any platform that has a JVM, thanks to bytecode.
d. Secure
Java provides:
• Runtime checks.
• No use of pointers.
• Secure class loading and bytecode verification.
e. Robust
Java handles errors through exception handling and has strong memory management (garbage collection).
f. Multi-threaded
Supports concurrent programming with built-in support for threads.
g. High Performance
Java achieves good performance through the Just-In-Time (JIT) compiler.
h. Distributed
Supports distributed computing via tools like Remote Method Invocation (RMI) and frameworks like Spring.
i. Dynamic
Java supports dynamic loading of classes at runtime.
j. Portable
The Java bytecode can run on any platform with a JVM, making it portable.
1. Object-Oriented Programming (OOP) in Java
Java is an object-oriented programming language that follows four key principles:
a. Encapsulation
• Wrapping data (fields) and methods (functions) in a single unit (class).
• Example:
class Person {
private String name;
public void setName(String name) { this.name = name; }
public String getName() { return name; }
}
b. Inheritance
• Enables one class to acquire properties and methods from another.
• Example:
class Animal {
void eat() { System.out.println("This animal eats."); }
}
class Dog extends Animal {
void bark() { System.out.println("Dog barks."); }
}
c. Polymorphism
• Allows one interface to be used for different types.
• Example:
class Shape { void draw() { System.out.println("Drawing Shape."); } }
class Circle extends Shape { void draw() { System.out.println("Drawing Circle."); } }
d. Abstraction
• Hides implementation details and shows only essential features.
• Example:
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() { System.out.println("Car starts with a key."); }
}
4. Operators in Java
1. Arithmetic Operators: +, -, *, /, %.
2. Relational Operators: >, <, >=, <=, ==, !=.
3. Logical Operators: &&, ||, !.
4. Bitwise Operators: &, |, ^, ~, <<, >>.
5. Assignment Operators: =, +=, -=, etc.
5. Expressions in Java
An expression is a combination of variables, operators, and method calls that produces a result.
Example:
int result = (10 + 5) * 3; // Expression
6. Control Statements
Control statements regulate the flow of execution in a program.
Selection Statements
• if Statement:
if (x > 0) { System.out.println("Positive number"); }
• if-else Statement:
if (x > 0) { System.out.println("Positive"); }
else { System.out.println("Negative"); }
• switch Statement:
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Invalid Day");
}
Iteration Statements
1. For Loop:
for (int i = 0; i < 5; i++) { System.out.println(i); }
2. While Loop:
int i = 0;
while (i < 5) { System.out.println(i); i++; }
3. Do-While Loop:
int i = 0;
do { System.out.println(i); i++; } while (i < 5);
Jump Statements
1. break: Exits a loop or switch.
for (int i = 0; i < 5; i++) {
if (i == 3) break;
System.out.println(i);
}
2. continue: Skips the current iteration.
for (int i = 0; i < 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
3. return: Exits from a method and optionally returns a value.
int add(int a, int b) {
return a + b;
}
2. Declaring a Class
A class is declared using the class keyword:
class MyClass {
int number;
void display() {
System.out.println("Number: " + number);
}
}
4. Constructors
A constructor initializes an object. It has the same name as the class and no return type.
Default Constructor:
class MyClass {
MyClass() {
System.out.println("Default Constructor Called");
}
}
Parameterized Constructor:
class MyClass {
int number;
MyClass(int n) {
number = n;
}
}
5. Argument Passing
Java supports pass-by-value for arguments.
Example:
void updateNumber(int num) {
num += 10;
}
7. Inner Class
An inner class is declared within another class.
Member Inner Class:
class Outer {
class Inner {
void display() { System.out.println("Inner class method"); }
}
}
Static Nested Class:
class Outer {
static class Nested {
void display() { System.out.println("Static nested class method"); }
}
}
8. Method Overloading
Defining multiple methods with the same name but different parameter lists.
class MathOperations {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
9. Inheritance
Inheritance allows a class to derive properties and methods from another class.
class Animal {
void eat() { System.out.println("This animal eats."); }
}
class Dog extends Animal {
void bark() { System.out.println("Dog barks."); }
}
10. Use of super Keyword
The super keyword refers to the parent class.
• Access Parent Class Constructor:
class Parent {
Parent() { System.out.println("Parent Constructor"); }
}
class Child extends Parent {
Child() { super(); }
}
• Access Parent Class Methods:
super.methodName();
3. Exception Types
a. Checked Exceptions
Exceptions checked at compile time. These must be handled using try-catch or declared using throws.
• Examples:
o IOException
o SQLException
o FileNotFoundException
b. Unchecked Exceptions
Exceptions that occur during runtime and do not require mandatory handling.
• Examples:
o ArithmeticException
o NullPointerException
o ArrayIndexOutOfBoundsException
4. Built-in Exceptions
Some common built-in exceptions:
Exception Description
ArithmeticException Thrown when a division by zero occurs.
NullPointerException Thrown when trying to use null as an object.
ArrayIndexOutOfBoundsException Thrown when accessing an invalid array index.
ClassNotFoundException Thrown when a class cannot be found.
IOException Thrown when an I/O operation fails.
FileNotFoundException Thrown when a file is not found.
5. User-Defined Exceptions
You can create custom exceptions by extending the Exception or RuntimeException class.
Example:
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
1. String Class
A String is an immutable object that represents a sequence of characters.
String Constructors:
• Default Constructor:
String str = new String();
• Using a Character Array:
char[] arr = {'H', 'e', 'l', 'l', 'o'};
String str = new String(arr); // "Hello"
• Using a Byte Array:
byte[] bytes = {65, 66, 67};
String str = new String(bytes); // "ABC"
• Direct Assignment:
String str = "Hello, World!";
2. String Operations
a. Character Extraction
• charAt(int index): Retrieves the character at the specified index.
String str = "Hello";
char c = str.charAt(1); // 'e'
• getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters to a destination array.
char[] dst = new char[5];
str.getChars(0, 5, dst, 0);
b. String Comparisons
• equals(): Compares two strings for equality.
boolean result = str1.equals(str2);
• equalsIgnoreCase(): Ignores case during comparison.
boolean result = str1.equalsIgnoreCase(str2);
• compareTo(): Lexicographically compares two strings.
int result = str1.compareTo(str2); // 0 if equal, <0 if str1 < str2, >0 if str1 > str2
c. Searching Strings
• indexOf(String str): Returns the index of the first occurrence of the substring.
int index = "Hello, World!".indexOf("World"); // 7
• lastIndexOf(String str): Returns the index of the last occurrence.
int index = "Hello, World! World!".lastIndexOf("World"); // 14
d. Modifying a String
• substring(int beginIndex, int endIndex): Extracts a substring.
String substr = "Hello, World!".substring(7, 12); // "World"
• concat(String str): Concatenates two strings.
String result = "Hello".concat(", World!"); // "Hello, World!"
• replace(char oldChar, char newChar): Replaces all occurrences of a character.
String result = "Java".replace('a', 'o'); // "Jovo"
e. Other Useful Methods
• length(): Returns the length of the string.
int len = "Hello".length(); // 5
• toLowerCase() / toUpperCase(): Converts case.
String lower = "HELLO".toLowerCase(); // "hello"
String upper = "hello".toUpperCase(); // "HELLO"
• trim(): Removes leading and trailing spaces.
String trimmed = " Hello ".trim(); // "Hello"
3. StringBuffer Class
The StringBuffer class is used to create mutable strings. It is thread-safe, making it slightly slower than StringBuilder.
Constructors
• Default Constructor: Creates an empty buffer with a default capacity of 16.
StringBuffer sb = new StringBuffer();
• With Initial String:
StringBuffer sb = new StringBuffer("Hello");
StringBuffer Operations
• Append: Adds data to the end of the buffer.
sb.append(" World"); // "Hello World"
• Insert: Inserts data at a specified position.
sb.insert(5, ","); // "Hello, World"
• Delete: Removes characters from a specified range.
sb.delete(5, 6); // "Hello World"
• Reverse: Reverses the string.
sb.reverse(); // "dlroW olleH"
• Replace: Replaces characters within a range.
sb.replace(0, 5, "Hi"); // "Hi World"
1. I/O Basics
• Stream: A sequence of data.
o Input Stream: Used to read data.
o Output Stream: Used to write data.
Types of Streams:
1. Byte Streams: Handle raw binary data.
o Classes: InputStream, OutputStream.
2. Character Streams: Handle text data (characters).
o Classes: Reader, Writer.
2. Byte Stream
Used for reading and writing binary data (e.g., images, audio, video).
Key Classes:
• InputStream: Abstract class for reading byte data.
o Example: FileInputStream.
• OutputStream: Abstract class for writing byte data.
o Example: FileOutputStream.
Example: Reading and Writing Bytes
import java.io.*;
int data;
while ((data = input.read()) != -1) { // Read byte by byte
output.write(data); // Write byte by byte
}
input.close();
output.close();
}
}
3. Character Stream
Used for reading and writing text data (character by character).
Key Classes:
• Reader: Abstract class for reading character streams.
o Example: FileReader.
• Writer: Abstract class for writing character streams.
o Example: FileWriter.
Example: Reading and Writing Characters
import java.io.*;
int data;
while ((data = reader.read()) != -1) { // Read character by character
writer.write(data); // Write character by character
}
reader.close();
writer.close();
}
}
Best Practices
1. Always close streams using close() or try-with-resources.
2. Use buffered streams (BufferedReader, BufferedWriter) for efficiency.
3. Handle exceptions properly using try-catch.
4. For larger files, use byte streams for better performance.
UNIT-8: Java Utility package
Java Utility Package (java.util)
The java.util package contains a set of classes and interfaces that provide a framework for handling collections of objects.
Collections represent groups of objects and provide various methods to manipulate those groups.
1. Collection Overview
A collection in Java is an object that represents a group of objects. It is a central part of Java’s Collection Framework. The
framework provides several classes and interfaces that help store and manipulate collections of data.
Core Interfaces of the Collection Framework:
• Collection: The root interface for most of the collection types (other than maps). It defines methods like add(),
remove(), clear(), etc.
• List: An ordered collection (also known as a sequence), allows duplicate elements.
• Set: A collection that does not allow duplicate elements.
• Queue: A collection used to hold elements before processing.
• Deque: A collection used to hold elements in a double-ended queue (both ends).
2. Collection Interfaces
Here are some of the key interfaces in the java.util package:
a. List Interface
An ordered collection that allows duplicate elements.
• Common Implementations: ArrayList, LinkedList.
b. Set Interface
A collection that does not allow duplicate elements.
• Common Implementations: HashSet, TreeSet, LinkedHashSet.
c. Queue Interface
A collection designed for holding elements prior to processing.
• Common Implementations: LinkedList, PriorityQueue.
d. Map Interface
A collection that maps keys to values (not a true collection).
• Common Implementations: HashMap, TreeMap, LinkedHashMap.
3. Collection Classes
a. ArrayList
ArrayList is a resizable array implementation of the List interface. It allows fast random access to elements but slower
insertions and deletions compared to LinkedList.
• Constructor:
ArrayList<Type> list = new ArrayList<>();
• Common Methods:
o add(E element): Adds an element to the list.
o get(int index): Retrieves the element at the specified index.
o remove(int index): Removes the element at the specified index.
o size(): Returns the number of elements in the list.
Example:
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Output: Apple
b. LinkedList
LinkedList is a doubly-linked list implementation of the List and Deque interfaces. It allows efficient insertions and deletions
at both ends but slower random access compared to ArrayList.
• Constructor:
LinkedList<Type> list = new LinkedList<>();
• Common Methods:
o addFirst(E element): Adds the element to the beginning of the list.
o addLast(E element): Adds the element to the end of the list.
o removeFirst(): Removes the first element.
o removeLast(): Removes the last element.
Example:
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.get(0)); // Output: Apple