Final Copy for Exam (JAVA-Web Technology)
Final Copy for Exam (JAVA-Web Technology)
HTML Structure: HTML (Hyper Text Markup Language) is the standard markup language for
creating web pages and web applications. It provides the basic structure for a webpage and allows
content to be presented and linked through the internet. HTML uses tags (such as <html>, <body>,
<p>, etc.) to structure and format content.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Heading</h1>
</body>
</html>
1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
3. <head>: Contains meta-information about the HTML document (e.g., title, character
encoding).
4. <title>: Sets the title of the webpage, which appears on the browser tab.
5. <body>: Contains all the visible content, such as headings, paragraphs, images, links, etc.
1. Block-Level Elements:
o Block elements take up the full width available and start on a new line.
2. Inline Elements:
o Inline elements do not start on a new line and only take up as much width as
needed.
o These elements structure the text content on the page, such as paragraphs,
headings, and lists.
5. Form Elements:
o These elements are used to create interactive forms to collect user input.
7. Interactive Elements:
HTML Tags: HTML (Hyper Text Markup Language) tags are used to structure and format content
on the web. Tags are enclosed within angle brackets, and most come in pairs with an opening and
closing tag, although some are self-closing. Here’s a brief overview of common HTML tags and their
types:
1. Structural Tags
<html>: The root element that encloses the entire HTML document.
2. Heading Tags
Used for titles and headings, with six levels, from <h1> (highest) to <h6> (lowest).
<strong> and <em>: Emphasize text with semantic meaning, making it bold or italic,
respectively.
<a>: Creates a hyperlink, allowing navigation to other pages or resources. Uses the href
attribute to specify the link target.
<img>: Embeds an image. Uses src to specify the image file, alt for alternative text (self-
closing).
<video> and <audio>: Embed video and audio content, respectively. They have attributes for
controls, autoplay, and loop.
7. List Tags
8. Table Tags
<input>: Defines an input field. Types include text, password, submit, etc. (self-closing).
Provide meaning to the HTML structure, helping search engines and accessibility tools
understand content better.
HTML Lists: In HTML, lists are used to group related items together and display them in a
structured way. There are three main types of lists in HTML:
o Each item is marked with a number or letter, depending on the specified type.
o Syntax:
<ol type="1"> <!-- type can be "1", "A", "a", "I", "i" --> It is comment
<li>First item</li>
<li>Second item</li>
</ol>
1: Numbers (default)
A: Uppercase letters
a: Lowercase letters
o Displays items in a bulleted format, with each item having a bullet or symbol in front.
o Syntax:
<ul style="list-style-type: disc;"> <!-- list-style-type can be "disc", "circle", or "square" -->
<li>First item</li>
<li>Second item</li>
</ul>
square: Square
o Syntax:
<dl>
<dt>HTML</dt>
<dt>CSS</dt>
</dl>
HTML Table: In HTML, tables are used to organize and display data in a tabular format (rows
and columns). Here’s an overview of HTML tables and their types:
An HTML table is created using the <table> element, with rows defined by <tr> (table row) elements.
Within each row, data cells are represented by <td> (table data) elements, and header cells (which
are typically bold) are represented by <th> (table header) elements.
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
1. Basic Table: A simple table with rows and columns, useful for displaying basic data without
complex formatting.
2. Bordered Table: A table with borders around cells and rows. You can add borders using CSS
or by using the border attribute directly in HTML (though this approach is deprecated).
<table border="1">
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
3. Striped Table: A table where rows are shaded alternatively. This is commonly achieved using
CSS to improve readability.
4. Hoverable Table: Rows change color when hovered over. This is often used in interactive data
tables.
5. Responsive Table: Tables that adjust to fit different screen sizes. This often involves CSS
media queries or overflow properties to make tables scrollable on smaller screens.
6. Fixed Header Table: A table where the header row stays fixed at the top while scrolling. This
is useful for large data tables and is achieved with CSS positioning.
HTML Link: In HTML, a link is an element that connects or links one page to another, either
within the same website or to an external website. The primary HTML element for creating links is
the <a> (anchor) tag, which is used to link to another document or resource.
1. Internal Link
o Also used to navigate to specific sections within the same page using an anchor ID
(e.g., <a href="#section1">Go to Section 1</a>).
2. External Link
o The target="_blank" attribute can be added to open the link in a new tab.
3. Email Link
o Links to an email address to open the default mail client with the recipient’s address
filled in.
o You can also predefine a subject and body using URL encoding (e.g., <a
href="mailto:[email protected]?subject=Hello&body=Message">Email
Us</a>).
4. Telephone Link
o Creates a link that allows users to call a number directly when clicked on mobile
devices.
o Can use the download attribute to specify the filename, like this: <a href="file.pdf"
download="example.pdf">Download PDF</a>.
target: Defines where the linked document will open (e.g., _blank for a new tab).
HTML Images: In HTML, images are an essential part of web content, providing visual
elements that enhance user experience. Here’s a brief overview of HTML images and their types:
HTML Form: HTML forms are used to collect user input and send it to a server for processing.
Forms are essential for web interactivity, allowing users to submit data, such as login credentials,
search queries, feedback, and more. The <form> element wraps the entire form and specifies the
submission method and destination.
o Allows users to enter an email address, with validation for proper format.
o Used to enter numeric values with options to specify min, max, and step.
o Multiple radio buttons with the same name attribute work as a group.
8. Textarea (<textarea></textarea>)
Basic Example
<form action="/submit" method="post">
<label for="name">Name:</label>
<label for="email">Email:</label>
<label for="password">Password:</label>
<label for="gender">Gender:</label>
<label for="male">Male</label>
<label for="female">Female</label><br><br>
<label for="bio">Bio:</label><br>
</form>
HTML Frame: In HTML, frames are used to divide a webpage into multiple sections, allowing
each section to load different documents independently. Although frames are not as commonly used
today due to responsive web design and the prevalence of CSS for layout, they were previously
popular for organizing content. HTML frames are defined within a <frameset> tag, and each
individual frame is represented by a <frame> tag. Here’s a brief overview of HTML frames and their
types:
1. Frameset Frame:
o The <frameset> tag is used in place of the <body> tag when using frames.
o Attributes like rows and cols specify how the frames are divided, either horizontally
or vertically.
o Example:
<frameset rows="50%,50%">
<frame src="frame1.html">
<frame src="frame2.html">
</frameset>
o The <iframe> element allows you to embed another HTML page within the current
page, providing more flexibility than the traditional <frameset>.
o It’s used more frequently in modern HTML as it doesn’t require replacing the <body>
tag and can be embedded inline within the content.
o Example:
3. NoFrames:
o The <noframes> tag is used to provide alternative content for browsers that do not
support frames. Basically it is use to inform user that this webpage is not working for
only this browser
o It is often used within a <frameset> to ensure content is still accessible for users with
older browsers.
o Example:
<noframes>
</noframes>
HTML Style sheets: In HTML, stylesheets are used to control the look and feel of a
webpage, allowing developers to separate content from design. CSS (Cascading Style Sheets) is the
language primarily used for styling HTML documents. Here’s a brief overview of the types of
stylesheets:
1. Inline CSS
Definition: Inline CSS is written directly within the HTML element using the style attribute.
Example:
Pros: Useful for quick changes or unique styling for single elements.
Definition: Internal CSS is written within a <style> tag in the <head> section of an HTML
document.
Usage: It applies to the entire HTML document but does not affect other pages.
Example:
<head>
<style>
h1 {
color: blue;
font-size: 24px;
</style>
</head>
Pros: Useful for single-page styling; keeps CSS centralized within the HTML.
Cons: Increases page load time for larger styles; not reusable across multiple pages.
3. External CSS
Definition: External CSS is written in a separate .css file and linked to the HTML document
using the <link> tag.
Usage: This stylesheet applies to multiple pages, making it ideal for large websites.
Example:
<head>
</head>
Pros: Allows reusability across pages; reduces HTML file size; improves website performance
with caching.
Cons: Requires additional file loading, which can slightly affect page load if not cached.
1. Platform Independence: Java code is compiled into bytecode that can be executed on any
system with a JVM, making it highly portable.
3. Robust and Secure: Java includes strong memory management and security features, making
it suitable for developing reliable applications.
5. Garbage Collection: Automatic memory management simplifies coding and reduces memory
leaks.
6. Simple and Familiar: Java was designed to be easy to learn and closely resembles C++
without complex features like pointers or operator overloading.
7. Interpreted and Compiled: Java is both compiled and interpreted. It’s compiled into
bytecode, which the JVM interprets at runtime, enabling faster execution than purely
interpreted languages.
8. Distributed: Java supports distributed computing, facilitating development for networked
systems with libraries like Remote Method Invocation (RMI) and support for sockets.
9. High Performance: Although slower than languages like C++, Java's Just-In-Time (JIT)
compiler and JVM optimizations enable good performance in various applications.
10. Dynamic and Extensible: Java supports dynamic loading of classes and methods, which helps
adapt to evolving requirements, and integrates easily with native C and C++ libraries for
added functionality.
2. Mobile Applications: Android development relies heavily on Java, which forms the backbone
of the Android operating system.
3. Enterprise Applications: Java Enterprise Edition (Java EE) provides an environment for
developing large-scale, multi-tiered, scalable, and secure applications for large enterprises.
4. Desktop GUI Applications: Java can create graphical user interface applications with tools
like JavaFX and Swing, suitable for cross-platform desktop software.
5. Scientific Applications: Java’s speed and reliability make it useful in scientific applications
that require significant computational power.
6. Embedded Systems: Java is found in embedded systems, including smart TVs, appliances,
and various IoT (Internet of Things) devices due to its stability and portability.
7. Cloud and Big Data: Java is a preferred language for cloud-based applications and big data
platforms due to its robustness and scalability.
Java Virtual Machine (JVM): The Java Virtual Machine (JVM) is a key component of the
Java Runtime Environment (JRE) that enables Java programs to be executed on any device or
operating system with a JVM, making Java a platform-independent language. Here’s a brief overview
of its main aspects:
1. Bytecode Execution: When Java source code is compiled, it’s converted into an intermediate
form called bytecode. The JVM reads and interprets this bytecode, translating it into native
machine code specific to the host machine, which makes Java portable and enables the
"write once, run anywhere" principle.
2. Memory Management: The JVM manages memory efficiently through an automatic garbage
collection process, which recycles unused objects to prevent memory leaks and optimize
performance.
3. Security: The JVM includes a class loader and a bytecode verifier that enhance security. The
class loader loads Java classes into the JVM, while the bytecode verifier checks for illegal
code that could violate Java’s security policies or lead to crashes.
4. Execution Engine: This part of the JVM interprets or compiles bytecode into machine code
using techniques like Just-In-Time (JIT) compilation, which boosts performance by compiling
frequently executed code paths into native code.
6. Multithreading and Concurrency: The JVM provides a robust platform for multithreading,
allowing Java programs to handle multiple threads in parallel, supporting concurrent
applications.
Java Runtime Environment (JRE): The Java Runtime Environment (JRE) is a crucial
part of the Java software platform that allows users to run Java applications on their devices. It
provides the libraries, Java Virtual Machine (JVM), and other components needed to execute Java
programs.
1. JVM (Java Virtual Machine): The JRE includes the JVM, which is responsible for converting
Java bytecode into machine code, allowing the Java application to run on different hardware
platforms without modification. JVM also manages memory and optimizes performance
through techniques like Just-In-Time (JIT) compilation.
2. Core Libraries: The JRE provides a set of essential libraries that Java programs require. These
libraries contain pre-written code for functions like handling data structures, input/output
operations, networking, and graphics.
3. Development Tools: While the JRE itself doesn't contain development tools like the Java
Development Kit (JDK) does, it provides the runtime environment necessary to execute code
after it has been developed and compiled.
4. Portability: By abstracting away the hardware and operating system details, the JRE ensures
that Java applications are platform-independent, aligning with Java’s “write once, run
anywhere” philosophy.
Java Development Kit (JKD): The Java Development Kit (JDK) is a software development
environment used for building applications, applets, and components using the Java programming
language. The JDK is provided by Oracle (as well as some open-source distributions) and includes a
range of tools that aid in Java software development. Here’s a brief overview of its main
components:
2. Java Runtime Environment (JRE): The JDK includes the JRE, which contains the necessary
libraries and files to run Java applications. The JRE itself includes the Java Virtual Machine
(JVM), core libraries, and other essential components for running applications.
3. Java Virtual Machine (JVM): The JVM interprets the compiled bytecode and executes it on
the underlying hardware. It's designed to enable "write once, run anywhere" portability for
Java applications.
4. Development Tools:
o Java Debugger (jdb): A tool for debugging Java applications, allowing developers to
find and fix errors in their code.
5. Additional Libraries: The JDK includes standard Java libraries (Java Standard Edition), which
contain pre-built classes and methods for networking, file handling, data structures, and
more.
JDK Editions:
Standard Edition (SE): General-purpose, used for building a wide variety of applications.
Enterprise Edition (EE): Contains additional libraries and tools for developing large-scale,
multi-tiered, and distributed applications.
Micro Edition (ME): Optimized for embedded systems and mobile devices with limited
resources.
Byte Code: Bytecode is an intermediate code that is generated after compiling source code in
languages like Java. Unlike machine code, which is directly executed by the computer's hardware,
bytecode is executed by a virtual machine (such as the Java Virtual Machine, JVM). This allows
bytecode to be platform-independent because the JVM can run on different operating systems and
architectures, making Java applications portable.
2. Efficiency: Bytecode is a more compact and optimized form of code than source code, which
makes it faster to interpret or further compile (just-in-time compilation in JVMs).
4. Easy Debugging: Since it’s at a level closer to the source code than machine code, debugging
bytecode can be more manageable.
1. Encapsulation:
2. Inheritance:
3. Polymorphism:
4. Abstraction:
1. Hello World
The classic starter program that displays "Hello, World!" in the console.
5. Factorial of a Number
import java.util.Scanner;
double result;
switch (operator) {
scanner.close();
7. Palindrome Checker
Data Types in Java: In Java, data types are divided into two main categories: primitive and
non-primitive (or reference) data types.
Primitive types are the most basic data types in Java. They are predefined by the language and
named by reserved keywords. They include:
byte: 8-bit integer, range from -128 to 127. Used to save memory in large arrays.
int: 32-bit integer, range from -2^31 to 2^31-1. The most commonly used integer type.
long: 64-bit integer, range from -2^63 to 2^63-1. Used when a wider range than int is
needed. Suffix "L" (e.g., 123L) specifies a long literal.
float: 32-bit floating-point number. Used for decimals, especially where memory savings are
needed. Suffix "f" (e.g., 3.14f) specifies a float literal.
double: 64-bit floating-point number. The default type for decimal values.
boolean: Holds one of two values, true or false. Used for simple flags.
char: 16-bit Unicode character. Used to store single characters like 'a', '@', etc.
Non-primitive types are user-defined types that refer to objects. They include classes, interfaces, and
arrays.
String: Represents a sequence of characters. It's immutable, meaning its content cannot
change after it’s created.
Classes and Objects: Classes define object blueprints, and objects are instances of classes.
Interfaces: Define methods that a class must implement, helping achieve abstraction.
Key Differences:
Memory Allocation: Primitive data types are stored in the stack, while non-primitive types
are stored in the heap.
Default Values: Primitive types have default values (like 0 for int, false for boolean), while
reference types default to null.
Mutability: Primitive values are immutable, whereas reference types can be mutable or
immutable based on the implementation (e.g., String is immutable, but StringBuilder is
mutable).
Java Operators: Java operators are symbols that perform operations on variables and values.
Here's a brief overview of the main types of operators in Java:
1. Arithmetic Operators:
2. Unary Operators:
4. Relational Operators:
Operators: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or
equal to), <= (less than or equal to)
5. Logical Operators:
6. Bitwise Operators:
Operators: & (AND), | (OR), ^ (XOR), ~ (complement), << (left shift), >> (right shift), >>>
(unsigned right shift)
7. Ternary Operator:
8. Instanceof Operator:
Java Expressions: In Java, expressions are constructs that evaluate to a single value and are
used as the building blocks for programming logic. Here’s a quick breakdown of key types:
2. Relational Expressions: Compare values using relational operators like ==, !=, <, >, <=, and
>=. These return a boolean value (true or false). For example, boolean isEqual = (5 == 5);.
3. Logical Expressions: Combine multiple conditions using logical operators && (AND), || (OR),
and ! (NOT). They are mainly used in conditional statements. For example, boolean result =
(a > b) && (b < c);.
4. Bitwise Expressions: Perform operations at the bit level using operators like &, |, ^ (XOR), ~
(bitwise NOT), << (left shift), >> (right shift). For example, int shifted = 4 << 1;.
5. Assignment Expressions: Assign values to variables using = and can include compound
assignments like +=, -=, *=, /=, etc. For example, int x = 10; or x += 5;.
7. Method Call Expressions: Involves calling methods or functions with specific arguments. For
example, int length = str.length();.
9. Type Casting Expressions: Explicitly converts a value from one data type to another. For
example, int x = (int) 10.5;.
10. Object Creation Expressions: Create new instances of objects using new. For example,
Strings= new String("Hello");.
11. Increment and Decrement Expressions: Modify a variable’s value by 1 using ++ or --. For
example, x++ or --y.
12. String Concatenation Expression: Joins strings using the + operator. For example, "Hello, " +
name.
Java Control Statements: Java control statements control the flow of execution
based on certain conditions, looping constructs, and decision-making logic. Here’s a brief overview
of the major types of control statements in Java:
1. Decision-Making Statements:
Java Selection Statements: Java provides several selection (or decision-making)
statements that allow a program to take different paths based on conditions. Here’s a brief overview
of each:
Java Iteration Statements: In Java, iteration statements, also known as loops, allow for
executing a block of code repeatedly based on certain conditions. Here are the main types:
Java Jump Statements: In Java, jump statements are used to transfer control to other
parts of a program. They help manage the flow of execution and improve code readability. Here are
the primary jump statements in Java:
Module-III Classes & Inheritance:
Classes in Java: In Java, a class is a blueprint or template that defines the structure and
behavior of objects. Each class in Java can contain fields (variables) and methods (functions), and it
serves as a foundational building block for object-oriented programming (OOP). Here’s a breakdown
of the main aspects of Java classes:
Types of Class: In Java, classes are the fundamental building blocks of object-oriented
programming. Here are the main types of classes in Java, each serving a unique purpose:
1.Final Class: When a variable, function, or class is declared final, its value persists throughout
the program. Declaring a method with the final keyword indicates that the method cannot be
overridden or change by subclasses. That is a class that is marked final cannot be subclasses. This
is very useful when creating immutable classes such as String classes. A class cannot be mutated
unless it is declared final. If only all the members of the class is final then it can’t be mutated
otherwise it can be mutated
2.Abstract Class:
3.Concrete Class: A normal class with an implementation for all of its methods and no abstract
methods is called a concrete class. They are not permitted to have any processes that are not in
use at the time. If it implements all of its methods, a concrete class can extend its parent, an
abstract class, or an interface. It’s a fully working, instantiable class.
4.Enum Class: A class that defines a fixed set of constants. Enum classes are implicitly final and
extend java.lang.Enum, making them type-safe and ensuring that only a limited set of values can
be used. Example: DayOfWeek.
5.Inner Class: We can define a class within a class in Java, and these classes are referred to as
nested classes. It’s used to logically arrange classes and achieve encapsulation. The outer class
members (including private) can be accessed by the inner class.
A. Nested Inner Class: It has access to an outer class’s private instance variables. The
access modifiers private, protected, public, and default can be applied to any
instance variable.
B. Anonymous Inner Class: Basically, these classes are declared without any name.
C. Static Nested Class: These classes are like static members of the outer class.
D. Method Local inner Class: An inner class can be declared within a method of an
outer class.
Declaring a class: In Java, a class is a blueprint for creating objects. Declaring a class in Java
follows a simple structure, and here’s how we can do it:
Example
Types of Constructors:
Use of static Keyword: In Java, the “static” keyword is used to define members (variables,
methods, blocks, or nested classes) that belong to the class itself rather than to instances of the
class. Here are the main uses of the “static” keyword in Java:
1. Static Variables:
2. Static Methods:
3. Static Block:
A block of code marked with static { }, which runs only once when the class is first loaded.
Often used for initializing static variables.
4. Static Classes:
An inner class can be made static, which means it can be accessed without an instance of the
outer class.
Static inner classes cannot access non-static members of the outer class directly.
Inner Class: In Java, an inner class is a class defined within another class. Inner classes are
useful for logically grouping classes that are only used in one place and can help improve
encapsulation by allowing access to the outer class's private members. Java supports several types
of inner classes:
1. Same Method Name, Different Parameters: Methods have the same name but differ in
parameter types, order, or count.
2. Compile-time Polymorphism: Method overloading is a type of compile-time (static)
polymorphism, as the decision of which method to invoke is made at compile time.
3. Return Type: The return type can be different, but it alone does not distinguish overloaded
methods. There must be a difference in parameter types or count.
4. Examples:
Inheritance in Java: In Java, inheritance is a fundamental concept that allows a class to
inherit fields and methods from another class. It promotes code reusability, allows for method
overriding, and enables polymorphism. Here's a quick overview:
1. Base Class (Superclass): The class that is inherited from. Also called the parent or base or
superclass.
2. Derived Class (Subclass): The class that inherits from the base class. Also called the child or
subclass. It gains access to all non-private fields and methods of the superclass.
3. extends Keyword: Used to establish inheritance. For example, class Dog extends Animal { }
means Dog inherits properties from Animal.
4. super Keyword: Used to access superclass methods and constructors. For example,
super.methodName() or super() to call the superclass's constructor.
5. Object Class: In Java, all classes implicitly inherit from the Object class, which is the root of
the inheritance hierarchy.
Types of Inheritance: In Java, inheritance allows a class to acquire the properties (fields and
methods) of another class. There are five main types of inheritance in Java:
1. Single Inheritance: A class inherits from only one superclass. This means that a subclass has
only one direct superclass.
o Example: class Dog extends Animal { }
2. Multilevel Inheritance: A class derives from another class, which is also derived from
another class, forming a hierarchy of inheritance.
o Example: class Animal { }, class Mammal extends Animal { }, class Dog extends
Mammal { }
3. Hierarchical Inheritance: Multiple classes inherit from a single superclass.
o Example: class Animal { }, class Dog extends Animal { }, class Cat extends Animal { }
4. Multiple Inheritance (Not directly supported in Java): Java does not allow a class to inherit
from multiple classes due to the "Diamond Problem." However, multiple inheritance can be
achieved through interfaces.
o Example using Interfaces: interface Flyable { }, interface Swimmable { }, class Duck
implements Flyable, Swimmable { }
5. Hybrid Inheritance (Combination of two or more types of inheritance): Java does not
support hybrid inheritance with classes directly, but it can be achieved by using interfaces.
Use of super keyword in Java: The super keyword in Java is used to refer to the
immediate parent class of an object. It serves several purposes:
1. Access Parent Class Constructor: You can use super() to call the constructor of the
immediate parent class. This is often used when the child class needs to inherit or initialize
attributes from the parent class.
2. Access Parent Class Methods: super can be used to call a method from the parent class if it
is overridden in the child class
3. Access Parent Class Variables: When a variable name in the child class is the same as in the
parent class, super helps distinguish between them.
Method Overriding: In Java, method overriding is a feature that allows a subclass (child
class) to provide a specific implementation of a method that is already defined in its superclass
(parent class). The overridden method in the child class must have the same name, return type, and
parameters as the method in the parent class. Method overriding is a core concept of polymorphism
in Java, allowing objects to be treated as instances of their superclass while still invoking the child
class's methods.
1. Same Signature: The method in the child class must have the same method signature
(name, parameters, and return type) as the one in the parent class.
2. @Override Annotation: Using the @Override annotation is recommended to ensure you’re
actually overriding a method and not creating an overloaded version by mistake.
3. Access Modifier: The access modifier of the overriding method cannot be more restrictive
than the method in the parent class.
4. Dynamic Binding: At runtime, Java determines which method to execute based on the
object type, enabling dynamic method dispatch.
5. Super Keyword: To call the parent class’s method, you can use the super keyword in the
child class.
Abstract Class: In Java, an abstract class is a class that cannot be instantiated directly and is
meant to be subclassed. It serves as a blueprint for other classes, defining common properties and
methods that can be shared among its subclasses. Here are the key points:
1. Declaration: Use the abstract keyword to declare an abstract class. It can contain both
abstract methods (without an implementation) and concrete methods (with an
implementation).
2. Abstract Methods: Abstract classes may have abstract methods, which are methods
declared without a body. Subclasses must provide implementations for these methods
unless they are also abstract.
3. Inheritance: Abstract classes are intended to be inherited. When a class inherits an abstract
class, it must either implement all abstract methods or be declared abstract itself.
4. Constructor: Although an abstract class cannot be instantiated, it can have a constructor,
which can be called when a subclass is instantiated.
5. Use Case: Abstract classes are useful when we have a base class that should not be
instantiated on its own but provides a common set of methods and fields for its subclasses.
In this example, Animal is an abstract class with an abstract method sound() and a concrete
method eat(). The Dog class extends Animal and provides an implementation for sound().
Use of ‘final’ keyword: In Java, the final keyword is used to apply restrictions on classes,
methods, and variables. Here’s a brief overview:
Module-IV Interface & Package:
Package: In Java, a package is a namespace that groups related classes and interfaces, helping
to organize and manage code efficiently. By grouping classes into packages, Java allows for a
modular approach to programming, where related functionalities are kept together, enhancing code
reusability and preventing naming conflicts.
Key Points:
1. Types of Packages:
o Built-in Packages: Java has predefined packages like java.lang, java.util, java.io, etc.,
which provide essential classes and interfaces.
o User-defined Packages: Developers can create custom packages to organize their
own classes.
4. Access Control: Packages help control access to classes. By default, classes in the same
package have package-private access to each other, but they can be made public for wider
accessibility.
5. Advantages:
Organizational: Makes code easier to locate and maintain.
Reusability: Classes can be reused across different projects.
Namespace Management: Avoids name conflicts, as each package defines a
separate namespace.
These access levels help in encapsulation, allowing control over what parts of a program can access
specific parts of a class.
final: Prevents a class from being subclassed or a method from being overridden.
abstract: Prevents instantiation of a class, allowing only inheritance.
Advantages
1. Abstraction: Defines a contract for what a class should do, without dictating how.
2. Multiple Inheritance Support: Allows a class to gain behavior from multiple
sources.
3. Decoupling: Promotes loosely coupled code, making it easier to test and maintain.
Dynamic Method look up: In Java, dynamic method lookup refers to the process where
the actual method to be called is determined at runtime, rather than compile-time. This behavior is
fundamental to Java's support for polymorphism, allowing different implementations of a method to
be called based on the object type of the instance, not the reference type.
1. Runtime Binding (Late Binding): When a method is overridden in a subclass, Java uses
dynamic method lookup to decide which method to call. The decision is based on the actual
type of the object (the subclass) at runtime, rather than the type of the reference variable.
2. Virtual Method Table (VTable): Java uses a virtual method table to achieve dynamic method
lookup efficiently. Each class has a VTable storing pointers to instance methods. At runtime,
the JVM checks the object’s class, finds the appropriate method in the VTable, and invokes
it.
3. Polymorphism: Dynamic method lookup is key to polymorphism, allowing us to call methods
on references of the superclass type and have the subclass methods executed if overridden.
In the below example, even though myDog is of type Animal, the sound() method in Dog is
called at runtime because of dynamic method lookup.
Module-IV Exception Handling:
1. Exception Classes: Java uses an extensive hierarchy of exception classes. All exceptions are
derived from Throwable, which has two main subclasses:
o Error: Serious problems that applications shouldn’t try to catch (e.g.,
OutOfMemoryError).
o Exception: Issues that programs might want to handle, divided into:
Checked Exceptions: Must be handled or declared in the method signature
(e.g., IOException).
Unchecked Exceptions (Runtime): Usually programming errors (e.g.,
NullPointerException).
2. Try-Catch Block: This is the core structure of exception handling:
o try: Wraps the code that may throw an exception.
o catch: Catches specific exceptions and defines how to handle them.
o finally: Executes code regardless of whether an exception was thrown, often used
for cleanup.
3. Throwing Exceptions: We can manually throw exceptions using the throw keyword, often in
custom validation logic.
4. Throws Keyword: When a method might throw a checked exception, it must declare this in
its signature using throws.
5. Custom Exceptions: Java allows you to create custom exception classes by extending
Exception or RuntimeException, providing flexibility in handling domain-specific errors.
Try: In Java, try is used to define a block of code that may throw an exception. It is part of
exception handling, where code that might throw an exception is enclosed in a try block, and
possible exceptions are caught using a catch block. Optionally, a finally block can be added to
execute code regardless of whether an exception occurs.
Throw: In Java, throw is a keyword used to explicitly throw an exception. When a situation arises
in which a method cannot proceed as expected (for example, invalid input or failed resource
allocation), we can use throw to create and throw an exception object, passing it up the call stack for
handling.
Throws: In Java, the throws keyword is used in method declarations to indicate that the method
may throw certain types of exceptions. By listing the exceptions a method can throw, throws helps
signal to other parts of the program (or developers using the method) that they need to handle or
propagate these potential errors.
Finally: In Java, finally is a block associated with try and catch statements that is used to execute
code regardless of whether an exception occurs or not. The finally block is especially useful for
cleanup operations, like closing files, releasing resources, or other important tasks that need to be
performed to ensure smooth operation, even if an error occurs.
Exception types: In Java, exceptions are objects that describe an unusual or erroneous
condition that arises during runtime. They are classified mainly into three categories:
1. Checked Exceptions: These exceptions are checked at compile-time, meaning the compiler
requires handling these exceptions, either by using a try-catch block or by declaring the
exception using the throws keyword in the method signature. Common checked exceptions
include:
o IOException: Issues with input/output operations, like reading a file that doesn’t
exist.
o SQLException: Problems in database operations.
o ClassNotFoundException: When an application tries to load a class through its name
but cannot find it.
2. Unchecked Exceptions: These exceptions are not checked at compile-time, so the compiler
doesn’t require explicit handling. They occur due to programming errors, such as accessing
an out-of-bounds index in an array. Common unchecked exceptions include:
o NullPointerException: When there’s an attempt to use null as if it were an object.
o ArrayIndexOutOfBoundsException: Attempting to access an invalid index in an
array.
o ArithmeticException: Errors like division by zero.
3. Errors: Errors represent serious issues that applications typically cannot handle, as they
occur outside the control of the Java program (often related to system-level issues). They are
unchecked but are more severe than exceptions. Common errors include:
o OutOfMemoryError: When the JVM runs out of memory.
o StackOverflowError: When the stack memory limit is exceeded, usually due to deep
or infinite recursion.
Built in Exceptions:
String Buffer: In Java, StringBuffer is a class used to represent strings that can be modified,
contrasting with the immutable String class. Key features of StringBuffer include:
• Mutability: Unlike strings, StringBuffer objects are mutable. This means we can change, add, or
remove characters from a StringBuffer object without creating a new one.
• Synchronized for Thread Safety: StringBuffer operations are thread-safe as the methods are
synchronized. This means it can be safely used in a multithreaded environment where multiple
threads are modifying the same StringBuffer object.
• Dynamic Expansion: A StringBuffer automatically adjusts its capacity (size) when necessary. If the
internal buffer overflows, it is automatically made larger to accommodate more characters.
• Performance: Due to its mutability, StringBuffer is more performance-efficient than String when
dealing with strings that require frequent modifications. This efficiency comes from avoiding the
creation of multiple immutable string objects.
• Common Operations: StringBuffer provides various methods for string manipulation like append()
(to add text at the end), insert() (to add text at a specific position), delete() and deleteCharAt() (to
remove text), reverse() (to reverse the content), and more.
• Conversion to String: You can convert a StringBuffer back to a String when needed using the
toString() method.
String Operations :
Character Extractions: In Java, we can extract characters from a string using various
methods provided by the String class. Here are the main ways to perform character extractions in
Java:
(here only the syntax is important that means the methods which we are used to extract any
character from string)
String comparisons: In Java, string comparison can be done in multiple ways, primarily
using ==, equals(), and compareTo() methods. Here’s a breakdown of each approach:
***This methods are not applicable for String Buffer if we want to apply this methods in string buffer
the we have to at first convert the string buffer to string using tostring()***
Searching strings: In Java, searching within a string can be done using several methods from
the String class:
Modifying a string: In Java, the String class is immutable, meaning once a String object is
created, it cannot be changed. However, there are methods in the String class that can create a
modified copy of the original string. Here are some of these methods:
To String() and valueOf() methods: In Java, both toString() and valueOf() methods
are used for converting objects to their String representation, but they differ in their use and
behavior. Here's a brief explanation:
String Buffer operations: In Java, the StringBuffer class is a mutable sequence of
characters, meaning it can be modified after creation. It is particularly useful when frequent
modifications to strings are required. Below is a brief overview of common operations:
Module-VII Java I/O Stream:
I/O Basics: I/O (Input/Output) Streams in Java are mechanisms for reading data from and
writing data to various sources and destinations, such as files, memory, or network sockets. Java's
java.io package provides classes for handling I/O streams, categorized into byte streams and
character streams. Here's a brief overview:
Byte Stream: In Java, byte streams are used to perform input and output (I/O) operations on
binary data (e.g., files, images). These streams read and write data in terms of bytes (8-bit values).
They are part of the java.io package and include two main categories: input streams and output
streams.
Character stream: Character streams in Java are part of the java.io package and are
designed to handle input and output of character data (text). These streams work with 16-bit
Unicode characters, making them ideal for reading and writing text data, including international
characters.
Reading console input: Reading console input in Java can be done using various classes.
Here's a brief overview:
Writing console output: In Java, writing console output is commonly done using the
System.out object, which is a PrintStream provided by the Java standard library. Here are the key
methods used for console output:
Reading and writing files: In Java, reading and writing files is handled through the java.io
and java.nio packages. Below are brief descriptions of commonly used methods for these tasks:
Writing files
Module-VIII Java Utility package:
Collection Overview: The Java java.util package provides a comprehensive set of utility
classes to manage collections, date and time, random number generation, and more. Here's a brief
overview of the Collections Framework within the java.util package:
Collection interfaces: The Collection interfaces in the Java Utility Package (java.util)
provide the foundation for working with groups of objects, also known as collections. These
interfaces define various methods for manipulating collections of objects, such as adding, removing,
and iterating over elements.
Collection classes:
ArrayList in Java (java.util package):
LinkList in Java (java.util package): In Java, the LinkedList class is part of the java.util
package and is a part of the Java Collections Framework. It provides a doubly-linked list
implementation, which means each node in the list has references to both the next and the previous
nodes. Here's a brief overview:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// Add elements
list.add("Apple");
list.add("Banana");
list.addFirst("Grapes");
list.addLast("Orange");
// Display the LinkedList
System.out.println(list); // Output: [Grapes, Apple, Banana, Orange]
// Remove an element
list.remove("Banana");
// Access elements
System.out.println(list.get(1)); // Output: Apple
}
}
Accessing a collection using iterator : In Java, an iterator is a mechanism provided
by the Java Utility package to traverse elements of a collection one by one. It is part of the java.util
package and is implemented by many collection classes, like ArrayList, HashSet, LinkedList, etc.
Note: Traversing a data structure is a fundamental concept that involves visiting each node or
element in the structure. It's also sometimes called iterating over the data structure.
Applet architecture: An applet's lifecycle is managed by methods that define its behaviour
during different stages of execution. The key methods, provided by the java.applet. Applet class, are:
Applet Skeleton: An applet skeleton in Java provides the basic structure for creating Java
applets. An applet is a small Java program that runs inside a web browser or an applet viewer. Here's
a brief explanation of its structure:
Life cycle methods: In Java, an applet is a small program that runs in the context of a web
browser or an applet viewer. The life cycle of an applet is controlled by the browser or applet viewer
and consists of the following methods:
‘setForeground()’ methods:
HTML Applet tag: The <applet> tag in HTML was used to embed Java applets into a web
page. A Java applet is a small application written in Java that can run in a web browser, provided the
browser supports Java (or has the necessary plugin). However, applets and the <applet> tag are now
deprecated and largely obsolete due to security concerns and lack of support in modern browsers.
Passing parameters to an applet: Passing parameters to an applet in Java is done
using the <PARAM> tag in the HTML file that embeds the applet. The parameters are then retrieved
within the applet using the getParameter(String name) method.
Delegation Event Model: The Delegation Event Model is a design pattern used in Java for
event handling, particularly in GUI applications such as those built with Abstract Window Toolkit
(AWT) or Swing. When a GUI component generates an event (such as a button press), it is delegated
to event listeners of that component. These listeners then handle the event by executing the
appropriate code. This model consists of four main components: the event source, the event object,
the event listener, and the event handler. The event source generates the event. The event object
contains information about the event. The event listener is notified when the event occurs. The
event handler handles the event.
Event Classes: Event handling in Java is an important concept in the Abstract Window Toolkit
(AWT) and Swing for handling user actions like button clicks, mouse movements, or keyboard input.
The Event classes are part of the java.awt.event package and encapsulate event-related information.
Sources of Events: In Java AWT (Abstract Window Toolkit), event handling is a mechanism
that manages user interactions with GUI components. Events in Java are objects that represent user
actions or occurrences in the application. A source is an object that generates an event. These are
typically GUI components in AWT.
Event Listener interfaces:
Event handling using adapter class: In Java AWT (Abstract Window Toolkit),
event handling is a crucial concept that allows us to manage user interactions with graphical
components like buttons, text fields, and windows. To simplify event handling, Adapter Classes
are provided as part of the java.awt.event package.
Adapter classes are abstract classes that provide empty implementations of event listener
interfaces. Instead of implementing all the methods of a listener interface, we can extend an
adapter class and override only the methods we need.
Inner and anonymous class: In Java, inner classes and anonymous classes are
commonly used for event handling in Abstract Window Toolkit (AWT) applications due to their
simplicity and ability to encapsulate event-handling code directly within the scope of the GUI
component.
1.Inner Classes in Event Handling: Inner classes are classes defined within another class.
They are often used for event handling in AWT as they can directly access the fields and methods of
the enclosing class.