0% found this document useful (0 votes)
8 views23 pages

Web Note (1-8)

Web Tech notes ECE 7th sem

Uploaded by

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

Web Note (1-8)

Web Tech notes ECE 7th sem

Uploaded by

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

UNIT-1: Web Development

Web Development: HTML Overview


Web development involves creating and managing websites. The foundation of most websites is HTML (HyperText Markup
Language), which structures the content of the web page. In this overview, we will discuss the structure of HTML, various
tags, links, images, forms, tables, and stylesheets.

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).

5. Links and Link Types


The <a> tag is used to create hyperlinks. Links can point to other pages, sections, or external websites.
Link to an External Page:
<a href="https://www.example.com">Visit Example</a>
Link to a Specific Section of the Same Page:
<a href="#section1">Go to Section 1</a>
<h2 id="section1">Section 1</h2>
<p>Content for Section 1</p>
Types of Links:
• Absolute URL: A full URL that points to a resource anywhere on the internet.
<a href="https://www.example.com">Visit Example</a>
• Relative URL: A URL relative to the current document.
<a href="about.html">About Us</a>
• Anchor Links: Links that point to specific sections within the same page.
<a href="#section1">Jump to Section 1</a>

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>

<input type="submit" value="Submit">


</form>
• <form>: Defines the form.
• action: Specifies the URL where the form data will be sent upon submission.
• method: Specifies the HTTP method (e.g., GET, POST) to be used for submitting the form.
• <input>: Used to define input fields (text, email, password, etc.).
• <label>: Provides a label for form elements.

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.

9. Stylesheets and Their Types


Stylesheets are used to control the appearance of web pages. There are three ways to include styles in HTML:
Inline Styles:
Applied directly to an HTML element using the style attribute.
<p style="color: red; font-size: 16px;">This is a red paragraph</p>
Internal Styles:
Defined within the <style> tag in the <head> section.
<head>
<style>
p{
color: green;
font-size: 14px;
}
</style>
</head>
External Styles:
Linked from an external CSS file.
<link rel="stylesheet" href="styles.css">
• CSS (Cascading Style Sheets) is used to define how HTML elements should appear (colors, fonts, margins, etc.).

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

Java and Java Applications


• Java:
Java is a high-level, class-based, object-oriented programming language developed by Sun Microsystems (now
owned by Oracle). It is designed to have minimal implementation dependencies, making it a platform-independent
language through the concept of "Write Once, Run Anywhere" (WORA).
• Features of Java:
o Object-Oriented
o Platform-Independent (uses JVM for portability)
o Secure (uses a sandbox environment)
o Robust (exception handling and memory management)
o Multi-threaded
o High Performance (via Just-In-Time compilation)
o Dynamic and Extensible
• Java Applications:
Java applications are software programs written in Java that can run on any device with a compatible Java Virtual
Machine (JVM). There are different types of Java applications:
1. Standalone Applications: Also called desktop applications, these are traditional software programs (e.g., media
players, antivirus software).
2. Web Applications: Applications that run on servers and are accessed via web browsers (e.g., online shopping
platforms, banking portals). Java technologies like Servlets, JSP, and Spring are used to build web applications.
3. Enterprise Applications: Large-scale applications used in corporate environments, such as ERP and CRM systems.
These are built using frameworks like Java EE (Jakarta EE).
4. Mobile Applications: Applications designed for mobile devices, especially Android. Android applications are
primarily built using Java and Kotlin.
5. Distributed Applications: Applications that run on multiple systems and communicate over a network, using Java
technologies like RMI, CORBA, or web services.
6. Embedded Systems: Java is used in devices with limited computing resources, like smartcards, sensors, and
appliances.
7. Scientific Applications: Java is popular in research and scientific environments due to its portability, performance,
and robustness.

1. Java Virtual Machine (JVM)


The JVM is an abstract machine that provides the runtime environment for executing Java bytecode. It is platform-
dependent but executes platform-independent bytecode.
Key responsibilities:
• Loads bytecode.
• Verifies bytecode for security.
• Interprets or compiles bytecode into native machine code (using JIT - Just-In-Time Compiler).
• Manages memory via Garbage Collection.

2. Java Runtime Environment (JRE)


The JRE provides the runtime environment needed to execute Java programs.
It includes:
• The JVM.
• Core Java libraries and classes.
• Other runtime components.
Note: JRE doesn’t include tools for developing Java programs, like compilers or debuggers.
3. Java Development Kit (JDK)
The JDK is a complete software development kit for developing and running Java applications.
It includes:
• The JRE (runtime environment).
• Development tools like:
o javac (Java compiler)
o java (JVM launcher)
o javadoc (documentation generator)
o jdb (Java debugger).
JDK Editions:
• Standard Edition (SE): For general-purpose development.
• Enterprise Edition (EE): For large-scale, enterprise-level applications.
• Micro Edition (ME): For embedded and mobile devices.

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."); }
}

2. Simple Java Programs


Example 1: Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Example 2: Sum of Two Numbers
public class Sum {
public static void main(String[] args) {
int a = 5, b = 10;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
3. Data Types in Java
Java has two types of data types:
1. Primitive Data Types
o byte, short, int, long (integers).
o float, double (decimals).
o char (single character).
o boolean (true/false).
2. Non-Primitive Data Types
o Arrays, Strings, Classes, Interfaces.

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;
}

UNIT-3: Classes, Inheritance


1. Classes in Java
A class is a blueprint for objects. It defines properties (fields) and behaviors (methods).
Example:
class Animal {
String name; // Field
void speak() { // Method
System.out.println(name + " is speaking.");
}
}

2. Declaring a Class
A class is declared using the class keyword:
class MyClass {
int number;
void display() {
System.out.println("Number: " + number);
}
}

3. Creating Instances of a Class


To use a class, create its instance (object):
MyClass obj = new MyClass();
obj.number = 5;
obj.display();

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;
}

6. Use of static Keyword


The static keyword associates a member with the class rather than the object.
• Static Variables: Shared among all instances.
• Static Methods: Accessed without creating an object.
Example:
class MyClass {
static int count = 0;
static void showCount() {
System.out.println("Count: " + count);
}
}
MyClass.showCount(); // Access static method directly

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();

11. Method Overriding


A child class provides its own implementation of a method defined in the parent class.
class Parent {
void display() { System.out.println("Parent method"); }
}
class Child extends Parent {
@Override
void display() { System.out.println("Child method"); }
}

12. Abstract Class


An abstract class contains abstract (no implementation) and concrete methods.
abstract class Vehicle {
abstract void start();
}
class Car extends Vehicle {
void start() { System.out.println("Car starts with a key."); }
}

13. Dynamic Method Dispatch


Used to call the overridden method at runtime using a parent class reference.
class Parent {
void display() { System.out.println("Parent method"); }
}
class Child extends Parent {
void display() { System.out.println("Child method"); }
}
Parent ref = new Child(); // Runtime decision
ref.display(); // Calls Child's display

14. Use of final Keyword


• Final Variable: Cannot be changed after initialization.
final int MAX = 100;
• Final Method: Cannot be overridden.
final void display() {}
• Final Class: Cannot be subclassed.
final class Animal {}
UNIT-4: Interface, Package
1. Package in Java
A package in Java is a namespace that organizes classes and interfaces. It helps avoid name conflicts and makes code easier
to manage.
Types of Packages:
1. Built-in Packages: Provided by Java (e.g., java.util, java.io).
2. User-defined Packages: Created by the programmer.
Declaring a Package:
package mypackage;

public class MyClass {


public void display() {
System.out.println("This is a package example.");
}
}
Using a Package:
import mypackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Advantages of Packages:
• Avoids name conflicts.
• Provides access protection.
• Makes it easier to locate and use related classes.

2. Access Control Mechanism


Java provides four levels of access control to secure data and methods in classes.
Access Modifiers:
Modifier Class Package Subclass World
public
protected
default
private
Examples:
1. Private: Accessible only within the same class.
class Test {
private int data = 10;
}
2. Protected: Accessible within the same package or by subclasses.
protected void display() {
System.out.println("Protected Method");
}
3. Public: Accessible from anywhere.
public void display() {
System.out.println("Public Method");
}
3. Interface in Java
An interface is a blueprint of a class. It contains abstract methods and constants. Interfaces are used to achieve full
abstraction and multiple inheritance.
Defining an Interface:
interface Animal {
void sound(); // Abstract method
}
Implementing an Interface:
java
Copy code
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
Using an Interface:
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound();
}
}
Key Features:
• Methods in an interface are public and abstract by default.
• Fields in an interface are public, static, and final.

4. Dynamic Method Lookup (Dynamic Method Dispatch)


Dynamic Method Lookup, also known as Dynamic Method Dispatch, refers to resolving method calls at runtime. This
happens in the context of method overriding where the method to be executed is determined by the runtime object, not
the reference type.
Example:
class Parent {
void show() {
System.out.println("Parent's show");
}
}
class Child extends Parent {
void show() {
System.out.println("Child's show");
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child(); // Parent reference, Child object
obj.show(); // Resolves to Child's show method at runtime
}
}
How It Works:
• Compile Time: The compiler checks whether the method exists in the reference class.
• Runtime: The JVM determines which method to call based on the object type.
Use Case:
This is essential in scenarios like implementing polymorphism, enabling flexibility in code.
UNIT-5: Exception Handling
Exception Handling in Java
Exception handling in Java is a mechanism to handle runtime errors gracefully, ensuring the program can continue to
execute or terminate in a controlled manner.

1. Java Exception Handling Mechanism


• Exception: An event that disrupts the normal flow of a program.
• Exception Handling: The process of handling exceptions using specific constructs like try, catch, finally, etc.

2. Keywords in Exception Handling


a. try
Defines a block of code to monitor for exceptions. If an exception occurs in this block, it is passed to the catch block.
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
b. catch
Handles the exception thrown by the try block.
catch (ExceptionType e) {
// Handle exception
}
c. throw
Used to explicitly throw an exception.
void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18.");
}
}
d. throws
Declares the exceptions a method might throw, ensuring the caller is aware.
void readFile() throws IOException {
FileReader file = new FileReader("nonexistent.txt");
}
e. finally
Executes a block of code regardless of whether an exception occurs or not. It is often used for cleanup operations like
closing files or releasing resources.
try {
int result = 10 / 2;
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
System.out.println("Execution of finally block");
}

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);
}
}

public class Main {


void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be at least 18.");
} else {
System.out.println("Age is valid.");
}
}

public static void main(String[] args) {


Main obj = new Main();
try {
obj.checkAge(16);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

6. Best Practices for Exception Handling


1. Catch specific exceptions instead of using a generic Exception.
2. Use finally to release resources.
3. Avoid unnecessary use of throws for runtime exceptions.
4. Log exceptions for debugging purposes.
5. Use custom exceptions for meaningful error messages.
UNIT-6: String Handling

String Handling in Java


Java provides a robust set of classes and methods for handling and manipulating strings. The primary classes used for string
handling are:
1. String: Immutable sequence of characters.
2. StringBuffer: Mutable sequence of characters (thread-safe).
3. StringBuilder: Mutable sequence of characters (not thread-safe, but faster).

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"

4. toString() and valueOf() Methods


toString() Method:
Converts an object into a string representation.
Example:
Integer num = 10;
String str = num.toString(); // "10"
valueOf() Method:
Converts primitive types or objects into a string.
Example:
int num = 10;
String str = String.valueOf(num); // "10"
UNIT-7: Java I/O Stream
Java I/O Streams
Java provides a rich set of classes for input and output (I/O) operations, which are part of the java.io package. Streams
handle data flow (input or output) in the form of bytes or characters.

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.*;

public class ByteStreamExample {


public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream("input.txt");
FileOutputStream output = new FileOutputStream("output.txt");

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.*;

public class CharacterStreamExample {


public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");

int data;
while ((data = reader.read()) != -1) { // Read character by character
writer.write(data); // Write character by character
}

reader.close();
writer.close();
}
}

4. Reading Console Input


Java provides classes like BufferedReader and Scanner for reading console input.
Using BufferedReader:
import java.io.*;

public class ConsoleInputExample {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Hello, " + name + "!");
}
}
Using Scanner:
import java.util.Scanner;

public class ConsoleInputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}

5. Writing Console Output


You can use System.out to write console output:
System.out.println("Hello, World!"); // Prints with a newline
System.out.print("Hello, "); // Prints without a newline
System.out.printf("My age is %d years.", 25); // Formatted output

6. Reading and Writing Files


Reading a File
Using BufferedReader for efficiency:
import java.io.*;

public class ReadFileExample {


public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Writing to a File
Using BufferedWriter:
import java.io.*;

public class WriteFileExample {


public static void main(String[] args) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, this is a test!");
writer.newLine();
writer.write("Writing to a file is easy.");
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

4. Accessing a Collection Using Iterator and forEach


a. Iterator Interface
The Iterator interface provides methods to traverse through a collection, remove elements, and check for the next element.
Methods:
• hasNext(): Returns true if there is another element in the collection.
• next(): Returns the next element in the collection.
• remove(): Removes the last element returned by the iterator.
Example:
import java.util.*;

public class IteratorExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

Iterator<String> iterator = list.iterator();


while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}
Output:
Apple
Banana
Cherry
b. forEach Method
forEach is a default method in the Iterable interface that allows you to iterate over elements using a lambda expression or
method reference.
Example:
import java.util.*;

public class ForEachExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.forEach(element -> System.out.println(element));
}
}
Output:
Apple
Banana
Cherry
Alternatively, using method references:
list.forEach(System.out::println);

5. Summary of Collection Classes and Operations


Class/Interface Description Common Operations
ArrayList Resizable array for List interface. Allows random access. add(), get(), remove(), size()
Doubly linked list for List and Deque interfaces. Efficient for insertions addFirst(), addLast(), removeFirst(),
LinkedList
and deletions at both ends. removeLast()
Unordered set implementation of the Set interface. Does not allow
HashSet add(), remove(), contains(), size()
duplicates.
TreeSet A sorted set that does not allow duplicates. add(), remove(), first(), last()
HashMap Maps keys to values. put(), get(), containsKey(), remove()
PriorityQueue A queue where elements are processed in priority order. add(), poll(), peek()

You might also like