0% found this document useful (0 votes)
0 views194 pages

Advanced Java

Uploaded by

Varun C BCA
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)
0 views194 pages

Advanced Java

Uploaded by

Varun C BCA
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/ 194

I - M.C.A.

Advanced Java Programming

AVS
COLLEGE OF ARTS & SCIENCE
(AUTONOMOUS)
Attur Main Road, Ramalingapuram, Salem - 106.
(Recognized under section 2(f) & 12(B) of UGC Act 1956 and
Accredited by NAAC with 'A' Grade)
(Co - Educational Institution | Affiliated to Periyar University, Salem
ISO 9001 : 2015 Certified Institution)
[email protected] | www.avscollege.ac.in
Ph : 9426 29322, 94427 00205.

Study Material
Paper Name : Advanced Java Programming
Paper Code : 23PCA06
Batch : 2023-25
Semester : Odd Semester
Staff In charge : Mr.N.SIRANJEEVI

1
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

SYLLABUS
ADVANCED JAVA PROGRAMMING
Course Objectives:
● To gain knowledge of Object Oriented Programming Concept in Java
● To understand usages of String functions in Java
● To familiarize with the applet and swing
● To grasp the concepts on Java Beans
● To comprehend the connection between Relational Database and Java.
UNIT – I
An Overview of Java: Object Oriented Programming- Data Types, Variables, and Arrays:
Primitive Types-Literals Variables - Type Conversion and Casting- Arrays-Operators: Control
Statements-Classes and Methods – Inheritance- Exception Handling.
UNIT – II
String Handling: The String Constructors - String Length - Special String Operations -
Character Extraction - String Comparison - Searching Strings - Modifying a String - Input/Output: The
I/O Classes and Interfaces – File - Byte Streams - Character Streams.
UNIT – III
The Applet Class: Basic Architecture - Applet Skeleton - Display methods - Status Window –
Passing Parameters. Introducing GUI Programming with Swing– Introducing Swing - Swing Is Built on
the AWT- Two Key Swing Features - The MVC Connection - Components and Containers - The Swing
Packages - A Simple Swing Application - Exploring Swing.
UNIT- IV
Java Beans: Introduction - Advantages of Beans – Introspection - The JavaBeans API - A Bean
Example. Servlets: Life Cycle Simple Servlet-Servlet API-Packages-Cookies session tracking.
UNIT – V
Network Programming: Working with URLs- Working with Sockets - Remote Method
Invocation. Introduction to Database Management Systems - Tables, Rows, and Columns - Introduction
to the SQL SELECT Statement - Inserting Rows - Updating and Deleting Existing Rows - Creating and
Deleting Tables - Creating a New Database with JDBC - Scrollable Result Sets.
Text Books:
1. Herbert Schildt, ―Java the Complete Reference‖, 10th edition, McGraw Hill Publishing
Company Ltd, New Delhi, 2017.
2. Tony Goddis, ―Starting out with Java from Control Structures Through Objects‖ 6th Edition,
Pearson Education Limited, 2016

2
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Reference books :
1. Herbert Schildt, Dale Skrien, ―Java Fundamentals – A Comprehensive Introduction‖, TMGH
Publishing Company Ltd, New Delhi, 2013

2. John Dean, Raymond Dean, ―Introduction to Programming with JAVA – A Problem


Solving Approach‖, TMGH Publishing Company Ltd, New Delhi,2012.

xxxxxxxxxxxxxxxx

QUESTION PATTERN (THEORY)


Time: 3 Hours Max. Marks: 75
PART- A: 15x1 = 15 marks
Answer all the questions
Three questions from each unit (Multiple Choice Questions)

PART- B: 2x5 = 10 marks


Answer any TWO questions
One question from each unit

PART- C: 5x10 = 50 marks


Answer all the questions
One question from each unit (either or type)
The Passing minimum shall be 50% out of 75 marks (3 marks)

3
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

ADVANCED JAVA PROGRAMMING


UNIT I
An Overview of Java: Object Oriented Programming- Data Types, Variables, and Arrays:
Primitive Types-Literals Variables - Type Conversion and Casting- Arrays-Operators: Control
Statements-Classes and Methods – Inheritance- Exception Handling.
xxxxxxxxxxxxxxxx
AN OVERVIEW OF JAVA
Java is a widely-used, versatile programming language renowned for its portability,
security, and robustness. Here's an overview of its key aspects:
1. Platform Independence: Java programs are compiled into bytecode, which can run on any
Java Virtual Machine (JVM), making Java platform-independent ("write once, run
anywhere").
2. Object-Oriented: Java is designed around the concept of objects, allowing developers to
create modular programs and reuse code.
3. Syntax: Java syntax is similar to C++, making it relatively easy to learn for developers
familiar with C-style languages.
4. Automatic Memory Management: Java manages memory allocation and deallocation
through its garbage collection mechanism, reducing the complexity of memory management
for developers.
5. Rich API: Java provides a vast library of classes and methods, known as the Java API
(Application Programming Interface), covering everything from data structures to
networking.
6. Multi-threading: Java supports concurrent programming with built-in features for creating
and managing threads, essential for developing responsive and scalable applications.
7. Security: Java places a strong emphasis on security, with features such as bytecode
verification and a robust security manager to protect systems from malicious code.
8. Popular Frameworks and Tools: Java has a rich ecosystem of frameworks (e.g., Spring,
Hibernate) and development tools (e.g., Eclipse, IntelliJ IDEA) that enhance productivity
and facilitate development.
9. Enterprise Capabilities: Java is widely used in enterprise environments due to its stability,
scalability, and support for large-scale applications.
10. Community Support: Java benefits from a large and active community of developers,
providing resources, forums, and libraries to support ongoing development.

4
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Overall, Java's combination of versatility, performance, and community support has made it a
cornerstone of modern software development, powering everything from mobile apps to enterprise
systems.
xxxxxxxxxxxxxxxx
OBJECT ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a fundamental paradigm in Java, shaping how
developers structure and design their applications. Here‟s an overview of how OOP concepts are
applied in Java:
1. Classes and Objects
 Class: A blueprint for creating objects. It defines attributes (fields) and behaviors (methods)
that all instances of the class share.
java
public class Car {
// Fields (attributes)
private String color;
private int speed;
// Constructor
public Car(String color, int speed) {
this.color = color;
this.speed = speed;
}
// Methods (behaviors)
public void accelerate(int increment) {
speed += increment;
}
public void brake(int decrement) {
speed -= decrement;
}
public String getColor() {
return color;
}
public int getSpeed() {
return speed;
}
}
5
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 Object: An instance of a class created using the new keyword. Each object has its own set
of attributes and can invoke methods defined in its class.
java
Car myCar = new Car("Red", 0);
myCar.accelerate(50);
System.out.println("Current speed: " + myCar.getSpeed());
2. Encapsulation
 Encapsulation refers to the bundling of data (fields) and methods that operate on the data
within a single unit (class). It allows for data hiding and helps in achieving modular design.
java
private String color;
private int speed;
3. Inheritance
 Inheritance enables a class (subclass or derived class) to inherit attributes and methods
from another class (superclass or base class). It supports code reuse and promotes the
concept of hierarchical classification.
java
public class ElectricCar extends Car {
private int batteryCapacity;

public ElectricCar(String color, int speed, int batteryCapacity) {


super(color, speed); // Call to superclass constructor
this.batteryCapacity = batteryCapacity;
}

public void chargeBattery() {


// Method specific to ElectricCar
}
}
4. Polymorphism
 Polymorphism allows objects to be treated as instances of their superclass or as instances
of their subclass through method overriding and dynamic method binding.
java
Car myCar = new ElectricCar("Blue", 0, 100);
myCar.accelerate(30); // Accelerate method from ElectricCar is invoked
6
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

5. Abstraction
 Abstraction involves hiding complex implementation details and exposing only the
essential features of an object. In Java, abstraction is achieved through abstract classes and
interfaces.
java
public interface Vehicle {
void accelerate(int increment);
void brake(int decrement);
}

public class Car implements Vehicle {


// Implementing methods from interface
}
6. Association, Aggregation, and Composition
 Association represents the relationship between two or more classes. It can be one-to-one,
one-to-many, or many-to-many.
 Aggregation is a specialized form of association where an object 'has-a' relationship with
another object, but the objects can exist independently.
 Composition is a strong form of aggregation where the child object cannot exist without the
parent object.
Benefits of OOP in Java:
 Modularity: OOP promotes modular design, making it easier to maintain and update code.
 Code Reusability: Inheritance and polymorphism facilitate code reuse, reducing
redundancy.
 Flexibility and Scalability: OOP allows for the creation of complex, scalable systems
through modular, reusable components.
Java‟s strong support for OOP principles makes it a powerful language for building robust, scalable
applications across various domains, from desktop software to enterprise-level systems and web
applications.
xxxxxxxxxxxxxxxx
DATA TYPES, VARIABLES, AND ARRAYS
DATA TYPES
1.Primitive Data Types
Java has eight primitive data types, which are the most basic types built into the language:
 Integral Types:
7
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

o byte: -bit signed integer. Range: -12 to 127.


o short: 16-bit signed integer. Range: -32,76 to 32,767.
o int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
o long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
 Floating-Point Types:
o float: 32-bit IEEE 754 floating-point. Example: 3.14f.
o double: 64-bit IEEE 754 floating-point. Example: 3.14 (default type for decimal
values).
 Other Types:
o boolean: Represents true or false values.
o char: 16-bit Unicode character. Example: 'A', '\u005A'.
2. Reference Data Types
Reference data types (non-primitive data types) include:
 Classes: User-defined types that can contain fields, methods, constructors, etc.
 Interfaces: Similar to classes but with only method signatures.
 Arrays: Objects that store multiple variables of the same type.
3. Default Values
Each primitive data type has a default value when not explicitly initialized:
 byte, short, int, long: 0
 float, double: 0.0
 boolean: false
 char: '\u0000' (NUL character)
4. Type Conversion (Casting)
Java supports both implicit and explicit type conversions:
 Widening (Implicit) Conversion: Automatically occurs when converting smaller data
types to larger ones (e.g., int to long).
 Narrowing (Explicit) Conversion: Requires explicit casting and can lead to data loss if the
value is out of range (e.g., double to int).

Examples
java
// Primitive types
int num1 = 10;
double num2 = 3.14;
boolean flag = true;

8
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

char letter = 'A';


// Reference types
String text = "Hello, Java!";
int[] numbers = {1, 2, 3, 4, 5};

// Default values
int defaultValue; // 0
double defaultDouble; // 0.0
boolean defaultBoolean; // false

// Type conversion
int intValue = 100;
long longValue = intValue; // Widening conversion (implicit)

double doubleValue = 3.14;


int intValue2 = (int) doubleValue; // Narrowing conversion (explicit)

 Understanding Java's data types is essential for writing efficient and correct programs, as it
governs how memory is allocated and how data is manipulated. Primitive types are
optimized for performance, while reference types allow for complex data structures and
object-oriented programming. Mastering these types ensures developers can utilize Java
effectively across a wide range of applications.
xxxxxxxxxxxxxxxx
LITERALS VARIABLES
In Java, literals and variables are fundamental concepts that form the building blocks of
programs. Here‟s an overview of what literals and variables are in Java:
Literals
Literals in Java represent constant values that can be assigned to variables. They are directly
used in the code to denote values of built-in types such as integers, floating-point numbers,
characters, booleans, and strings.

Integer Literals: Represented by whole numbers without decimal points. Examples:


java
int num1 = 10;
long num2 = 1000L; // L or l suffix to denote a long literal
9
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Floating-Point Literals: Represented by numbers with decimal points. Examples:


java
double num1 = 3.14;
float num2 = 2.5f; // f or F suffix to denote a float literal

Character Literals: Represented by single characters enclosed in single quotes. Examples:


java
char letter = 'A';

String Literals: Represented by sequences of characters enclosed in double quotes. Examples:


java
String message = "Hello, Java!";

Boolean Literals: Represented by the keywords true and false.


java
boolean flag = true;

Null Literal: Represented by the keyword null, denoting the absence of a value.
java
String str = null;

VARIABLES
Variables are named memory locations used to store data values that can change during
program execution. Each variable has a data type that determines the type of data it can hold.

Variable Declaration:
Syntax for declaring variables includes specifying the data type and optionally initializing
them with literals:
java
int age; // Declaration of an integer variable named age
double price = 29.99; // Declaration and initialization of a double variable named price
Naming Conventions: Variables follow certain naming rules:

Must begin with a letter, underscore _, or dollar sign $.


10
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Subsequent characters can be letters, digits, underscores, or dollar signs.


Case-sensitive (myVariable is different from MyVariable).
Scope: Refers to the region of the program where a variable is accessible. Variables can have
different scopes, such as local (within a method), instance (within a class but outside any method),
or class (static variables).

Final Variables: Variables can be declared as final, meaning their value cannot be changed once
initialized.

java
final int MAX_COUNT = 100;
Variable Types: In addition to primitive types (like int, double, boolean), Java supports reference
types (like String, arrays, objects), which hold references to objects stored in memory.

Usage Example
java
public class Example {
public static void main(String[] args) {
// Integer and String literals
int num1 = 10;
String message = "Hello, Java!";
// Variable declaration and initialization
double price = 29.99;
// Outputting values
System.out.println("Number: " + num1);
System.out.println("Message: " + message);
System.out.println("Price: " + price);
}
}
xxxxxxxxxxxxxxxx
TYPE CONVERSION AND CASTING
1. Type Conversion (Implicit and Explicit)
Java supports two types of type conversions:

11
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Implicit Conversion (Widening Conversion): This happens automatically when a value of


one data type is assigned to another type that can hold a wider range of values without loss of
information. For example:
java
int numInt = 100;
long numLong = numInt; // Implicit conversion from int to long
In this case, numInt of type int is implicitly converted to numLong of type long.

Explicit Conversion (Narrowing Conversion): This requires a manual casting operation


when a value of one data type is assigned to another type that can hold a narrower range of values.
Explicit casting is done by placing the type in parentheses before the value to be converted. For
example:
java
double numDouble = 3.14;
int numInt = (int) numDouble; // Explicit conversion from double to int
Here, numDouble of type double is explicitly converted to numInt of type int. Note that this
can result in data loss if the value being converted is out of the range of the target type.

2. Type Promotion
 In expressions involving different data types, Java follows rules of type promotion to
determine the data type of the result:
 Numeric Promotion: When different numeric types are involved in an operation, smaller
types are promoted to larger types automatically.
java
int num1 = 10;
double num2 = 3.5;
double result = num1 + num2; // num1 is promoted to double before addition

3. Casting
 Casting is explicitly specifying the data type of an expression. It's necessary when
converting from a wider type to a narrower type, or when converting between different
primitive types and their wrappers (e.g., int to Integer, float to Float). Casting is also used to
clarify code or resolve ambiguity.

Primitive Types:
12
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

java
double numDouble = 3.75;
int numInt = (int) numDouble; // Explicit casting from double to int
Object Types:

java
Object obj = "Hello";
String str = (String) obj; // Casting Object to String

4. Casting with Objects


 When working with object types, casting can be used to treat an object of one class as
another class, provided that there is a valid inheritance relationship or the object implements
the target interface:
 Downcasting: Casting from a superclass to a subclass. It requires explicit casting and may
result in ClassCastException at runtime if the actual object isn't of the target type.
java
Animal animal = new Dog();
Dog dog = (Dog) animal; // Downcasting from Animal to Dog
Upcasting: Casting from a subclass to a superclass. It's implicit and doesn't require explicit casting.

java
Dog dog = new Dog();
Animal animal = dog; // Upcasting from Dog to Animal

5. Avoiding ClassCastException
To avoid ClassCastException, use the instanceof operator to check the type before casting:

java
Animal animal = new Cat();

if (animal instanceof Dog) {


Dog dog = (Dog) animal;
// Proceed with operations specific to Dog
} else {
// Handle cases where animal isn't a Dog
13
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
xxxxxxxxxxxxxxxx
ARRAYS
In Java, arrays are fundamental data structures that allow you to store multiple values of the
same type under a single variable name. Arrays provide efficient access to elements based on their
index. Here‟s an overview of how arrays work in Java:
1. Array Declaration and Initialization
To declare an array variable in Java, you specify the type of elements followed by square brackets
[]:
java
// Declaration of an integer array
int[] numbers;

// Initialization: creating an array with 5 elements


numbers = new int[5];
Alternatively, you can combine declaration and initialization in one line:
java
int[] numbers = new int[5]; // Array with 5 elements
2. Array Elements
 Accessing Elements: Elements in an array are accessed using zero-based indexing (starting
from 0).
java
numbers[0] = 10; // Assigning value to the first element
int firstElement = numbers[0]; // Accessing the first element
 Length: Arrays have a length property that indicates the number of elements in the array.
java
int size = numbers.length; // Returns 5
3. Array Initialization
Arrays can be initialized with values when they are created using an array initializer:
java
int[] numbers = {1, 2, 3, 4, 5}; // Array initialized with specific values
4. Iterating Through Arrays
You can iterate through arrays using loops, such as for loops or enhanced for loops (for-each):
java
for (int i = 0; i < numbers.length; i++) {
14
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println(numbers[i]); // Accessing each element by index


}

// Enhanced for loop (for-each loop)


for (int num : numbers) {
System.out.println(num); // Accessing each element directly
}
5. Multidimensional Arrays
Java supports multidimensional arrays, which are arrays of arrays. You can have arrays of any
number of dimensions:
java
// Declaration and initialization of a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, , 9}
};
int element = matrix[1][2]; // Retrieves element at row 1, column 2 (value 6)
6. Arrays and Objects
Arrays in Java are objects, which means they inherit properties and behaviors from the
java.lang.Object class. However, arrays in Java are of fixed size once initialized, and their size
cannot be changed dynamically.
7. Common Operations
 Sorting: Arrays can be sorted using utility methods from the java.util.Arrays class.
java
int[] numbers = {5, 2, , 1, 3};
Arrays.sort(numbers); // Sorts the array in ascending order
 Searching: You can search for elements in an array using methods like binarySearch() from
the java.util.Arrays class.
java
int index = Arrays.binarySearch(numbers, ); // Searches for the element
Example Usage
java
public class ArrayExample {
public static void main(String[] args) {
15
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

int[] numbers = new int[5]; // Declaration and initialization


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Print all elements in the array


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Arrays are versatile and widely used in Java programming for storing and manipulating
collections of data efficiently. Understanding how to work with arrays is crucial for building many
types of applications, from simple utilities to complex data processing systems.
Types
In Java, arrays are categorized based on the type of elements they can store. Here‟s an
overview of the different types of arrays in Java:'

1. Single-Dimensional Arrays
Single-dimensional arrays, often referred to simply as arrays, are the most common type.
They store elements of the same data type in a contiguous block of memory. Here's how you
declare and initialize a single-dimensional array:

java
// Declaration and initialization of an integer array
int[] numbers = new int[5];
Accessing Elements: Elements in a single-dimensional array are accessed using zero-based
indexing:

java
Copy code
numbers[0] = 10; // Assigning value to the first element
int firstElement = numbers[0]; // Accessing the first element
16
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

2. Multidimensional Arrays
Java supports multidimensional arrays, which are arrays of arrays. These arrays can store
elements in more than one dimension (e.g., rows and columns). Here's an example of a two-
dimensional array:
java
// Declaration and initialization of a 2D integer array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, , 9}
};
Accessing Elements: Elements in a multidimensional array are accessed using nested indexing:

java
int element = matrix[1][2]; // Retrieves element at row 1, column 2 (value 6)

3. Arrays of Objects
Arrays in Java can also hold references to objects of classes, interfaces, or arrays of these
types. This allows you to create arrays of any class type or interface type:

java
// Declaration and initialization of an array of String objects
String[] names = {"Alice", "Bob", "Charlie"};
Accessing Elements: Elements in an array of objects are accessed similarly to other arrays:

java
String name = names[0]; // Retrieves the first element (name "Alice")

4. Variable-Length Argument Lists (Varargs)


Java also supports varargs, which allow you to pass a variable number of arguments to a method.
Varargs are treated as arrays internally by the Java compiler:

java
// Example of a method with varargs
public void printNumbers(int... numbers) {
17
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

for (int num : numbers) {


System.out.println(num);
}
}
Passing Arguments: You can pass multiple arguments of the same type or an array of the specified
type:

java
printNumbers(1, 2, 3); // Passing individual arguments
printNumbers(new int[]{4, 5, 6}); // Passing an array

5. Arrays of Primitive Types vs. Arrays of Objects


In Java, there's a distinction between arrays of primitive types (like int, double, boolean)
and arrays of objects (like String, Integer, custom classes). Arrays of primitive types store actual
values, while arrays of objects store references to objects in memory.
xxxxxxxxxxxxxxxx
OPERATOR
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. In this article, we will learn about Java Operators
and learn all their types.
What are the Java Operators?
Operators in Java are the symbols used for performing specific operations in Java.
Operators make tasks like addition, multiplication, etc which look easy although the
implementation of these tasks is quite complex.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
18
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
: Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Example:
// Java Program to implement
// Arithmetic Operators
import java.io.;
// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {

// Arithmetic operators
int a = 10;
int b = 3;

System.out.println("a + b = " + (a + b));


System.out.println("a - b = " + (a - b));
System.out.println("a b = " + (a b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));

}
}
Output
a + b = 13
a-b=7
a b = 30
a/b=3
a%b=1

19
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a value.

– : Unary minus, used for negating the values.


+ : Unary plus indicates the positive value (numbers are positive without this, however). It
performs an automatic conversion to int when the type of its operand is the byte, char, or short.
This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
– – : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
Post-decrement: Value is first used for computing the result and then decremented.
Pre-Decrement: The value is decremented first, and then the result is computed.
! : Logical not operator, used for inverting a boolean value.
Example:
// Java Program to implement
// Unary Operators
import java.io.;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));


20
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println("Predecrement : " + (--b));


}
}

Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement :
3. Assignment Operator
„=‟ Assignment operator is used to assign a value to any variable. It has right-to-left associativity,
i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and
therefore right-hand side value must be declared before using it or should be a constant.

The general format of the assignment operator is:

variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we can
write a += 5.

+=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
-=, for subtracting the right operand from the left operand and then assigning it to the variable on
the left.
=, for multiplying the left operand with the right operand and then assigning it to the variable on the
left.
/=, for dividing the left operand by the right operand and then assigning it to the variable on the left.
%=, for assigning the modulo of the left operand by the right operand and then assigning it to the
variable on the left.
Example:

// Java Program to implement


// Assignment Operators
import java.io.;
21
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f = 4: " + (f = 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}

Output
f += 3: 10
f -= 2:
f = 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
22
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than.
They return boolean results after the comparison and are extensively used in looping statements as
well as conditional if-else statements. The general format is,

variable relation_operator value


Some of the relational operators are-

==, Equal to returns true if the left-hand side is equal to the right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand side.
<=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-
hand side.
Example:

import java.io.;
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

System.out.println("a > b: " + (a > b));


System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
23
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a
function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the
second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has “Logical NOT”,
which returns true when the condition is false and vice-versa

Conditional operators are:


&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa

Example:

import java.io.;

// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;

System.out.println("x && y: " + (x && y));


System.out.println("x || y: " + (x || y));
24
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println("!x: " + (!x));


}
}
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence
the name Ternary.

The general format is:

condition ? if true : if false


The above statement means that if the condition evaluates to true, then execute the statements after
the „?‟ else execute the statements after the „:‟.

Example:

public class operators {


public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

Output
Max of three numbers = 30
25
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They
can be used with any of the integer types. They are used when performing update and query
operations of the Binary indexed trees.

&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the one‟s complement
representation of the input value, i.e., with all bits inverted.

// Java Program to implement


// bitwise operators
import java.io.;

// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}

Output
26
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

d & e:
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby multiplying or
dividing the number by two, respectively. They can be used when we have to multiply or divide a
number by two. General format-
number shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as multiplying the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as
a result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the
number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left
as a result. The leftmost bit is set to 0.

// Java Program to implement


// shift operators
import java.io.;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;

// using left shift


System.out.println("a<<1 : " + (a << 1));

// using right shift


27
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println("a>>1 : " + (a >> 1));


}
}

Output
a<<1 : 20
a>>1 : 5
9. instance of operator
The instance of the operator is used for type checking. It can be used to test if an object is
an instance of a class, a subclass, or an interface. General format-

object instance of class/subclass/interface

// Java program to illustrate


// instance of operator

class operators {
public static void main(String[] args)
{

Person obj1 = new Person();


Person obj2 = new Boy();

// As obj is of type person, it is not an


// instance of Boy or interface
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy,


// whose parent class is person
// and it implements the interface Myinterface
28
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// it is instance of all of these classes


System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}

class Person {
}

class Boy extends Person implements MyInterface {


}

interface MyInterface {
}

Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
xxxxxxxxxxxxxxxx
CONTROL STATEMENTS
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides statements that can
be used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Decision Making statements
 if statements
29
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 switch statement
Loop statements
 do while loop
 while loop
 for loop
 for-each loop
Jump statements
break statement
continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.
 Simple if statement
 if-else statement
 if-else-if ladder
 Nested if-statement
Let's understand the if-statements one by one.

1) Simple if statement:
 It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.

30
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20
2) if-else statement
 The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.

Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
31
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.

Student.java
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
32
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
33
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}else {
System.out.println("You are not living in India");
}
}
}
Output:

Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.

Student.java

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
34
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2

Loop Statements
In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
 for loop
 while loop
 do-while loop
Let's understand the loop statements one by one.

Java for loop


 In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}
The flow chart for the for-loop is given below.

Control Flow in Java


Consider the following example to understand the proper functioning of the for loop in java.

35
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:

The sum of first 10 natural numbers is 55

Java for-each loop


 Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.

for(data_type var : array_name/collection_name){


//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
36
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
}
}
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript
Java while loop
 The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.
 It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
The syntax of the while loop is given below.

while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.

Control Flow in Java


Consider the following example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
37
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:

Printing the list of first 10 even numbers

0
2
4
6
10
Java do-while loop
 The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.

Control Flow in Java


Consider the following example to understand the functioning of the do-while loop in Java.

Calculation.java
38
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:

Printing the list of first 10 even numbers


0
2
4
6
10
Jump Statements
 Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java break statement
 As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.
39
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

BreakExample.java

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop

Calculation.java

public class Calculation {

public static void main(String[] args) {


// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
40
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in
Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
41
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
xxxxxxxxxxxxxxxx
CLASSES AND METHODS
In Java, classes and methods are core concepts that form the foundation of object-oriented
programming (OOP). Here's an overview of classes and methods in Java:
Classes:
Definition:
A class is a blueprint or template for creating objects in Java.
It defines the properties (fields or attributes) and behaviors (methods) that objects of the class will
have.
Syntax:
A class is defined using the class keyword followed by the class name.
It may include fields (variables) and methods that describe the behavior of objects of that class.

java
// Example of a class definition
public class Car {
// Fields (attributes)
private String brand;
private String model;
private int year;
42
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}

// Methods
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
Instantiation:

Objects are instances of classes created using the new keyword followed by a constructor.
Constructors initialize newly created objects.
java
// Creating objects of the Car class
Car myCar = new Car("Toyota", "Camry", 2023);

Methods:
Definition:
Methods are functions defined within a class that perform specific tasks or operations.
They encapsulate behavior and allow objects to interact with each other.
Types of Methods:

Instance Methods: Associated with objects of the class. They can access instance variables and
other instance methods.

Static Methods: Belong to the class itself rather than any object. They are called using the class
name and can access static variables and other static methods.
Syntax:
43
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Methods have a return type (void if no return value), a name, optional parameters (arguments), and
a body enclosed in curly braces {}.
java
// Example of instance method and static method
public class MyClass {
// Instance method
public void instanceMethod() {
// Method body
}

// Static method
public static void staticMethod() {
// Method body
}
}
Access Modifiers:
Methods can have access modifiers (public, private, protected, or default).
Access modifiers control the visibility and accessibility of methods from other classes.
java
public class MyClass {
// Public method accessible from any class
public void publicMethod() {
// Method body
}

// Private method accessible only within the same class


private void privateMethod() {
// Method body
}

// Protected method accessible within the same package or subclasses


protected void protectedMethod() {
// Method body
}
44
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Default (package-private) method accessible within the same package


void defaultMethod() {
// Method body
}
}
Example Usage:
java
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2023);

// Calling an instance method


myCar.displayInfo();

// Calling a static method (assuming staticMethod() is defined in Car class)


Car.staticMethod();
}
}
 Classes and methods in Java provide a structured way to define objects and their behavior.
Classes encapsulate data (fields) and behavior (methods), and methods define actions that
objects can perform or behaviors they exhibit. Understanding these concepts is fundamental
to writing Java programs that are organized, maintainable, and scalable.
xxxxxxxxxxxxxxxx
INHERITANCE
The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Inheritance in Java Example

45
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends the Bicycle class and class Test is a driver class to run
the program.
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}
class MountainBike extends Bicycle {
public int seatHeight;
46
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public MountainBike(int gear, int speed,


int startHeight)
{
super(gear, speed);
seatHeight = startHeight;
}

public void setHeight(int newValue)


{
seatHeight = newValue;
}
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}

public class Test {


public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

Output
No of gears are 3
speed of bicycle is 100
Java Inheritance Types
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
47
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 Multiple Inheritance
 Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below
figure, „A‟ is a parent class and „B‟ is a child class. The class „B‟ inherits all the properties of the
class „A‟.

Single inheritance
// Java program to illustrate the
// concept of single inheritance
import java.io.;
import java.lang.;
import java.util.;

// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
class Two extends One {
public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
48
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
}

Output
Geeks
for
Geeks

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the
derived class also acts as the base class for other classes. In the below image, class A serves as a
base class for the derived class B, which in turn serves as a base class for the derived class C. In
Java, a class cannot directly access the grandparent‟s members.
Multilevel Inheritance
import java.io.;
import java.lang.;
import java.util.;

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}
// Child class Two inherits from class One
class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}
// Child class Three inherits from class Two
class Three extends Two {
// Method to print "Geeks"
49
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public void print_lastgeek() {


System.out.println("Geeks");
}
}
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();
// Calling method from class Two
g.print_for();
// Calling method from class Three
g.print_lastgeek();
}
}
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
subclass. In the below image, class A serves as a base class for the derived classes B, C, and D.
Hierarchical-Inheritance-in-Java
// Java program to illustrate the
// concept of Hierarchical inheritance
class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
50
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes. Please note that Java does not support multiple inheritances with classes. In
Java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is
derived from interfaces A and B.

Multiple Inheritance
51
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Java program to illustrate the


// concept of Multiple inheritance
import java.io.;
import java.lang.;
import java.util.;

interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
52
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn‟t support
multiple inheritances with classes, hybrid inheritance involving multiple inheritance is also not
possible with classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want
to involve multiple inheritance to implement Hybrid inheritance.
Hybrid Inheritance
Java IS-A type of Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is
used to achieve inheritance.
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
Now, based on the above example, in Object-Oriented terms, the following are true:-

SolarSystem is the superclass of Earth class.


SolarSystem is the superclass of Mars class.
Earth and Mars are subclasses of SolarSystem class.
Moon is the subclass of both Earth and SolarSystem classes.

class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
53
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class Moon extends Earth {


public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

System.out.println(s instanceof SolarSystem);


System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem);
}
}
Output
true
true
true
Advantages Of Inheritance in Java:
Code Reusability: Inheritance allows for code reuse and reduces the amount of code that needs to
be written. The subclass can reuse the properties and methods of the superclass, reducing
duplication of code.
Abstraction: Inheritance allows for the creation of abstract classes that define a common interface
for a group of related classes. This promotes abstraction and encapsulation, making the code easier
to maintain and extend.
Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be used to
model real-world objects and their relationships.
Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to take on
multiple forms. Subclasses can override the methods of the superclass, which allows them to
change their behavior in different ways.
Disadvantages of Inheritance in Java:
Complexity: Inheritance can make the code more complex and harder to understand. This is
especially true if the inheritance hierarchy is deep or if multiple inheritances is used.
Tight Coupling: Inheritance creates a tight coupling between the superclass and subclass, making
it difficult to make changes to the superclass without affecting the subclass.
xxxxxxxxxxxxxxxx

54
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

EXCEPTION HANDLING
Exception handling in Java is a mechanism that allows you to handle runtime errors, known
as exceptions, gracefully without terminating the program abruptly. Exceptions occur during the
execution of a program when something unexpected happens, such as division by zero, accessing
an array out of bounds, or attempting to open a file that does not exist. Here's an overview of how
exception handling works in Java:
Types of Exceptions:
Checked Exceptions:
These are exceptions that the compiler forces you to handle or declare in a throws clause.
Examples include IOException, SQLException, etc.
Unchecked Exceptions (Runtime Exceptions):
These exceptions do not need to be explicitly handled or declared.
Examples include ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.
Errors:
These are serious issues that usually cannot be handled by your application (e.g.,
OutOfMemoryError, StackOverflowError).
Generally, you should not try to handle errors programmatically.
Exception Handling Keywords:
try:
The try block is used to enclose the code that may throw an exception.
catch:
The catch block is used to handle the exception that is thrown in the try block.
It must be preceded by a try block.
finally:
The finally block is used to execute important code such as closing a resource, regardless of
whether an exception is thrown or not.
It follows the try or catch block.
throw:
The throw keyword is used to explicitly throw an exception.
It is followed by an instance of Throwable (usually Exception or Error).
throws:
The throws keyword is used in method declarations to specify that the method might throw one or
more types of exceptions.
It specifies the exceptions that a method can throw but does not handle.
55
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Example of Exception Handling:


java
Copy code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {


public static void main(String[] args) {
BufferedReader reader = null;
try {
// Opening a file
reader = new BufferedReader(new FileReader("input.txt"));

// Reading lines from the file


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handling IOException
System.err.println("IOException: " + e.getMessage());
} finally {
// Closing the file regardless of whether an exception occurred or not
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Error closing BufferedReader: " + e.getMessage());
}
}
}
}
Explanation:
56
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

try block: Contains the code that might throw an exception, in this case, reading from a file.
catch block: Handles the IOException that might be thrown by the try block.
finally block: Ensures that the file resource (reader) is closed, even if an exception occurs or not.
throw keyword: Used to explicitly throw an exception, for example, if a condition is met that
should cause an exceptional case.
Best Practices:
Handle exceptions as close to the point of occurrence as possible for better readability and
maintainability.
xxxxxxxxxxxxxxxx
UNIT I - QUESTION BANK
MULTIPLE CHOICE QUESTIONS
1. Which of the following is not a primitive data type in Java?
A. int B. float C. string D. char
Answer: C. string
2. What is the default value of a boolean variable in Java?
A. true B. false C. null D. 0
Answer: B. false
3. Which of the following statements is correct about arrays in Java?
A. An array can store elements of only the same data type.
B. Arrays are of fixed size once they are created.
C. Array elements can be accessed using negative indices.
D. Array index starts from 1.
Answer: B. Arrays are of fixed size once they are created.
4. What is the result of the following operation in Java?
```java
int a = 15;
float b = 4.5f;
float result = a / b;
```
A. 3.0 B. 3 C. 3.333 D. Compilation Error
Answer: B. 3
5. Which of the following is an implicit type conversion in Java?
A. double to float B. long to int
C. float to double D. int to String
Answer: B. long to int
57
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

6. What will be the output of the following code snippet?


```java
int x = 5;
if (x == 5) {
System.out.println("x is equal to 5");
} else {
System.out.println("x is not equal to 5");
}
```
A. x is equal to 5 B. x is not equal to 5 C. Compilation Error
D. Runtime Error Answer: A. x is equal to 5
7. In Java, a subclass inherits from a superclass using which keyword?
A. extends B. inherits C. implements D. inherits_from
Answer: A. extends
. Which of the following keywords is used to handle exceptions in Java?
A. try B. catch C. throw D. All of the above
Answer: D. All of the above
9. Which of the following concepts in Java is used to implement multiple interfaces in a class?
A. Overloading B. Overriding C. Inheritance D. Interface
Answer: D. Interface
10. Which of the following is true about Java methods?
A. A method can have a different name from its class.
B. A method can return multiple values.
C. A method cannot take any arguments.
D. A method can have more than one return statement.
Answer: A. A method can have a different name from its class.
FIVE MARK & TEN MARK QUESTIONS
1. Explain the concept of type conversion and casting in Java.
2. Discuss the concept of exception handling in Java.
3. Describe the principles of object-oriented programming (OOP) in Java. Discuss the key
features of OOPs
4. Describe the role of methods (functions) in Java programming.
5. Explain the concept of literals and variables in Java.
6. Discuss the role of arrays in Java. Explain how arrays are declared, initialized, and
accessed.
58
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

7. What are control statements in Java? Explain the different types of control statements (if-
else, switch, loops) with examples.
8. Explain the concept of inheritance in Java. Discuss how inheritance promotes code
reusability and describe the types of inheritance supported in Java.
9. Discuss the various types of operators available in Java.
10. Discuss the different data types available in Java. Explain primitive data types.
xxxxxxxxxxxxxxxx UNIT I END xxxxxxxxxxxxxxxx

59
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

UNIT – II
String Handling: The String Constructors - String Length - Special String Operations -
Character Extraction - String Comparison - Searching Strings - Modifying a String - Input/Output: The
I/O Classes and Interfaces – File - Byte Streams - Character Streams.
xxxxxxxxxxxxxxxx
STRING HANDLING
String handling in Java is a crucial aspect of programming due to the widespread use of
strings for representing textual data. Here's an overview of Java string handling, including its
features, operations, and common practices:
Features of Java Strings:
1. Immutable: Strings in Java are immutable, meaning their values cannot be changed once they are
created. Operations on strings like concatenation actually create new strings.
2. String Pool: Java maintains a string pool, which is a pool of unique string literals. Strings created
using string literals are stored in the string pool to conserve memory and improve performance.
3. String Concatenation: Strings can be concatenated using the `+` operator or `concat()` method.
Concatenation results in a new string being created.
4. String Comparison: Strings can be compared using `equals()` method for content comparison and
`==` for reference comparison (checking if two references point to the same object in memory).
5. String Manipulation: Java provides numerous methods for manipulating strings, such as
`length()`, `charAt()`, `substring()`, `toLowerCase()`, `toUpperCase()`, `trim()`, etc.
6. String Formatting: Java supports string formatting using `String.format()` method or `printf()`
method (from `System.out`).

Operations on Strings:
- Creating Strings:
```java
String str1 = "Hello";
String str2 = new String("World");
```
- Concatenation:
```java
String message = str1 + " " + str2;
String fullName = str1.concat(" ").concat(str2);
```

60
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Accessing Characters:
```java
char firstChar = str1.charAt(0);
```
- Substring:
```java
String substring = str1.substring(2, 4); // Returns "ll"
```
- Comparing Strings:
```java
boolean isEqual = str1.equals(str2); // Content comparison
boolean isSameObject = (str1 == str2); // Reference comparison
```
- Formatting Strings:
```java
String formattedString = String.format("Hello, %s!", name);
System.out.printf("Hello, %s!", name);
```
Common Practices in String Handling:
- Use `StringBuilder` for Mutable Strings: When you need to perform a lot of string manipulations
(especially concatenations) in a loop, use `StringBuilder` for efficiency, as it avoids creating
multiple intermediate string objects.
- Avoid String Concatenation in Loops: Concatenating strings inside loops can be inefficient due to
the creation of new string objects repeatedly. Use `StringBuilder` instead.
- Use `equals()` for Content Comparison: Always use `equals()` method to compare string contents
rather than `==`, which checks for reference equality.
- String Manipulation Methods: Familiarize yourself with the various methods available in the
`String` class (`substring()`, `indexOf()`, `replace()`, etc.) as they can simplify many common string
operations.
Example:
```java
public class StringHandlingExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
61
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Concatenation
String message = str1 + " " + str2;
// Substring
String subStr = message.substring(6); // Returns "World"
// Comparing Strings
boolean isEqual = str1.equals(str2);
// String formatting
String formattedString = String.format("Hello, %s!", "Java");
System.out.println(message);
System.out.println(subStr);
System.out.println(isEqual);
System.out.println(formattedString);
}
}
xxxxxxxxxxxxxxxx
THE STRING CONSTRUCTORS
In Java, the `String` class provides several constructors that allow you to create string
objects in different ways. Here's an overview of the various constructors available for creating
strings:
Constructors of the String Class:
1. String Literal:
- Strings created using double quotes (`" "`).
- These strings are stored in the string pool.
```java
String str1 = "Hello";
```
2. Empty String:
- Creates an empty string with no characters.
```java
String str2 = "";
```
3. String Object (Using `new` keyword):
- Creates a new string object with the specified content.
- This does not use the string pool.
```java
62
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

String str3 = new String("World");


```
4. String from Character Array:
- Creates a new string from a character array.
```java
char[] charArray = {'J', 'a', 'v', 'a'};
String str4 = new String(charArray);
```
5. String from Unicode Character Array:
- Creates a new string from a subset of the character array.
```java
char[] unicodeArray = {'\u004A', '\u0061', '\u0076', '\u0061'};
String str5 = new String(unicodeArray, 1, 3); // Creates "ava" from index 1 to 3
```
6. String from Bytes:
- Creates a new string from an array of bytes using the platform's default charset.
```java
byte[] byteArray = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str6 = new String(byteArray);
```
7. String from Bytes with Charset:
- Creates a new string from an array of bytes using a specified charset.
```java
byte[] byteArrayUtf = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str7 = new String(byteArrayUtf, StandardCharsets.UTF_);
```
Notes:
- String Immutability: Once a string object is created, its value cannot be changed. Any operation
that modifies a string actually creates a new string object.
- String Pool: String literals (`" "`) are stored in the string pool, a special area in the Java heap
memory, to conserve memory and improve performance by reusing already existing strings.
- Performance Considerations: Use string literals (`" "`) for constant strings whenever possible
because they are shared in the string pool. Use `new String()` only when necessary, such as when
creating strings from byte arrays or character arrays that need to be modified.
Example Usage:
63
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
public class StringConstructorExample {
public static void main(String[] args) {
// Using different constructors of String class
String str1 = "Hello"; // String literal
String str2 = ""; // Empty string
String str3 = new String("World"); // String object
char[] charArray = {'J', 'a', 'v', 'a'};
String str4 = new String(charArray); // String from character array
byte[] byteArray = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str5 = new String(byteArray); // String from bytes

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}
```
Understanding these constructors allows you to create strings in Java using different sources
and formats, depending on your programming needs.

In Java, the `String` class provides several constructors that allow you to create string objects in
different ways. Here's an overview of the various constructors available for creating strings:
xxxxxxxxxxxxxxxx
THE STRING CONSTRUCTORS
1. String Literal:
- Strings created using double quotes (`" "`).
- These strings are stored in the string pool.
```java
String str1 = "Hello";
```
2. Empty String:
- Creates an empty string with no characters.
64
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
String str2 = "";
```
3. String Object (Using `new` keyword):
- Creates a new string object with the specified content.
- This does not use the string pool.
```java
String str3 = new String("World");
```
4. String from Character Array:
- Creates a new string from a character array.
```java
char[] charArray = {'J', 'a', 'v', 'a'};
String str4 = new String(charArray);
```
5. String from Unicode Character Array:
- Creates a new string from a subset of the character array.
```java
char[] unicodeArray = {'\u004A', '\u0061', '\u0076', '\u0061'};
String str5 = new String(unicodeArray, 1, 3); // Creates "ava" from index 1 to 3
```
6. String from Bytes:
- Creates a new string from an array of bytes using the platform's default charset.
```java
byte[] byteArray = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str6 = new String(byteArray);
```
7. String from Bytes with Charset:
- Creates a new string from an array of bytes using a specified charset.
```java
byte[] byteArrayUtf = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str7 = new String(byteArrayUtf, StandardCharsets.UTF_);
```
 String Immutability: Once a string object is created, its value cannot be changed. Any
operation that modifies a string actually creates a new string object.
65
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 String Pool: String literals (`" "`) are stored in the string pool, a special area in the Java heap
memory, to conserve memory and improve performance by reusing already existing strings.
 Performance Considerations: Use string literals (`" "`) for constant strings whenever
possible because they are shared in the string pool. Use `new String()` only when necessary,
such as when creating strings from byte arrays or character arrays that need to be modified.
Example Usage:
public class StringConstructorExample {
public static void main(String[] args) {
// Using different constructors of String class
String str1 = "Hello"; // String literal
String str2 = ""; // Empty string
String str3 = new String("World"); // String object
char[] charArray = {'J', 'a', 'v', 'a'};
String str4 = new String(charArray); // String from character array
byte[] byteArray = {72, 101, 10, 10, 111}; // ASCII values for "Hello"
String str5 = new String(byteArray); // String from bytes

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}
```
xxxxxxxxxxxxxxxx
STRING LENGTH
In Java, the length of a string refers to the number of characters it contains. The length of a
string can be determined using the `length()` method provided by the `String` class. Here‟s how
you can work with string length in Java:
String Length in Java:
1. Using the `length()` Method:
- The `length()` method returns an integer value representing the number of characters in the
string.

66
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
String str = "Hello, Java!";
int length = str.length(); // length is 12
```
2. Handling Empty Strings:
- An empty string (`""`) has a length of 0.
```java
String emptyStr = "";
int emptyLength = emptyStr.length(); // emptyLength is 0
```
3. Iterating Over String Characters:
- You can iterate over each character of a string using the `length()` method in conjunction with
the `charAt()` method.
```java
String text = "Java is awesome";
int len = text.length();
for (int i = 0; i < len; i++) {
char ch = text.charAt(i);
System.out.println("Character at position " + i + " is " + ch);
}
```
4. Null Handling:
- If a string reference variable is `null`, invoking `length()` on it will result in a
`NullPointerException`.
```java
String nullStr = null;
// int nullLength = nullStr.length(); // This will throw NullPointerException
```
5. Performance Considerations:
- The `length()` method in Java is efficient and operates in constant time O(1) because the length
of a string is stored internally and updated whenever the string is modified.
Example Usage:
Here‟s a simple Java program demonstrating the use of the `length()` method to determine
and display the length of a string:

67
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
public class StringLengthExample {
public static void main(String[] args) {
String str = "Hello, Java!";
int length = str.length();
System.out.println("Length of the string '" + str + "' is: " + length);

// Iterating over each character


System.out.println("Characters in the string:");
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.println("Character at position " + i + " is " + ch);
}
}
}
```
Output:
Length of the string 'Hello, Java!' is: 12
Characters in the string:
Character at position 0 is H
Character at position 1 is e
Character at position 2 is l
Character at position 3 is l
Character at position 4 is o
Character at position 5 is ,
Character at position 6 is
Character at position 7 is J
Character at position is a
Character at position 9 is v
Character at position 10 is a
Character at position 11 is !
xxxxxxxxxxxxxxxx

68
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

SPECIAL STRING OPERATIONS


In Java, string operations go beyond basic concatenation and comparison. There are several
special operations and methods available in the `String` class that facilitate various string
manipulations. Here's an overview of some of these special string operations:
Special String Operations in Java:
1. Substring Extraction (`substring()`):
- Extracts a portion of the string starting from a specified index up to (but not including) another
index.
```java
String str = "Hello, Java!";
String substr = str.substring(7); // "Java!"
String substr2 = str.substring(7, 11); // "Java"
```
2. Concatenation (`concat()`):
- Combines two strings together and returns a new string.
```java
String str1 = "Hello";
String str2 = "World";
String result = str1.concat(" ").concat(str2); // "Hello World"
```
3. String Comparison (`equals()` and `compareTo()`):
- Checks if two strings have the same content (`equals()`).
- Compares two strings lexicographically (`compareTo()`).
```java
String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equals(str2); // false (case-sensitive)
int compareResult = str1.compareTo(str2); // < 0 because 'h' < 'H' in ASCII
```
4. Whitespace Removal (`trim()`):
- Removes leading and trailing whitespace characters from the string.
```java
String str = " Hello, Java! ";
String trimmedStr = str.trim(); // "Hello, Java!"
```
69
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

5. Case Conversion (`toUpperCase()` and `toLowerCase()`):


- Converts all characters in the string to uppercase or lowercase.
```java
String str = "Hello, Java!";
String upperCaseStr = str.toUpperCase(); // "HELLO, JAVA!"
String lowerCaseStr = str.toLowerCase(); // "hello, java!"
```
6. String Replacement (`replace()`):
- Replaces all occurrences of a specified character or substring with another character or
substring.
```java
String str = "Hello, World!";
String replacedStr = str.replace("World", "Java"); // "Hello, Java!"
```
7. Splitting Strings (`split()`):
- Splits the string into an array of substrings based on a delimiter.
```java
String str = "apple,banana,grape";
String[] fruits = str.split(","); // {"apple", "banana", "grape"}
```
. Checking Prefix and Suffix (`startsWith()` and `endsWith()`):
- Checks if the string starts or ends with a specified prefix or suffix.
```java
String str = "Hello, Java!";
boolean startsWithHello = str.startsWith("Hello"); // true
boolean endsWithJava = str.endsWith("Java!"); // true
```
9. Finding Characters or Substrings (`indexOf()` and `lastIndexOf()`):
- Returns the index of the first occurrence (`indexOf()`) or last occurrence (`lastIndexOf()`) of a
character or substring within the string.
```java
String str = "Hello, Java!";
int index = str.indexOf('J'); // 7
int lastIndex = str.lastIndexOf('a'); // 10
```
70
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

10. Converting to/from Character Arrays (`toCharArray()` and `valueOf(char[])`):


- Converts the string to a character array (`toCharArray()`).
- Converts a character array to a string (`valueOf(char[])`).
```java
String str = "Hello";
char[] charArray = str.toCharArray(); // {'H', 'e', 'l', 'l', 'o'}
String strFromCharArray = String.valueOf(charArray); // "Hello"
```
Example Usage:
Here‟s an example demonstrating some of these special string operations in Java:
```java
public class SpecialStringOperations {
public static void main(String[] args) {
String str = " Hello, Java! ";
// Substring extraction
String substr = str.substring(7); // "Java! "
String substr2 = str.substring(7, 11); // "Java"
// Concatenation
String concatStr = "Hello".concat(" ").concat("World"); // "Hello World"
// Case conversion
String upperCaseStr = str.toUpperCase(); // " HELLO, JAVA! "
String lowerCaseStr = str.toLowerCase(); // " hello, java! "
// Trim whitespace
String trimmedStr = str.trim(); // "Hello, Java!"
// String replacement
String replacedStr = str.replace("Java", "World"); // " Hello, World! "
// Splitting strings
String fruitsStr = "apple,banana,grape";
String[] fruits = fruitsStr.split(","); // {"apple", "banana", "grape"}
// Checking prefix and suffix
boolean startsWithHello = str.startsWith("Hello"); // false
boolean endsWithJava = str.endsWith("Java!"); // false
// Finding characters or substrings
int index = str.indexOf('J'); // 9
int lastIndex = str.lastIndexOf('a'); // 14
71
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Converting to/from character arrays


char[] charArray = str.toCharArray(); // {' ', ' ', ' ', 'H', 'e', 'l', 'l', 'o', ',', ' ', 'J', 'a', 'v', 'a', '!', ' ', ' ', '
'}
String strFromCharArray = String.valueOf(charArray); // " Hello, Java! "
// Output results
System.out.println("Original String: " + str);
System.out.println("Substring: " + substr);
System.out.println("Concatenated String: " + concatStr);
System.out.println("Uppercase String: " + upperCaseStr);
System.out.println("Lowercase String: " + lowerCaseStr);
System.out.println("Trimmed String: " + trimmedStr);
System.out.println("Replaced String: " + replacedStr);
System.out.println("Split String: " + Arrays.toString(fruits));
System.out.println("Index of 'J': " + index);
System.out.println("Last Index of 'a': " + lastIndex);
System.out.println("String from Character Array: " + strFromCharArray);
}
}
```
These special string operations provide flexibility and power for manipulating strings in
Java, making it easier to perform common tasks such as substring extraction, concatenation, case
conversion, and more.
xxxxxxxxxxxxxxxx
CHARACTER EXTRACTION
Character extraction in Java involves accessing individual characters from a string or
converting strings to character arrays for manipulation. Here are the primary methods and
approaches for character extraction in Java:
Methods for Character Extraction:
1. Accessing Characters by Index:
- Use the `charAt()` method to retrieve a specific character from a string based on its index.
Indexing starts at 0.
```java
String str = "Hello, Java!";
char firstChar = str.charAt(0); // 'H'
char sixthChar = str.charAt(5); // ','
72
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```
2. Converting String to Character Array:
- Use the `toCharArray()` method to convert a string into an array of characters. This allows
direct access and manipulation of individual characters.
```java
String str = "Hello, Java!";
char[] charArray = str.toCharArray();
char thirdChar = charArray[2]; // 'l'
```
3. Iterating Over Characters:
- Iterate over each character in a string using a loop and the `charAt()` method.
```java
String str = "Hello, Java!";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
System.out.println("Character at index " + i + ": " + ch);
}
```
Example Usage:
Here's an example demonstrating these methods for character extraction in Java:
```java
public class CharacterExtractionExample {
public static void main(String[] args) {
String str = "Hello, Java!";

// Accessing characters by index


char firstChar = str.charAt(0); // 'H'
char sixthChar = str.charAt(5); // ','

// Converting string to character array


char[] charArray = str.toCharArray();
char thirdChar = charArray[2]; // 'l'

// Iterating over characters


System.out.println("Characters in the string:");
73
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);
System.out.println("Character at index " + i + ": " + ch);
}
}
}
```
Output:
```
Characters in the string:
Character at index 0: H
Character at index 1: e
Character at index 2: l
Character at index 3: l
Character at index 4: o
Character at index 5: ,
Character at index 6:
Character at index 7: J
Character at index : a
Character at index 9: v
Character at index 10: a
Character at index 11: !
```
Notes:
- Indexing: String characters in Java are indexed starting from 0.
- Immutable Strings: Strings in Java are immutable, meaning their characters cannot be directly
modified. To manipulate strings, you typically create new strings.
- Performance Considerations: The `charAt()` method provides O(1) time complexity for accessing
individual characters, making it efficient for most practical purposes.
- These methods for character extraction provide flexibility and ease of use when working with
strings in Java, allowing you to access, manipulate, and iterate over individual characters as needed.
xxxxxxxxxxxxxxxx

74
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

STRING COMPARISON
String comparison in Java involves comparing the content of two strings to determine if
they are equal or if one precedes the other lexicographically (alphabetically). Java provides several
methods and approaches for string comparison, each serving different purposes and considerations.
Here‟s an overview of string comparison in Java:
Methods for String Comparison:
1. Using `equals()` Method:
- The `equals()` method compares the content of two strings for equality.
- It is case-sensitive, meaning "Hello" is not equal to "hello".
```java
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // true
```
2. Ignoring Case:
- Use `equalsIgnoreCase()` method to compare strings while ignoring case differences.
- "Hello" is considered equal to "hello".
```java
String str1 = "Hello";
String str2 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true
```
3. Using `compareTo()` Method:
- The `compareTo()` method compares two strings lexicographically (based on the Unicode
values of their characters).
- Returns a negative integer, zero, or a positive integer if the first string is lexicographically less
than, equal to, or greater than the second string, respectively.
```java
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2); // negative value (-1) because "apple" < "banana"
```
4. Using `compareToIgnoreCase()` Method:
- Similar to `compareTo()`, but ignores case differences during comparison.
```java
75
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

String str1 = "apple";


String str2 = "Banana";
int resultIgnoreCase = str1.compareToIgnoreCase(str2); // positive value (1) because "apple" >
"Banana"
```
5. Using `startsWith()` and `endsWith()` Methods:
- `startsWith()` checks if a string starts with a specified prefix.
- `endsWith()` checks if a string ends with a specified suffix.
```java
String str = "Hello, Java!";
boolean startsWithHello = str.startsWith("Hello"); // true
boolean endsWithJava = str.endsWith("Java!"); // true
```
6. Comparing Lexicographical Order:
- For comparing strings lexicographically regardless of case, consider converting them to a
common case (e.g., lowercase) before comparison.
```java
String str1 = "apple";
String str2 = "Banana";
int resultLexicographical = str1.toLowerCase().compareTo(str2.toLowerCase()); // positive value
(1) because "apple" > "banana"
```
Example Usage:

```java
public class StringComparisonExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
String str4 = "World";
String str5 = "banana";
String str6 = "Banana";

// Using equals()
76
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

boolean isEqual = str1.equals(str2); // true


// Using equalsIgnoreCase()
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str3); // true
// Using compareTo()
int result1 = str1.compareTo(str4); // negative value because "Hello" < "World"
// Using compareToIgnoreCase()
int result2 = str5.compareToIgnoreCase(str6); // positive value because "banana" > "Banana"
// Using startsWith() and endsWith()
boolean startsWithHello = str1.startsWith("Hello"); // true
boolean endsWithWorld = str4.endsWith("World"); // true
// Output results
System.out.println("Using equals(): " + isEqual);
System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase);
System.out.println("Using compareTo(): " + result1);
System.out.println("Using compareToIgnoreCase(): " + result2);
System.out.println("Using startsWith(): " + startsWithHello);
System.out.println("Using endsWith(): " + endsWithWorld);
}
}
```
Output:
```
Using equals(): true
Using equalsIgnoreCase(): true
Using compareTo(): -15
Using compareToIgnoreCase(): 32
Using startsWith(): true
Using endsWith(): true
```
Notes:
- Case Sensitivity: Methods like `equals()` and `compareTo()` are case-sensitive by default.
- Performance: String comparison methods in Java (`equals()`, `compareTo()`, etc.) are optimized
for efficiency and should be preferred over manual character-by-character comparisons.
xxxxxxxxxxxxxxxx

77
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

SEARCHING STRINGS
Searching strings in Java involves finding specific substrings or characters within a given
string. Java provides several methods and techniques to perform string searching efficiently. Here
are the primary methods and approaches for searching strings in Java:
Methods for Searching Strings:
1. Finding Substring (`indexOf()` and `lastIndexOf()`):
- The `indexOf()` method returns the index of the first occurrence of a substring within the string.
- The `lastIndexOf()` method returns the index of the last occurrence of a substring within the
string.
```java
String str = "Hello, Java!";
int index1 = str.indexOf("Java"); // 7
int index2 = str.lastIndexOf("a"); // 10
```
2. Checking for Substring (`contains()`):
- The `contains()` method checks whether a substring is present within the string.
```java
String str = "Hello, Java!";
boolean containsJava = str.contains("Java"); // true
```
3. Matching Regular Expressions (`matches()`):
- The `matches()` method checks if the entire string matches a regular expression pattern.
```java
String str = "Hello123";
boolean isMatch = str.matches("[a-zA-Z0-9]+"); // true (contains letters and digits only)
```
4. Splitting Strings (`split()`):
- The `split()` method splits the string into an array of substrings based on a delimiter.
```java
String str = "apple,banana,grape";
String[] fruits = str.split(","); // {"apple", "banana", "grape"}
```
5. Finding Characters (`indexOf()` and `lastIndexOf()` for characters):
- Similar to finding substrings, `indexOf()` and `lastIndexOf()` can also be used to find the index
of a specific character within the string.
78
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
String str = "Hello, Java!";
int indexOfComma = str.indexOf(','); // 5
int lastIndexOfA = str.lastIndexOf('a'); // 10
```
6. Using Regular Expressions (`Pattern` and `Matcher` classes):
- For advanced string searching based on patterns, use the `Pattern` and `Matcher` classes from
`java.util.regex` package.
```java
import java.util.regex.;

String str = "Hello123";


Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(str);
boolean matches = matcher.matches(); // true (contains digits only)
```
Example Usage:
```java
public class StringSearchExample {
public static void main(String[] args) {
String str = "Hello, Java!";
// Finding substring
int index1 = str.indexOf("Java"); // 7
int index2 = str.lastIndexOf("a"); // 10
// Checking for substring
boolean containsJava = str.contains("Java"); // true
// Matching regular expression
String str2 = "Hello123";
boolean isMatch = str2.matches("[a-zA-Z0-9]+"); // true
// Splitting string
String str3 = "apple,banana,grape";
String[] fruits = str3.split(","); // {"apple", "banana", "grape"}
// Finding characters
int indexOfComma = str.indexOf(','); // 5
int lastIndexOfA = str.lastIndexOf('a'); // 10
79
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Using regular expressions with Pattern and Matcher


String str4 = "Hello123";
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(str4);
boolean matches = matcher.matches(); // true (contains digits only)
// Output results
System.out.println("Index of 'Java': " + index1);
System.out.println("Last index of 'a': " + index2);
System.out.println("Contains 'Java': " + containsJava);
System.out.println("Matches pattern: " + isMatch);
System.out.println("Split string: " + Arrays.toString(fruits));
System.out.println("Index of ',': " + indexOfComma);
System.out.println("Last index of 'a': " + lastIndexOfA);
System.out.println("Matches digits pattern: " + matches);
}
}
```
Output:
```
Index of 'Java': 7
Last index of 'a': 10
Contains 'Java': true
Matches pattern: true
Split string: [apple, banana, grape]
Index of ',': 5
Last index of 'a': 10
Matches digits pattern: true
```
Notes:
- Performance: String searching methods in Java (`indexOf()`, `contains()`, etc.) are optimized for
efficiency and handle most practical scenarios effectively.
- Regular Expressions: For complex pattern-based searching, using `Pattern` and `Matcher` classes
provides powerful capabilities.

80
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Understanding these methods and techniques for searching strings allows you to efficiently
manipulate and process string data in Java applications, addressing various search requirements
effectively.
xxxxxxxxxxxxxxxx
MODIFYING A STRING
In Java, strings are immutable, meaning once a `String` object is created, its content cannot
be changed. However, there are several methods and techniques you can use to effectively modify
and manipulate strings. Here‟s how you can achieve various string modifications in Java:

Methods for Modifying Strings:


1. Concatenation (`+` operator or `concat()` method):
- Concatenation is used to append one string to the end of another.
```java
String str1 = "Hello";
String str2 = "World";
String result = str1 + ", " + str2; // "Hello, World"
```
2. Substring Replacement (`substring()` and concatenation):
- Use `substring()` to extract parts of the string and concatenate them with new content.
```java
String str = "Hello, Java!";
String modifiedStr = str.substring(0, 5) + "World!"; // "HelloWorld!"
```
3. StringBuilder and StringBuffer:
- Use `StringBuilder` or `StringBuffer` classes for mutable string operations, especially when you
need to perform multiple modifications efficiently.
```java
StringBuilder sb = new StringBuilder("Hello");
sb.append(", Java!"); // Append
sb.insert(5, "World"); // Insert
sb.replace(7, 11, "Universe"); // Replace
sb.delete(0, 6); // Delete
String result = sb.toString(); // Convert StringBuilder to String
```
4. Replacing Characters or Substrings (`replace()` and `replaceAll()`):
81
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Use `replace()` to replace occurrences of a specific character or substring.


- Use `replaceAll()` with regular expressions for more complex replacements.
```java
String str = "Hello, Java!";
String replacedStr = str.replace("Java", "World"); // "Hello, World!"
String regexReplacedStr = str.replaceAll("[aeiou]", ""); // "Hll, Jv!"
```
5. Converting Case (`toUpperCase()` and `toLowerCase()`):
- Change the case of characters in a string.
```java
String str = "Hello, Java!";
String upperCaseStr = str.toUpperCase(); // "HELLO, JAVA!"
String lowerCaseStr = str.toLowerCase(); // "hello, java!"
```
6. Trimming Whitespace (`trim()`):
- Remove leading and trailing whitespace characters from a string.
```java
String str = " Hello, Java! ";
String trimmedStr = str.trim(); // "Hello, Java!"
```
Example Usage:
```java
public class StringModificationExample {
public static void main(String[] args) {
// Concatenation
String str1 = "Hello";
String str2 = "World";
String result1 = str1 + ", " + str2; // "Hello, World"
// Substring and concatenation
String str3 = "Hello, Java!";
String modifiedStr = str3.substring(0, 5) + "World!"; // "HelloWorld!"
// StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(", Java!"); // "Hello, Java!"
sb.insert(5, "World"); // "HelloWorld, Java!"
82
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

sb.replace(10, 15, "Universe"); // "HelloWorldUniverse!"


sb.delete(5, 15); // "Hello!"
String result2 = sb.toString(); // Convert StringBuilder to String
// Replacing characters or substrings
String str4 = "Hello, Java!";
String replacedStr = str4.replace("Java", "World"); // "Hello, World!"
String regexReplacedStr = str4.replaceAll("[aeiou]", ""); // "Hll, Jv!"
// Converting case
String str5 = "Hello, Java!";
String upperCaseStr = str5.toUpperCase(); // "HELLO, JAVA!"
String lowerCaseStr = str5.toLowerCase(); // "hello, java!"
// Trim whitespace
String str6 = " Hello, Java! ";
String trimmedStr = str6.trim(); // "Hello, Java!"
// Output results
System.out.println("Concatenation result: " + result1);
System.out.println("Modified string: " + modifiedStr);
System.out.println("StringBuilder result: " + result2);
System.out.println("Replaced string: " + replacedStr);
System.out.println("Regex replaced string: " + regexReplacedStr);
System.out.println("Uppercase string: " + upperCaseStr);
System.out.println("Lowercase string: " + lowerCaseStr);
System.out.println("Trimmed string: " + trimmedStr);
}
}
```
Output:
```
Concatenation result: Hello, World
Modified string: HelloWorld!
StringBuilder result: Hello!
Replaced string: Hello, World!
Regex replaced string: Hll, Jv!
Uppercase string: HELLO, JAVA!
Lowercase string: hello, java!
83
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Trimmed string: Hello, Java!


```
Notes:
- Immutability: Remember that `String` objects in Java are immutable, meaning methods like
`replace()`, `toUpperCase()`, etc., return new strings rather than modifying the original string.
- StringBuilder vs StringBuffer: `StringBuilder` is preferred in most cases due to its better
performance in non-thread-safe environments, while `StringBuffer` is thread-safe but slower due to
synchronization.
- Using these methods and techniques allows you to effectively manipulate and modify strings in
Java according to your application's requirements.
xxxxxxxxxxxxxxxx
INPUT/OUTPUT - THE I/O CLASSES AND INTERFACES
In Java, I/O (Input/Output) operations are essential for interacting with external data sources
such as files, network sockets, and standard input/output streams. Java provides a rich set of classes
and interfaces for handling I/O efficiently and flexibly. Here‟s an overview of the key classes and
interfaces related to I/O in Java:
Key Classes and Interfaces for I/O:
1. java.io package:
- This package contains classes for input and output streams, readers, writers, and file operations.
2. InputStream and OutputStream (Abstract Classes):
- `InputStream`: Abstract class representing input stream of bytes.
- `OutputStream`: Abstract class representing output stream of bytes.
```java
InputStream inStream = new FileInputStream("input.txt");
OutputStream outStream = new FileOutputStream("output.txt");
```
3. Reader and Writer (Abstract Classes):
- `Reader`: Abstract class representing character input streams.
- `Writer`: Abstract class representing character output streams.
```java
Reader reader = new FileReader("input.txt");
Writer writer = new FileWriter("output.txt");
```
4. File Class:
- Represents a file or directory pathname in a platform-independent manner.
84
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
File file = new File("input.txt");
```
5. BufferedInputStream and BufferedOutputStream:
- Provide buffering for input and output streams, improving efficiency.
```java
InputStream inStream = new FileInputStream("input.txt");
OutputStream outStream = new FileOutputStream("output.txt");
BufferedInputStream bufferedIn = new BufferedInputStream(inStream);
BufferedOutputStream bufferedOut = new BufferedOutputStream(outStream);
```
6. BufferedReader and BufferedWriter:
- Provide buffering for character input and output streams, improving efficiency.
```java
Reader reader = new FileReader("input.txt");
Writer writer = new FileWriter("output.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
```
7. InputStreamReader and OutputStreamWriter:
- Bridge classes that convert byte streams to character streams and vice versa.
```java
InputStream inStream = new FileInputStream("input.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inStream);
Reader reader = new BufferedReader(inputStreamReader);
OutputStream outStream = new FileOutputStream("output.txt");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outStream);
Writer writer = new BufferedWriter(outputStreamWriter);
```
. Scanner Class:
- Allows easy parsing of primitive types and strings from input streams.
```java
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
```
85
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

9. PrintStream and PrintWriter:


- Provide convenient methods for printing formatted representations of objects to output streams.
```java
PrintStream printStream = new PrintStream(System.out);
PrintWriter printWriter = new PrintWriter(System.out);
```
10. Serializable Interface:
- Marker interface that objects can implement to indicate that they can be serialized to streams.
```java
class MyClass implements Serializable {
// Class implementation
}
```
Example Usage:

```java
import java.io.;
public class IOExample {
public static void main(String[] args) {
try {
// Reading from a file using BufferedReader
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


BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, Java!");
writer.newLine(); // Platform-independent newline
writer.close();

} catch (IOException e) {
86
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

e.printStackTrace();
}
}
}
```
Notes:
- Closeable Interface: Most I/O classes implement the `Closeable` interface, which defines a
`close()` method to release resources associated with the stream.
- Exception Handling: I/O operations may throw `IOException`, so it's crucial to handle exceptions
properly using try-catch blocks or propagate them to the caller.
- Performance: Buffered classes (`BufferedInputStream`, `BufferedOutputStream`, etc.) improve
performance by reducing the number of I/O operations.
- Understanding and utilizing these classes and interfaces enables efficient handling of input and
output operations in Java applications, supporting tasks such as file manipulation, network
communication, and data streaming effectively.
xxxxxxxxxxxxxxxx
FILE
In Java, the `File` class is used to represent file and directory pathnames. It provides
methods for creating, deleting, querying, and manipulating files and directories on the file system.
Here's an overview of how to use the `File` class effectively:
Key Methods and Operations with `File` Class:
1. Creating a `File` Object:
- You can create a `File` object using its pathname in the form of a string or a URI.
```java
// Using pathname
File file = new File("path/to/file.txt");

// Using URI
File fileURI = new File("file:///path/to/file.txt");
```
2. File and Directory Operations:
- Creating Files and Directories:
```java
File newFile = new File("path/to/newfile.txt");
boolean created = newFile.createNewFile(); // Creates a new empty file
87
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

File newDir = new File("path/to/newdir");


boolean dirCreated = newDir.mkdir(); // Creates a new directory
```
- Deleting Files and Directories:
```java
File fileToDelete = new File("path/to/file.txt");
boolean deleted = fileToDelete.delete(); // Deletes the file

File dirToDelete = new File("path/to/dir");


boolean dirDeleted = dirToDelete.delete(); // Deletes the directory
```
- Checking Existence and Properties:
```java
File fileToCheck = new File("path/to/file.txt");
boolean exists = fileToCheck.exists(); // Checks if the file exists
boolean isFile = fileToCheck.isFile(); // Checks if it's a file
boolean isDirectory = fileToCheck.isDirectory(); // Checks if it's a directory

long fileSize = fileToCheck.length(); // Returns the size of the file in bytes


```
- Listing Files and Directories:
```java
File directory = new File("path/to/directory");
File[] files = directory.listFiles(); // Lists files and directories in the directory

for (File file : files) {


System.out.println(file.getName());
}
```
- File Path and Name Operations:
```java
File file = new File("path/to/file.txt");
String fileName = file.getName(); // Returns the name of the file
String filePath = file.getPath(); // Returns the pathname as a string
```
88
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

3. Handling File System Properties:


- File System Roots:
```java
File[] roots = File.listRoots(); // Returns the file system roots
for (File root : roots) {
System.out.println("File system root: " + root.getAbsolutePath());
}
```
- File Permissions and Metadata:
- Java's `java.nio.file` package offers more advanced capabilities for file system operations,
including file attributes and permissions.
Example Usage:
```java
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
// Creating a new file
File newFile = new File("example.txt");
boolean created = newFile.createNewFile();
if (created) {
System.out.println("New file created: " + newFile.getAbsolutePath());
}

// Checking file properties


System.out.println("File exists: " + newFile.exists());
System.out.println("File size: " + newFile.length() + " bytes");
System.out.println("Is a directory: " + newFile.isDirectory());
System.out.println("Is a file: " + newFile.isFile());

// Listing files in a directory


File directory = new File("path/to/directory");
File[] files = directory.listFiles();
if (files != null) {
89
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println("Files in directory:");
for (File file : files) {
System.out.println(file.getName());
}
}

// Deleting a file
boolean deleted = newFile.delete();
if (deleted) {
System.out.println("File deleted: " + newFile.getAbsolutePath());
}

} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Notes:
- File Operations Safety: Always handle exceptions (`IOException` in file operations) to manage
errors gracefully.
- Path Separators: Use `File.separator` or `File.separatorChar` for platform-independent path
separators.
- Performance: File I/O operations may vary in performance based on the underlying file system
and hardware.
- Using the `File` class allows Java programs to interact with the file system effectively, performing
tasks such as creating, deleting, checking existence, and manipulating files and directories as
needed. For more advanced file operations, consider using classes from the `java.nio.file` package,
which provides enhanced file system operations and attributes handling.
xxxxxxxxxxxxxxxx
BYTE STREAMS
In Java, byte streams are used to perform input and output of -bit bytes, which are the basic
units of data in many file systems and networks. Byte streams are typically used for handling
binary data, such as images, audio, and other non-text files. Java provides several classes in the

90
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

`java.io` package for reading from and writing to byte streams efficiently. Here's an overview of
key byte stream classes and their usage:
Key Byte Stream Classes:
1. InputStream and OutputStream:
- `InputStream`: Abstract class representing an input stream of bytes.
- `OutputStream`: Abstract class representing an output stream of bytes.
These are the base classes for all byte stream classes in Java.
2. FileInputStream and FileOutputStream:
- `FileInputStream`: Used to read data from a file as a sequence of bytes.
- `FileOutputStream`: Used to write data to a file as a sequence of bytes.
```java
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {
// Reading from FileInputStream
int byteRead;
while ((byteRead = fis.read()) != -1) {
// Process byteRead
fos.write(byteRead); // Writing to FileOutputStream
}
} catch (IOException e) {
e.printStackTrace();
}
```
3. ByteArrayInputStream and ByteArrayOutputStream:
- `ByteArrayInputStream`: Allows reading from a byte array as a stream of bytes.
- `ByteArrayOutputStream`: Allows writing to a byte array as a stream of bytes.
```java
byte[] data = { 65, 66, 67, 6, 69 }; // Example byte array
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
int byteRead;
while ((byteRead = bais.read()) != -1) {
// Process byteRead
baos.write(byteRead); // Writing to ByteArrayOutputStream
}
91
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

byte[] outputData = baos.toByteArray(); // Get output as byte array


System.out.println(Arrays.toString(outputData));
} catch (IOException e) {
e.printStackTrace();
}
```
4. BufferedInputStream and BufferedOutputStream:
- `BufferedInputStream`: Adds buffering functionality to an input stream, improving performance
by reducing the number of reads from the underlying input stream.
- `BufferedOutputStream`: Adds buffering functionality to an output stream, improving
performance by reducing the number of writes to the underlying output stream.
```java
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("input.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream("output.txt"))) {
int byteRead;
while ((byteRead = bis.read()) != -1) {
// Process byteRead
bos.write(byteRead); // Writing to BufferedOutputStream
}
} catch (IOException e) {
e.printStackTrace();
}
```
5. DataInputStream and DataOutputStream:
- `DataInputStream`: Allows reading primitive Java data types from an input stream in a
machine-independent way.
- `DataOutputStream`: Allows writing primitive Java data types to an output stream in a machine-
independent way.
```java
try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"));
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
// Writing data using DataOutputStream
dos.writeInt(123);
dos.writeDouble(45.67);
92
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Reading data using DataInputStream


int intValue = dis.readInt();
double doubleValue = dis.readDouble();
} catch (IOException e) {
e.printStackTrace();
}
```
Example Usage:
Here's an example demonstrating basic byte stream operations in Java:
```java
import java.io.;
public class ByteStreamExample {
public static void main(String[] args) {
try {
// Example using FileInputStream and FileOutputStream
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");

int byteRead;
while ((byteRead = fis.read()) != -1) {
// Process byteRead (e.g., manipulate or write to fos)
fos.write(byteRead);
}

// Closing streams
fis.close();
fos.close();

// Example using ByteArrayInputStream and ByteArrayOutputStream


byte[] data = { 65, 66, 67, 6, 69 }; // Example byte array
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

while ((byteRead = bais.read()) != -1) {


// Process byteRead (e.g., manipulate or write to baos)
93
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

baos.write(byteRead);
}

byte[] outputData = baos.toByteArray(); // Get output as byte array


System.out.println("Output data: " + Arrays.toString(outputData));

// Closing streams
bais.close();
baos.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Notes:
- Exception Handling: Always handle exceptions (`IOException`) properly when working with byte
streams, especially when performing I/O operations that may fail due to file system errors or other
reasons.
- Buffering: Use buffered byte streams (`BufferedInputStream`, `BufferedOutputStream`) for
improved performance when reading/writing large amounts of data.
- Data Integrity: When reading and writing data, ensure consistency and proper handling of data
types to avoid data corruption or loss.
- Understanding and using byte streams effectively allows Java programs to handle binary data
operations efficiently, supporting tasks such as file manipulation, network communication, and data
processing involving non-textual content.
xxxxxxxxxxxxxxxx
CHARACTER STREAMS
Character streams in Java are used to perform input and output operations for textual data,
where characters are the basic unit of data instead of bytes. They handle Unicode characters and are
designed to handle internationalization (i1n) and localization (l10n) issues effectively. Java
provides several classes in the `java.io` package for reading from and writing to character streams.
Here's an overview of key character stream classes and their usage:

94
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Key Character Stream Classes:


1. Reader and Writer (Abstract Classes):
- `Reader`: Abstract class representing a character stream input.
- `Writer`: Abstract class representing a character stream output.
2. FileReader and FileWriter:
- `FileReader`: Used for reading characters from a file.
- `FileWriter`: Used for writing characters to a file.
```java
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {
// Reading from FileReader
int charRead;
while ((charRead = reader.read()) != -1) {
// Process charRead
writer.write(charRead); // Writing to FileWriter
}
} catch (IOException e) {
e.printStackTrace();
}
```
3. BufferedReader and BufferedWriter:
- `BufferedReader`: Adds buffering functionality to a `Reader`, improving performance by
reducing the number of reads from the underlying input stream.
- `BufferedWriter`: Adds buffering functionality to a `Writer`, improving performance by
reducing the number of writes to the underlying output stream.
```java
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
// Process line
bw.write(line); // Writing to BufferedWriter
bw.newLine(); // Add newline character
}
} catch (IOException e) {
95
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

e.printStackTrace();
}
```
4. CharArrayReader and CharArrayWriter:
- `CharArrayReader`: Allows reading characters from an in-memory character array (`char[]`).
- `CharArrayWriter`: Allows writing characters to an in-memory character array (`char[]`).
```java
char[] data = { 'H', 'e', 'l', 'l', 'o' }; // Example char array
try (CharArrayReader reader = new CharArrayReader(data);
CharArrayWriter writer = new CharArrayWriter()) {
int charRead;
while ((charRead = reader.read()) != -1) {
// Process charRead
writer.write(charRead); // Writing to CharArrayWriter
}
char[] outputData = writer.toCharArray(); // Get output as char array
System.out.println("Output data: " + Arrays.toString(outputData));
} catch (IOException e) {
e.printStackTrace();
}
```
5. InputStreamReader and OutputStreamWriter:
- `InputStreamReader`: Bridge class that converts byte streams into character streams (`Reader`).
- `OutputStreamWriter`: Bridge class that converts character streams into byte streams (`Writer`).
```java
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("input.txt"));
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"))) {
int charRead;
while ((charRead = isr.read()) != -1) {
// Process charRead
osw.write(charRead); // Writing to OutputStreamWriter
}
} catch (IOException e) {
e.printStackTrace();
}
96
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```
Example Usage:
```java
import java.io.;

public class CharacterStreamExample {


public static void main(String[] args) {
try {
// Example using FileReader and FileWriter
FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt");

int charRead;
while ((charRead = fr.read()) != -1) {
// Process charRead (e.g., manipulate or write to fw)
fw.write(charRead);
}

// Closing streams
fr.close();
fw.close();

// Example using BufferedReader and BufferedWriter


BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

String line;
while ((line = br.readLine()) != null) {
// Process line (e.g., manipulate or write to bw)
bw.write(line);
bw.newLine(); // Add newline character
}

// Closing streams
br.close();
97
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

bw.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Notes:
- Exception Handling: Always handle exceptions (`IOException`) properly when working with
character streams, especially when performing I/O operations that may fail due to file system errors
or other reasons.
- Buffering: Use buffered character streams (`BufferedReader`, `BufferedWriter`) for improved
performance when reading/writing large amounts of text data.
- Encoding: When using `InputStreamReader` and `OutputStreamWriter`, specify the character
encoding to ensure proper conversion between byte streams and character streams.
- Unicode Support: Character streams support Unicode characters, making them suitable for
internationalized applications where text data may contain characters from various languages.
- Using character streams allows Java applications to handle textual data effectively, supporting
tasks such as reading/writing text files, parsing textual data, and processing strings in a manner that
is both efficient and supports internationalization requirements.
xxxxxxxxxxxxxxxx
UNIT II QUESTION BANK
MULTIPLE CHOICE QUESTIONS
1. Which of the following statements about Java strings is correct?
- A) Strings in Java are mutable.
- B) Strings can be created using the `new` keyword only.
- C) String literals are stored in a common pool.
- D) Strings can be directly converted to byte arrays.
Answer: C) String literals are stored in a common pool.
2. What is the length of the string `"Hello, World!"`?
- A) 10 - B) 12 - C) 13 - D) 14 Answer: C) 13
3. Which constructor creates an empty string object?
- A) `new String()` - B) `new String("")` - C) `new String(" ")`
- D) `String.empty()` Answer: B) `new String("")`
98
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

4. What does the `trim()` method do in Java?


- A) Removes all whitespace characters from the beginning and end of a string.
- B) Trims the string length to a specified number of characters.
- C) Converts the string to uppercase letters.
- D) Replaces all occurrences of a substring with another substring.
Answer: A) Removes all whitespace characters from the beginning and end of a string.
5. Which method is used to extract a single character from a string at a specific index?
- A) `charAt()` - B) `substring()` - C) `indexOf()` - D) `replace()`
Answer: A) `charAt()`
6. How do you compare two strings for equality in Java?
- A) Using the `==` operator.
- B) Using the `equals()` method.
- C) Using the `compareTo()` method.
- D) Using the `contains()` method.
Answer: B) Using the `equals()` method.
7. Which method is used to find the index of the first occurrence of a substring within a string?
- A) `indexOf()` - B) `lastIndexOf()` - C) `startsWith()` - D) `contains()`
Answer: A) `indexOf()`
. Which statement is true about string immutability in Java?
- A) Immutable strings can be changed after they are created.
- B) StringBuilder and StringBuffer classes are used to create immutable strings.
- C) Modifying a string creates a new string object.
- D) Immutability applies only to string literals.
Answer: C) Modifying a string creates a new string object.
9. Which class is used to represent file and directory pathnames in Java?
- A) `FileInputStream` - B) `File` - C) `FileWriter` - D) `FileSystem`
Answer: B) `File`
10. Which class is used to read bytes from a file in Java?
- A) `FileInputStream` - B) `FileReader` - C) `BufferedReader`
- D) `ByteArrayInputStream`
Answer: A) `FileInputStream`
11. Which class is used to write characters to a file in Java?
- A) `FileReader` - B) `FileWriter` - C) `BufferedReader` - D) `BufferedWriter`
Answer: B) `FileWriter`
FIVE MARK QUESTIONS & TEN MARK QUESTIONS
99
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

1. Explain the different ways to create a string object in Java using constructors. Provide examples
for each method.
2. Discuss the concept of string immutability in Java.
3. Describe the `length()` method in Java strings. How is the length of a string determined, and
what are its implications in string operations?
4. Explain the purpose and usage of the `trim()` method in Java strings
5. Discuss to How is it used to extract characters from a string, and what are its limitations?
6. Compare and contrast the usage of `equals()`, `compareTo()`, and `equalsIgnoreCase()` methods
for string comparison in Java.
7. Explain the significance of the `indexOf()` and `lastIndexOf()` methods in Java strings.
8. Discuss the implications of string immutability on modifying string contents in Java.
9. Explain the role of the `File` class in Java I/O operations.
10. Describe the purpose and functionality of byte streams in Java I/O.

xxxxxxxxxxxxxxxx UNIT II END xxxxxxxxxxxxxxxx

100
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

UNIT – III
The Applet Class: Basic Architecture - Applet Skeleton - Display methods - Status Window
– Passing Parameters. Introducing GUI Programming with Swing– Introducing Swing - Swing Is
Built on the AWT- Two Key Swing Features - The MVC Connection - Components and Containers
- The Swing Packages - A Simple Swing Application - Exploring Swing.
xxxxxxxxxxxxxxxx
THE APPLET CLASS
The `Applet` class in Java is a class that represents a small application or program, typically
designed to be embedded within a web page and run in a web browser. It was primarily used in
early Java applet development for creating interactive and dynamic content on web pages.
Here are some key points about the `Applet` class:
1. Package: It belongs to the `java.applet` package.
2. Hierarchy: The `Applet` class extends the `Panel` class, which means it inherits functionality
for laying out components within its window.
3. Lifecycle Methods: It provides several methods that can be overridden to manage the lifecycle
of the applet, such as `init()`, `start()`, `stop()`, and `destroy()`.
- `init()`: Called when the applet is first loaded.
- `start()`: Called when the applet is about to start running.
- `stop()`: Called when the applet is suspended or minimized.
- `destroy()`: Called when the applet is about to be destroyed.
4. GUI Development: It supports GUI development by allowing components to be added to it,
which are then displayed within the applet's area in the web browser.
5. Deprecated: As of Java 9, the `Applet` class and related APIs are deprecated, mainly due to
security concerns and the decline in usage of Java applets on the web. Modern web applications
typically use other technologies such as HTML5, JavaScript, and CSS for similar functionalities.
6. Security Restrictions: Applets run under a security sandbox imposed by the web browser,
which limits their access to the user's system resources for security reasons.
Here's a simple example of an `Applet` class:
```java
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
@Override
public void init() {
// Initialization code here
101
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

@Override
public void start() {
// Start code here
}

@Override
public void paint(Graphics g) {
// Drawing code here
g.drawString("Hello, World!", 20, 20);
}

@Override
public void stop() {
// Stop code here
}

@Override
public void destroy() {
// Cleanup code here
}
}
```
In this example:
- `init()`, `start()`, `paint()`, `stop()`, and `destroy()` are overridden to define the applet's behavior.
- The `paint()` method is responsible for rendering graphics on the applet's surface.
xxxxxxxxxxxxxxxx
BASIC ARCHITECTURE
The architecture of an applet in Java revolves around its lifecycle, its graphical user
interface (GUI) components, and its interaction with the web browser. Here‟s a breakdown of the
basic architecture of an applet:

102
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

1. Applet Lifecycle
The lifecycle of an applet is managed by the web browser or the applet viewer. It follows these
stages:

- Initialization (`init()` method): This method is called when the applet is first loaded into
memory. It is used to perform initialization tasks such as setting up GUI components, initializing
variables, and loading resources.
- Starting (`start()` method): After initialization, the `start()` method is called. It is used to start
any threads or animations that the applet may have. This method is also called when the user
revisits a page containing the applet after it has been stopped.
- Running: The applet remains in the running state while it is visible on the web page and the
browser is active. During this phase, the applet can respond to user input and update its display as
needed.
- Stopping (`stop()` method): When the applet is no longer visible or the user navigates away from
the page, the `stop()` method is called. It is used to suspend any ongoing activities such as
animations or other processes that are not necessary when the applet is not visible.
- Destroying (`destroy()` method): When the applet is about to be unloaded from memory (for
example, when the user closes the browser or navigates away from the page), the `destroy()`
method is called. This is where cleanup tasks such as releasing resources and freeing memory
should be performed.
2. Applet GUI
- Components: Applets can contain GUI components such as buttons, text fields, labels, and other
AWT or Swing components. These components are added to the applet using methods like `add()`
or by overriding the `paint()` method to draw custom graphics.
- Event Handling: Applets respond to user interactions through event handling. Events such as
button clicks, mouse movements, and keyboard inputs are handled by implementing event listener
interfaces (`ActionListener`, `MouseListener`, `KeyListener`, etc.) and registering these listeners
with the appropriate components.
3. Security Restrictions
- Applets run in a sandboxed environment provided by the web browser. This restricts their access
to the user's system resources such as the file system and network connections.
- Applets must adhere to certain security policies defined by the browser or the Java Runtime
Environment (JRE). Violating these policies can result in security exceptions being thrown.
4. Deployment

103
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Applets are typically deployed by embedding them within HTML pages using the `<applet>` tag
or `<object>` tag (in older versions).

- Modern web standards and security concerns have led to a decline in the use of Java applets in
favor of other technologies such as JavaScript, HTML5, and CSS.
Example Applet Code
```java
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
}
}
```
In this example:
- The `paint()` method is overridden to draw the string "Hello, World!" at coordinates (20, 20) on
the applet's surface.
- This basic architecture gives you a foundational understanding of how applets work in Java.
However, it's important to note that due to security concerns and the evolution of web technologies,
applets are no longer recommended for new development.
xxxxxxxxxxxxxxxx
APPLET SKELETON
Certainly! Below is a basic skeleton of a Java applet that includes the essential methods and
structure:

```java
import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {

// Initialization method
public void init() {
// Initialization code goes here
104
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Starting method
public void start() {
// Start code (e.g., start threads, animations)
}

// Painting method (required for rendering graphics)


public void paint(Graphics g) {
// Drawing code (e.g., draw shapes, text)
g.drawString("Hello, Applet!", 20, 20);
}

// Stopping method
public void stop() {
// Stop code (e.g., suspend threads, animations)
}

// Cleanup method
public void destroy() {
// Cleanup code (e.g., release resources, clean up memory)
}
}
```
1. Imports:
- `import java.applet.Applet;`: Import the `Applet` class from the `java.applet` package, which is
essential for creating applets.
- `import java.awt.Graphics;`: Import the `Graphics` class from the `java.awt` package, which
provides methods for drawing graphics.
2. Class Definition:
- `public class MyApplet extends Applet { ... }`: Defines a class named `MyApplet` that extends
the `Applet` class. This means `MyApplet` inherits the behavior and properties of the `Applet`
class.
3. Lifecycle Methods:

105
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- init(): This method is called when the applet is initialized. It is typically used to perform setup
tasks such as initializing variables, loading resources, and setting up GUI components.

- start(): Called when the applet is about to start running. It is used to start any threads or
animations that the applet may have.

- paint(Graphics g): This method is called whenever the applet needs to repaint its contents. It
receives a `Graphics` object as a parameter, which is used to draw shapes, text, and other graphical
elements on the applet's surface.

- stop(): Called when the applet is about to be stopped, such as when the user navigates away
from the applet's web page. It is used to suspend any ongoing activities that are not necessary when
the applet is not visible.

- destroy(): Called when the applet is about to be destroyed, typically when the applet's web page
is closed or refreshed. It is used to perform cleanup tasks such as releasing resources and freeing
memory.

4. Graphics Drawing:
- In the `paint(Graphics g)` method, a simple text string "Hello, Applet!" is drawn on the applet's
surface using the `drawString()` method of the `Graphics` object (`g.drawString("Hello, Applet!",
20, 20);`).

Deployment:
To deploy and run the applet, you typically embed it within an HTML file using the `<applet>` tag
(for older browsers) or `<object>` tag (for newer browsers). Here‟s an example of embedding the
`MyApplet` class in an HTML file:

```html
<!DOCTYPE html>
<html>
<head>
<title>My Applet Example</title>
</head>
<body>
106
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

<applet code="MyApplet.class" width="300" height="200">


<!-- Optional: Alternative content if applet fails to load -->
Your browser does not support Java applets.
</applet>
</body>
</html>
```
Notes:
- Replace `MyApplet.class` with the actual name of your compiled applet class file.
- Specify the `width` and `height` attributes in the `<applet>` tag to define the initial size of the
applet's display area.
- This skeleton provides a basic framework for developing Java applets. Keep in mind that Java
applets are largely deprecated due to security concerns and the evolution of web technologies, so
it's recommended to use alternative technologies for web development.
xxxxxxxxxxxxxxxx
DISPLAY METHODS
In the context of Java applets, the primary method used for displaying content is the
`paint(Graphics g)` method. This method is overridden from the `java.awt.Component` class, which
the `Applet` class inherits from. Here‟s an explanation of how the `paint(Graphics g)` method
works and how it's used for displaying content in an applet:

`paint(Graphics g)` Method


The `paint(Graphics g)` method is responsible for rendering graphics on the applet's display
area. When the applet needs to display or update its visual content, this method is automatically
called by the system. Here's a breakdown of its characteristics and usage:
- Method Signature:
```java
public void paint(Graphics g)
```
- It's a `public` method, inherited from the `Component` class.
- It takes a `Graphics` object (`g`) as a parameter, which provides methods for drawing shapes,
text, and images on the applet's surface.

- Invocation:

107
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- The `paint(Graphics g)` method is invoked automatically by the system when the applet needs to
redraw its content, such as when it's first displayed, resized, uncovered after being hidden by
another window, or when `repaint()` is called explicitly.

- Drawing Operations:
- Inside `paint(Graphics g)`, you can use methods of the `Graphics` object (`g`) to draw various
elements, such as lines, shapes, text, and images.
- Common drawing methods include:
- `drawLine(int x1, int y1, int x2, int y2)`: Draws a line between the specified coordinates.
- `drawRect(int x, int y, int width, int height)`: Draws a rectangle with the specified dimensions.
- `drawString(String str, int x, int y)`: Draws a string at the specified coordinates.
- `drawImage(Image img, int x, int y, ImageObserver observer)`: Draws an image at the
specified coordinates.

- Double Buffering:
- To reduce flickering when redrawing the applet, especially for animations or frequent updates,
you can implement double buffering. This involves drawing to an off-screen `Image` first and then
copying the entire image to the screen. Here‟s a basic example:

```java
// Declare an off-screen image
private Image offscreenImage;
private Graphics offscreenGraphics;

// Override update method to use double buffering


@Override
public void update(Graphics g) {
// Create off-screen buffer if not initialized or size mismatch
if (offscreenImage == null || offscreenImage.getWidth(this) != getWidth() ||
offscreenImage.getHeight(this) != getHeight()) {
offscreenImage = createImage(getWidth(), getHeight());
offscreenGraphics = offscreenImage.getGraphics();
}

// Clear the off-screen buffer


108
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

offscreenGraphics.clearRect(0, 0, getWidth(), getHeight());

// Call paint method to draw on the off-screen buffer


paint(offscreenGraphics);

// Draw the off-screen buffer to the screen


g.drawImage(offscreenImage, 0, 0, this);
}
```
- Customization:
- Override `paint(Graphics g)` to customize how your applet displays content. For example, you
can create animations, interactive elements, or graphical interfaces using various drawing
operations and event handling.

Example Usage

```java
import java.applet.Applet;
import java.awt.Graphics;

public class DisplayApplet extends Applet {

@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}
}
```
In this example:
- The `paint(Graphics g)` method is overridden to draw the string "Hello, Applet!" at coordinates
(20, 20) on the applet's surface.
xxxxxxxxxxxxxxxx

109
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

STATUS WINDOW
In Java applets, the concept of a "status window" typically refers to a part of the applet's
display area where textual messages or status updates can be shown. This is often used to provide
feedback to the user about ongoing operations or to display debugging information during
development.
Implementing a Status Window in Java Applets

To implement a status window in a Java applet, you can utilize components like `Label`,
`TextArea`, or `TextField` to display text-based information. Here‟s a basic example using a
`Label` component to create a simple status window:

```java
import java.applet.Applet;
import java.awt.Label;
import java.awt.Font;
public class StatusWindowApplet extends Applet {
private Label statusLabel;
@Override
public void init() {
statusLabel = new Label("Status: Ready"); // Initial status message
statusLabel.setFont(new Font("Arial", Font.BOLD, 14)); // Setting font for the label
add(statusLabel); // Adding the label to the applet
}
// Example method to update status
public void updateStatus(String message) {
statusLabel.setText("Status: " + message);
}
// Example method to clear status
public void clearStatus() {
statusLabel.setText("Status: Ready");
}
// Other applet lifecycle methods (start, stop, destroy) can be implemented as needed
}
```
1. Imports and Class Definition:
110
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Import necessary packages (`java.applet.Applet` for the applet functionality and


`java.awt.Label` for creating the label component).
- Define the `StatusWindowApplet` class that extends `Applet`.
2. Initialization (`init()` method):
- Create a `Label` (`statusLabel`) with an initial message ("Status: Ready").
- Set the font for the label using `setFont()` to improve readability (optional).
- Add the `Label` to the applet using `add(statusLabel)`.
3. Updating Status (`updateStatus()` method):
- Define a method (`updateStatus(String message)`) to update the status message displayed in the
`Label`.
- This method sets the text of `statusLabel` to the provided message.
4. Clearing Status (`clearStatus()` method):
- Provide a method (`clearStatus()`) to reset the status message back to its initial state ("Status:
Ready").
5. Usage:
- You can call `updateStatus()` or `clearStatus()` methods from within your applet's logic or event
handlers to dynamically update or clear the status message displayed to the user.
Deploying the Applet
To deploy and run the applet, you typically embed it within an HTML file using the
`<applet>` tag (for older browsers) or `<object>` tag (for newer browsers). Here‟s an example of
embedding the `StatusWindowApplet` class in an HTML file:

```html
<!DOCTYPE html>
<html>
<head>
<title>Status Window Applet Example</title>
</head>
<body>
<applet code="StatusWindowApplet.class" width="300" height="200">
<!-- Optional: Alternative content if applet fails to load -->
Your browser does not support Java applets.
</applet>
</body>
</html>
111
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```
Replace `"StatusWindowApplet.class"` with the actual name of your compiled applet class
file. Specify the `width` and `height` attributes in the `<applet>` tag to define the initial size of the
applet's display area.
 Implementing a status window in a Java applet involves using GUI components like `Label`
to display textual messages to the user.
 The example provided demonstrates how to create a `Label` for displaying status messages
and methods to update or clear the status dynamically.
 This approach enhances user interaction and provides feedback during the applet's
execution. However, given the deprecated status of Java applets, consider using modern
web technologies for similar functionalities in web development.
xxxxxxxxxxxxxxxx
PASSING PARAMETERS
In Java applets, passing parameters to an applet can be done through several methods,
primarily involving HTML parameters or by using `getParameter()` method within the applet itself.
Here‟s how you can pass parameters to a Java applet and retrieve them:
1. Using HTML Parameters
You can pass parameters to an applet by specifying them in the HTML code that embeds
the applet using the `<param>` tag within the `<applet>` or `<object>` tags.

HTML Example:

```html
<!DOCTYPE html>
<html>
<head>
<title>Applet with Parameters</title>
</head>
<body>
<applet code="MyApplet.class" width="300" height="200">
<!-- Parameters -->
<param name="message" value="Hello from HTML!">
<param name="count" value="5">
<!-- Optional: Alternative content if applet fails to load -->

112
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Your browser does not support Java applets.


</applet>
</body>
</html>
```
In this example:
- The applet `MyApplet.class` is embedded with width and height attributes.
- Two parameters, `message` and `count`, are passed to the applet using `<param>` tags.
- `name` attribute specifies the parameter name (`message` and `count`).
- `value` attribute specifies the parameter value (`Hello from HTML!` and `5`).
Java Applet Code to Retrieve Parameters:
```java
import java.applet.Applet;
import java.awt.Graphics;

public class MyApplet extends Applet {

private String message;


private int count;

@Override
public void init() {
// Retrieve parameters from HTML
message = getParameter("message");
try {
count = Integer.parseInt(getParameter("count"));
} catch (NumberFormatException e) {
count = 0; // Default value if count parameter is not a valid integer
}
}

@Override
public void paint(Graphics g) {
// Display the parameters
g.drawString("Message: " + message, 20, 20);
113
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

g.drawString("Count: " + count, 20, 40);


}
}
```
- HTML Parameters:
- Parameters (`message` and `count`) are specified within the `<applet>` tag using `<param>` tags.
- Each `<param>` tag has a `name` attribute (parameter name) and a `value` attribute (parameter
value).
- Java Applet (`MyApplet`):
- In the `init()` method, use `getParameter("parameterName")` to retrieve each parameter's value.
- `getParameter("message")` retrieves the value of the `message` parameter (e.g., `"Hello from
HTML!"`).
- `getParameter("count")` retrieves the value of the `count` parameter as a `String`, which can be
converted to an integer using `Integer.parseInt()`.
- Displaying Parameters:
- In the `paint(Graphics g)` method, use `drawString()` to display the retrieved parameters
(`message` and `count`) on the applet's surface.
2. Directly in the `<applet>` Tag
Alternatively, you can pass parameters directly in the `<applet>` tag without using `<param>` tags:
```html
<applet code="MyApplet.class" width="300" height="200" message="Hello from HTML!"
count="5">
<!-- Optional: Alternative content if applet fails to load -->
Your browser does not support Java applets.
</applet>
```
In this case, `message` and `count` are directly specified as attributes of the `<applet>` tag. In Java,
you retrieve them similarly using `getParameter()` in the `init()` method of your applet.
 Passing parameters to Java applets involves specifying them in the HTML `<applet>` tag
using `<param>` tags or as attributes directly within the `<applet>` tag.
 The applet then retrieves these parameters using `getParameter()` method during its
initialization (`init()` method). This allows you to configure and customize applet behavior
based on input values provided from the HTML page.
xxxxxxxxxxxxxxxx

114
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

INTRODUCING GUI PROGRAMMING WITH SWING


Introducing GUI programming with Swing in Java is a great way to create interactive and
visually appealing graphical applications. Swing is a rich set of libraries provided by Java for
building graphical user interfaces (GUIs). Here‟s a step-by-step guide to get started with Swing:

1. Setting Up Your Development Environment


Before diving into Swing programming, ensure you have the following set up:
- Java Development Kit (JDK): Download and install the latest JDK from Oracle's website or use
a package manager if you're on a Unix-based system.
- Integrated Development Environment (IDE): Use a Java IDE such as IntelliJ IDEA, Eclipse, or
NetBeans, which provide GUI builders and other tools to simplify Swing development.
2. Understanding Swing Components
Swing provides a wide range of GUI components that you can use to build your application. Some
of the commonly used components include:
- JFrame: A top-level container that represents the main window of your application.
- JPanel: A container that can hold other components.
- JButton: A button that can trigger actions when clicked.
- JLabel: A non-editable text component used for displaying text or icons.
- JTextField: A text input field that allows users to enter and edit text.
- JTextArea: A multi-line text area for displaying/editing large amounts of text.
- JComboBox: A drop-down list from which users can select an item.
- JCheckBox: A check box that allows users to select/deselect an option.
3. Creating a Simple Swing Application
Let‟s create a simple Swing application that demonstrates the basic use of JFrame, JLabel,
and JButton components:
```java
import javax.swing.;

public class SimpleSwingApp {

public static void main(String[] args) {


// Create a JFrame
JFrame frame = new JFrame("Simple Swing Application");

// Create a JLabel
115
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

JLabel label = new JLabel("Hello, Swing!", JLabel.CENTER);

// Create a JButton
JButton button = new JButton("Click Me!");

// Add the label and button to the frame


frame.add(label);
frame.add(button);

// Set frame properties


frame.setSize(300, 200); // Set size of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the application on
close
frame.setVisible(true); // Make the frame visible
}
}
```
- JFrame: `JFrame` is created with a title ("Simple Swing Application"). It serves as the main
window for the application.
- JLabel: `JLabel` displays the text "Hello, Swing!" at the center of the frame.
- JButton: `JButton` labeled "Click Me!" is added to the frame.
- Adding Components: `frame.add(label)` and `frame.add(button)` add the label and button to the
frame.
- Frame Properties:
- `frame.setSize(300, 200)`: Sets the size of the frame to 300 pixels wide and 200 pixels tall.
- `frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)`: Specifies that the application
should exit when the frame is closed.
- `frame.setVisible(true)`: Makes the frame visible to the user.
4. Using Layout Managers
Swing uses layout managers to arrange components within containers. Some common
layout managers include `FlowLayout`, `BorderLayout`, `GridLayout`, `GridBagLayout`, and
`BoxLayout`. Each layout manager has its own way of arranging components. Here‟s an example
of using `FlowLayout`:

```java
116
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

import javax.swing.;
import java.awt.;

public class SwingLayoutExample {

public static void main(String[] args) {


JFrame frame = new JFrame("Swing Layout Example");

// Create a JPanel with FlowLayout


JPanel panel = new JPanel(new FlowLayout());

// Add buttons to the panel


for (int i = 1; i <= 5; i++) {
panel.add(new JButton("Button " + i));
}

// Add the panel to the frame


frame.add(panel);

// Set frame properties


frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
5. Event Handling
Swing components can generate events, such as button clicks or text input changes. You can
handle these events using listeners. For example, handling a button click with an ActionListener:
```java
button.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "Button clicked!");
});
```
6. Resources and Further Learning
117
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Swing Documentation: Refer to the [Swing API Documentation]


(https://docs.oracle.com/javase//docs/api/javax/swing/package-summary.html) for detailed
information about Swing classes and methods.
- Tutorials and Books: Explore online tutorials and books such as "Java Swing" by Marc Loy, or
various resources available on platforms like Oracle's Java documentation and tutorials.
 Swing provides a powerful framework for building graphical user interfaces in Java. By
understanding the basics of Swing components, layout managers, event handling, and using
an IDE, you can create robust and interactive GUI applications. Start with simple examples
and gradually explore more advanced topics to become proficient in Swing programming.
xxxxxxxxxxxxxxxx
INTRODUCING SWING
Swing is a powerful and versatile GUI toolkit provided by Java for developing graphical
user interfaces (GUIs) in desktop applications. It offers a rich set of components, layouts, and
utility classes that facilitate the creation of interactive and visually appealing applications. Here‟s
an introduction to Swing and its key features:
What is Swing?
Swing is part of the Java Foundation Classes (JFC) and is built on top of the Abstract
Window Toolkit (AWT), providing a more sophisticated and consistent set of GUI components
than AWT. It was introduced with Java 2 (JDK 1.2) and has since become the standard GUI toolkit
for Java.
Key Features of Swing:
1. Rich Set of Components:
- Swing provides a comprehensive set of lightweight, platform-independent GUI components.
Some of the commonly used components include:
- `JFrame`: Top-level container for creating a window.
- `JPanel`: Container that can hold other components or be used for custom drawing.
- `JButton`, `JLabel`, `JTextField`, `JTextArea`: Basic UI components for buttons, labels, text
input, and text areas.
- `JComboBox`, `JList`, `JTable`: Components for dropdown lists, lists, and tables respectively.
- `JCheckBox`, `JRadioButton`, `JToggleButton`: Components for checkboxes, radio buttons,
and toggle buttons.
2. Customizable Look and Feel:
- Swing allows you to customize the appearance of your application through "look and feel"
(L&F). You can choose different L&F styles, such as "Metal," "Nimbus," "Windows," or "Motif,"
to match the appearance of native operating systems or provide a unique look.
118
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

3. Layout Managers:
- Swing provides various layout managers (`FlowLayout`, `BorderLayout`, `GridLayout`,
`GridBagLayout`, etc.) to arrange components within containers. Layout managers handle the
sizing and positioning of components based on predefined rules.
4. Event Handling:
- Swing components generate events (e.g., button clicks, mouse movements) that can be handled
using event listeners. Common listeners include `ActionListener` for buttons and `MouseListener`,
`MouseMotionListener` for mouse events.
5. Double Buffering and Painting:
- Swing uses double buffering by default to reduce flickering when rendering graphics. Custom
painting can be done by overriding the `paintComponent(Graphics g)` method of Swing
components or by using the `paint(Graphics g)` method for heavyweight components.
6. Thread Safety:
- Swing components are designed to be lightweight and are generally not thread-safe. GUI
updates should be performed on the Event Dispatch Thread (EDT) using utilities like
`SwingUtilities.invokeLater(Runnable)` to ensure proper synchronization.

Example of a Simple Swing Application:


```java
import javax.swing.;
public class SimpleSwingExample {

public static void main(String[] args) {


// Create a JFrame (window)
JFrame frame = new JFrame("Simple Swing Example");

// Create a JLabel (label)


JLabel label = new JLabel("Hello, Swing!", JLabel.CENTER);

// Create a JButton (button)


JButton button = new JButton("Click Me!");

// Add the label and button to the frame


frame.add(label);
frame.add(button);
119
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Set frame properties


frame.setSize(300, 200); // Set size of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the application on
close
frame.setVisible(true); // Make the frame visible
}
}
```
Resources for Learning Swing:
- Oracle Swing Documentation: Official documentation from Oracle provides detailed explanations
and examples for Swing components and APIs.
- Books: Explore books like "Java Swing" by Marc Loy, which covers Swing programming
concepts, best practices, and advanced techniques.
- Online Tutorials and Courses: Websites like Oracle's Java tutorials, Udemy, Coursera, and
Pluralsight offer courses and tutorials on Swing programming.
 Swing remains a robust choice for creating cross-platform desktop GUI applications in
Java. Its rich set of components, customizable look and feel, layout managers, event
handling capabilities, and thread safety features make it suitable for developing applications
ranging from simple tools to complex enterprise solutions.
xxxxxxxxxxxxxxxx
SWING IS BUILT ON THE AWT
Swing is indeed built on top of the Abstract Window Toolkit (AWT), which was the
original GUI toolkit provided by Java. Understanding this relationship helps in grasping how Swing
enhances and extends the capabilities offered by AWT. Here‟s a detailed explanation of how Swing
builds upon AWT:
Abstract Window Toolkit (AWT):
AWT was the first GUI toolkit introduced in Java, providing basic components for creating
graphical user interfaces. Some key aspects of AWT include:
1. Platform Dependent: AWT components are implemented using native platform widgets (peer
components). This approach ensures that AWT components look and feel consistent with the host
operating system's GUI.
2. Heavyweight Components: AWT components are "heavyweight," meaning they are directly
mapped to native components provided by the underlying operating system. This direct mapping
makes AWT components less flexible and potentially slower in performance compared to Swing.
120
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

3. Limited Components: AWT provides a limited set of GUI components, such as `Button`,
`Label`, `TextField`, `Checkbox`, and basic layout managers (`FlowLayout`, `BorderLayout`,
`GridLayout`).
Swing and its Relationship with AWT:
Swing was introduced later (with Java 2, JDK 1.2) to address several limitations of AWT
and to provide a more powerful and flexible GUI toolkit. Here‟s how Swing enhances and extends
AWT:
1. Lightweight Components:
- Swing components are "lightweight," meaning they are entirely written in Java and are not
mapped directly to native OS components. Instead, Swing components are rendered using Java's
2D graphics capabilities (`Graphics` and `Graphics2D` classes).
- Lightweight components offer more flexibility, improved performance, and consistent behavior
across different platforms compared to AWT's heavyweight components.
2. Rich Set of Components:
- Swing provides a richer set of GUI components compared to AWT. It includes components like
`JFrame`, `JPanel`, `JButton`, `JLabel`, `JTextField`, `JTextArea`, `JComboBox`, `JList`, `JTable`,
etc.
- These components are highly customizable and can be extended to create complex GUIs with
ease.
3. Look and Feel Customization:
- Swing allows "look and feel" (L&F) customization, enabling developers to change the
appearance of their applications. This capability provides options like "Metal," "Nimbus,"
"Windows," or "Motif" L&Fs to match the native OS or create a unique style.
4. Event Handling:
- Swing provides an event model similar to AWT for handling user interactions (e.g., button
clicks, mouse events). However, Swing enhances this model with additional event types and
listeners (`ActionListener`, `MouseListener`, `KeyListener`, etc.).
5. Layout Managers:
- Swing retains AWT's layout managers (`FlowLayout`, `BorderLayout`, `GridLayout`, etc.) for
arranging components within containers. These layout managers help in creating flexible and
responsive GUI layouts.
6. Thread Safety:
- Swing components are designed to be more thread-safe compared to AWT. GUI updates should
typically be performed on the Event Dispatch Thread (EDT) to avoid concurrency issues.
Interoperability and Usage:
121
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Swing components can be used alongside AWT components within the same GUI application.
- AWT and Swing are seamlessly integrated, allowing developers to mix and match components
based on requirements. For example, you can embed AWT components within a Swing container
or vice versa.
Evolution and Adoption:
- Due to its lightweight nature, flexibility, and extensive feature set, Swing has become the
preferred choice for GUI development in Java, especially for desktop applications.
- Despite advancements in web technologies and alternative GUI frameworks, Swing remains
relevant and widely used in enterprise applications and tools where robust desktop GUIs are
required.
 Swing builds upon AWT by providing lightweight, flexible, and highly customizable GUI
components for Java applications.
 It enhances AWT's capabilities with a richer set of components, look and feel
customization, improved event handling, and layout management.
 Understanding the relationship between Swing and AWT is crucial for leveraging their
strengths in Java GUI development.
xxxxxxxxxxxxxxxx
TWO KEY SWING FEATURES
Swing, as a GUI toolkit for Java, offers a range of features that make it powerful and
versatile for developing desktop applications. Here are two key features of Swing:
1. Lightweight Components
One of the fundamental improvements Swing brought over AWT is its use of lightweight
components. Unlike AWT's heavyweight components, which are directly mapped to native
operating system widgets, Swing components are entirely written in Java and rendered using Java's
2D graphics capabilities (`Graphics` and `Graphics2D`).
- Advantages of Lightweight Components:
- Platform Independence: Swing components look and behave consistently across different
platforms because they are not tied to native OS components.
- Flexibility: Since Swing components are not limited by native widget styles, developers have
more freedom to customize their appearance and behavior.
- Performance: Lightweight components are generally faster and more efficient than their
heavyweight counterparts because they do not rely on native OS calls for rendering.
- Examples of Lightweight Components in Swing:

122
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- `JFrame`, `JPanel`, `JButton`, `JLabel`, `JTextField`, `JTextArea`, `JComboBox`, `JList`,


`JTable`, etc.
- These components can be easily extended and customized using various properties and methods
provided by Swing.
2. Look and Feel Customization
Swing provides extensive support for customizing the "look and feel" (L&F) of your application.
This feature allows developers to change the appearance of their GUI applications to match
different operating systems or create unique styles.
- Key Aspects of Look and Feel Customization:
- Pluggable Look and Feel: Swing supports multiple look and feel implementations, such as
"Metal," "Nimbus," "Windows," "Motif," etc. Each look and feel provides a different visual style
and behavior for Swing components.
- UI Defaults: Swing uses UIManager and UIDefaults to manage the appearance and behavior of
components. Developers can programmatically set UI defaults to customize colors, fonts, borders,
icons, and other visual aspects.
- Substance Look and Feel: Apart from the standard look and feels, libraries like Substance
provide enhanced look and feel options with themes and additional component styles.
- Example of Setting Look and Feel in Swing:
```java
import javax.swing.;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;

public class CustomLookAndFeelExample {

public static void main(String[] args) {


try {
// Set Nimbus look and feel
UIManager.setLookAndFeel(new NimbusLookAndFeel());

// Create and show a JFrame


JFrame frame = new JFrame("Custom Look and Feel Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} catch (UnsupportedLookAndFeelException e) {
123
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

e.printStackTrace();
}
}
}
```
- In this example, `NimbusLookAndFeel` is set as the look and feel for the JFrame, providing a
modern appearance with smooth gradients and subtle animations.
Benefits of These Features:
- Enhanced User Experience: Lightweight components ensure consistent and fast performance
across different platforms, while customizable look and feel options allow developers to create
visually appealing and user-friendly interfaces.
- Ease of Development: Developers can focus on application logic without worrying about
platform-specific GUI differences, thanks to Swing's platform independence and customizable
appearance.
- Adaptability: Swing's flexibility makes it suitable for a wide range of applications, from enterprise
desktop software to consumer-facing applications requiring unique branding and design.
- Swing's lightweight components and extensive look and feel customization capabilities are core
features that differentiate it from AWT and contribute to its popularity in Java desktop application
development.
xxxxxxxxxxxxxxxx
THE MVC CONNECTION
The Model-View-Controller (MVC) architectural pattern is a fundamental concept in
software design, including GUI applications. While Swing itself is primarily a GUI toolkit and not
a full MVC framework, it allows developers to implement MVC principles to structure their
applications effectively. Here‟s how Swing components can fit into the MVC pattern:
MVC Components in Swing:
1. Model (M):
- Purpose: Represents the data and business logic of the application. It encapsulates the
application‟s state and provides methods to manipulate this state.
- Implementation: In Swing applications, the model can be represented by custom Java classes or
existing data structures (`ArrayList`, `HashMap`, etc.) that hold application data.
2. View (V):
- Purpose: Represents the presentation layer of the application. It displays the data to the user and
handles user interactions (like button clicks, text input).

124
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Implementation: In Swing, the view is primarily composed of Swing components (`JFrame`,


`JPanel`, `JButton`, `JLabel`, etc.) that visually represent the model data and provide user interface
elements.
3. Controller (C):
- Purpose: Acts as an intermediary between the model and view components. It interprets user
inputs from the view, manipulates the model data accordingly, and updates the view to reflect
changes in the model.
- Implementation: In Swing applications, controllers are typically implemented using event
listeners (`ActionListener`, `MouseListener`, etc.) attached to Swing components. These listeners
respond to user actions and invoke methods on the model to update its state, then update the view
to reflect these changes.
Example of MVC in a Swing Application:
Let's consider a simple example of a Swing application following MVC principles:
- Model (Data): Represents a simple counter that can be incremented.
```java
public class CounterModel {
private int count;

public CounterModel() {
count = 0;
}

public int getCount() {


return count;
}

public void increment() {


count++;
}
}
```
- View: Displays the counter value using a `JLabel` and provides a button (`JButton`) to increment
the counter.

```java
125
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

import javax.swing.;
import java.awt.;
import java.awt.event.;

public class CounterView extends JFrame {


private JLabel label;
private JButton button;
private CounterModel model;

public CounterView(CounterModel model) {


this.model = model;
label = new JLabel("Counter: " + model.getCount(), JLabel.CENTER);
button = new JButton("Increment");

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.increment();
label.setText("Counter: " + model.getCount());
}
});

setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);

setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
```
- Controller: Responds to button clicks and updates the model accordingly.
```java
public class CounterController {
126
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

private CounterModel model;


private CounterView view;

public CounterController(CounterModel model, CounterView view) {


this.model = model;
this.view = view;
}

// Controller logic (event handling) can be implemented here if necessary


}
```

Connecting MVC Components:

- Main Application:
```java
public class Main {
public static void main(String[] args) {
CounterModel model = new CounterModel();
CounterView view = new CounterView(model);
CounterController controller = new CounterController(model, view);
}
}
```
MVC Benefits in Swing:
- Separation of Concerns: MVC promotes a clear separation between the application's data (model),
its presentation (view), and user interactions (controller). This makes the application easier to
maintain and extend.
- Reusability: Components (model, view, and controller) can be reused or replaced independently
without affecting other parts of the application.
- Testability: Each component (model, view, controller) can be tested independently, facilitating
unit testing and improving overall code quality.
 While Swing itself is not a strict MVC framework, it provides the necessary components
and flexibility to implement the MVC pattern effectively.

127
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 By structuring your Swing applications following MVC principles, you can achieve better
organization, maintainability, and scalability in your GUI development project.
xxxxxxxxxxxxxxxx
COMPONENTS AND CONTAINERS
In Swing, components and containers are fundamental building blocks used to create
graphical user interfaces (GUIs). Understanding their roles and relationships is crucial for
designing and developing effective Swing applications. Here‟s an overview of components,
containers, and how they work together in Swing:
Components:
Components in Swing represent individual graphical elements that can be added to containers to
create the user interface. Some common Swing components include:
1. JButton:
- Represents a push-button that users can click to trigger actions.
2. JLabel:
- Displays a single line of read-only text or an image.
3. JTextField:
- Allows users to enter and edit a single line of text.
4. JTextArea:
- Multi-line text area for displaying/editing large amounts of text.
5. JComboBox:
- Dropdown list from which users can select an item.
6. JCheckBox and JRadioButton:
- Check box and radio button components for selecting options.
7. JList and JTable:
- Components for displaying lists and tables of data.
. Custom Components:
- Developers can create custom Swing components by extending existing Swing classes or
implementing specific interfaces (`JComponent`, `TableCellRenderer`, etc.).
Containers:
Containers in Swing are components that can hold other components. They provide
structure and organization to the GUI layout. Some common Swing containers include:
1. JFrame:
- Represents the main application window or frame. It is typically the top-level container for
Swing applications.
2. JPanel:
128
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- A generic container that can hold multiple components. Used for grouping and organizing
components within a frame.
3. JScrollPane:
- A container that provides scroll bars for viewing the contents of another component that is too
large to fit within the available space.
4. JDialog:
- A window that allows interaction with the user, usually for tasks like displaying messages or
prompting for input.
5. Layout Managers:
- Containers use layout managers (`LayoutManager` and its subclasses) to define how
components are arranged and resized within them.
- Common layout managers include `FlowLayout`, `BorderLayout`, `GridLayout`,
`GridBagLayout`, and `BoxLayout`, each offering different strategies for component positioning
and sizing.
Relationships and Usage:
- Adding Components to Containers:
- Components are added to containers using methods like `add(Component comp)` or
`setContentPane(Component contentPane)` for frame (`JFrame`) or dialog (`JDialog`) containers.
- Nested Containers:
- Containers can be nested within each other to create complex layouts. For example, a `JPanel`
can contain multiple other panels, buttons, labels, etc., each with its own layout manager.
- Hierarchy:
- Swing components and containers form a hierarchical structure, where each component or
container can contain other components or containers. This hierarchy defines how components are
organized and displayed within the GUI.

Example of Using Components and Containers:


```java
import javax.swing.;
import java.awt.;

public class ComponentsAndContainersExample {


public static void main(String[] args) {
// Create a JFrame (main window)
JFrame frame = new JFrame("Swing Components and Containers Example");
129
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

frame.setSize(400, 300); // Set size of the frame


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close operation

// Create a JPanel (container)


JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // Set layout manager for the panel

// Create components (buttons, labels, etc.)


JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton submitButton = new JButton("Submit");

// Add components to the panel


panel.add(label);
panel.add(textField);
panel.add(submitButton);

// Add panel to the frame


frame.add(panel);

// Make the frame visible


frame.setVisible(true);
}
}
```
- Components are individual graphical elements (e.g., buttons, labels) in Swing that users interact
with.
- Containers are components that can hold other components (e.g., frames, panels) and provide
structure to the GUI layout.
- Understanding how components and containers work together, along with layout managers, is
essential for creating well-organized and responsive Swing applications. By mastering these
concepts, developers can design flexible and user-friendly GUIs that meet the requirements of their
applications effectively.
xxxxxxxxxxxxxxxx

130
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

THE SWING PACKAGES


Swing, being a comprehensive GUI toolkit for Java, is organized into several packages,
each containing classes and interfaces that serve specific purposes in building graphical user
interfaces. Here's an overview of the main Swing packages and their key contents:
1. `javax.swing` Package
The `javax.swing` package forms the core of the Swing framework and includes essential classes
and interfaces for GUI development:
- Components: Classes like `JFrame`, `JPanel`, `JButton`, `JLabel`, `JTextField`, `JTextArea`,
`JComboBox`, `JList`, `JTable`, etc., which are used to create various GUI elements.
- Layout Managers: Interfaces (`LayoutManager`, `LayoutManager2`,
`LayoutFocusTraversalPolicy`) and implementations (`BorderLayout`, `FlowLayout`,
`GridLayout`, `BoxLayout`, `GridBagLayout`, etc.) that manage the arrangement of components
within containers.
- Events and Listeners: Interfaces (`ActionListener`, `MouseListener`, `KeyListener`,
`WindowListener`, etc.) for handling user interactions and component lifecycle events.
- Data Models: Interfaces (`ListModel`, `TableModel`, `ComboBoxModel`, etc.) and
implementations (`DefaultListModel`, `DefaultTableModel`, `DefaultComboBoxModel`) for
managing data displayed in list-like components.
2. `javax.swing.border` Package
The `javax.swing.border` package provides classes and interfaces for defining borders around
Swing components:
- Border Interfaces: (`Border`, `BevelBorder`, `CompoundBorder`, `EmptyBorder`,
`EtchedBorder`, `LineBorder`, `MatteBorder`, `SoftBevelBorder`, `TitledBorder`) for customizing
the appearance of component edges.
3. `javax.swing.event` Package
The `javax.swing.event` package contains event classes and listener interfaces specific to Swing
components:
- Event Interfaces: (`ActionEvent`, `ChangeEvent`, `MouseEvent`, `KeyListener`,
`ListSelectionListener`, `TableModelListener`, etc.) for capturing user interactions, state changes,
and updates in components.
4. `javax.swing.filechooser` Package
The `javax.swing.filechooser` package provides classes and interfaces related to file chooser
dialogs:
- FileChooser Classes: (`JFileChooser`, `FileFilter`, `FileNameExtensionFilter`, etc.) for selecting
files and directories within Swing applications.
131
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

5. `javax.swing.plaf` Package
The `javax.swing.plaf` package defines the Look and Feel (L&F) classes and interfaces for Swing
components:
- L&F Interfaces: (`LookAndFeel`, `UIManager.LookAndFeelInfo`, `BorderUIResource`, etc.) for
customizing the appearance and behavior of Swing components.
6. `javax.swing.table` Package
The `javax.swing.table` package contains classes and interfaces for working with tables in Swing
applications:
- Table Interfaces: (`TableModel`, `TableCellRenderer`, `TableCellEditor`, `TableColumn`, etc.)
for displaying and manipulating tabular data in `JTable` components.
7. `javax.swing.text` Package
The `javax.swing.text` package provides classes and interfaces for handling text-related operations
in Swing:
- Text Components: (`JTextComponent`, `JTextField`, `JTextArea`, `JEditorPane`,
`StyledDocument`, etc.) for displaying and editing text with support for styles, fonts, and
formatting.
8 . `javax.swing.tree` Package
The `javax.swing.tree` package contains classes and interfaces for working with tree-like
structures in Swing applications:
- Tree Components: (`JTree`, `TreeModel`, `TreeNode`, `TreePath`, etc.) for displaying
hierarchical data in tree structures with expandable nodes.
9. `javax.swing.undo` Package
The `javax.swing.undo` package provides classes and interfaces for implementing undo and
redo functionality in Swing applications:
- Undo Support: (`UndoManager`, `UndoableEdit`, `AbstractUndoableEdit`, etc.) for managing
reversible changes to application state.
Additional Packages:
In addition to these main packages, Swing also includes several other packages that provide
utility classes, auxiliary components, and extensions for specific tasks:
- `javax.swing.colorchooser`: Classes for selecting and manipulating colors (`JColorChooser`,
`ColorSelectionModel`, etc.).
- `javax.swing.event`: Additional event classes and listener interfaces for specific Swing
components.
- `javax.swing.table`: Extensions and utility classes for working with tables (`AbstractTableModel`,
`TableColumnModel`, etc.).
132
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- `javax.swing.text.html`: Classes for displaying and editing HTML content (`JEditorPane` with
HTML support, `HTMLDocument`, etc.).
xxxxxxxxxxxxxxxx
A SIMPLE SWING APPLICATION
Swing application that demonstrates the basic structure and functionality of creating a
window (`JFrame`) with a label (`JLabel`) and a button (`JButton`). This example will display a
window with a label showing a counter that increments each time the button is clicked.
```java
import javax.swing.;
import java.awt.;
import java.awt.event.;
public class SimpleSwingApplication {
private JFrame frame;
private JLabel label;
private JButton button;
private int count = 0;
public SimpleSwingApplication() {
// Create a JFrame (window)
frame = new JFrame("Simple Swing Application");
// Create a JLabel (label)
label = new JLabel("Counter: " + count, JLabel.CENTER);
// Create a JButton (button)
button = new JButton("Increment");
// Add ActionListener to the button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Counter: " + count);
}
});

// Set layout for the JFrame


frame.setLayout(new BorderLayout());

// Add components to the JFrame


133
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

frame.add(label, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);

// Set JFrame properties


frame.setSize(300, 200); // Set size of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close operation
frame.setVisible(true); // Make the frame visible
}

public static void main(String[] args) {


// Create and run the application
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleSwingApplication();
}
});
}
}
```
1. Import Statements:
- `javax.swing.`: Imports necessary Swing components and utilities.
- `java.awt.`: Imports abstract window toolkit classes for basic window handling.

2. Class `SimpleSwingApplication`:
- Initializes instance variables: `JFrame frame`, `JLabel label`, `JButton button`, and `int count`.
3. Constructor `SimpleSwingApplication()`:
- Creates a `JFrame` (`frame`) with the title "Simple Swing Application".
- Creates a `JLabel` (`label`) with initial text "Counter: 0".
- Creates a `JButton` (`button`) with label "Increment".
- Adds an `ActionListener` to the `button` that increments the `count` variable and updates the
text of `label` accordingly.
- Sets the layout of the `JFrame` to `BorderLayout`.
- Adds `label` to the center and `button` to the south (bottom) of the `JFrame`.
- Sets size (300x200 pixels), default close operation (EXIT_ON_CLOSE), and makes the frame
visible.
134
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

4. `main()` Method:
- Entry point of the application.
- Uses `SwingUtilities.invokeLater()` to ensure the Swing components are initialized and updated
on the Event Dispatch Thread (EDT), which is necessary for thread safety in Swing applications.
- Creates an instance of `SimpleSwingApplication` to start the application.
Running the Application:
- Compile the Java file (`SimpleSwingApplication.java`).
- Run the compiled class (`SimpleSwingApplication.class`).
- A window titled "Simple Swing Application" should appear with a label "Counter: 0" and a
button labeled "Increment".
- Clicking the "Increment" button should increment the counter displayed in the label.
 This simple example demonstrates how to create a basic Swing application with a graphical
window, a label for displaying text, and a button for user interaction. It lays the foundation
for building more complex GUI applications using Java Swing.
xxxxxxxxxxxxxxxx
EXPLORING SWING
Swing is a graphical user interface (GUI) toolkit for Java that allows developers to create
rich and interactive user interfaces. It's part of the Java Foundation Classes (JFC) and provides a
wide range of components for building desktop applications. Here‟s an overview to get you started
with exploring Swing:
Basics of Swing:
1. Components: Swing provides a comprehensive set of GUI components like buttons, text fields,
labels, lists, tables, etc., which you can use to build your application interfaces.
2. Lightweight: Swing components are lightweight, meaning they are not tied to the underlying
operating system's windowing system directly. Instead, Swing components are rendered using Java
code, making them platform-independent.
3. MVC Architecture: Swing follows the Model-View-Controller architecture, where components
typically have a data model (model), a visual representation (view), and the ability to handle user
actions (controller).
Getting Started:
1. Setting Up: To start using Swing, ensure you have Java Development Kit (JDK) installed on
your system. Swing is included in the standard Java libraries, so no additional installation is
needed.
2. Creating a Swing Application: You typically extend classes like `JFrame`, `JPanel`, or other
Swing components to build your GUI. Here‟s a basic example:
135
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```java
import javax.swing.;
public class MySwingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("My Swing Application");
JLabel label = new JLabel("Hello, Swing!", JLabel.CENTER);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
- JFrame: Represents a window in Swing.
- JLabel: Displays a short string or an image.
3. Event Handling: Swing uses listeners to handle events such as button clicks, mouse movements,
etc. For example, to handle a button click, you would attach an `ActionListener` to the button.
Learning Resources:
1. Official Documentation: The Java Swing tutorial on Oracle‟s website provides comprehensive
documentation and examples.
2. Books: Look for books like "Java Swing" by Marc Loy, "Swing: A Beginner's Guide" by Herbert
Schildt, or "Java Swing" by Robert Eckstein for in-depth learning.
3. Online Courses: Platforms like Coursera, edX, or Udemy offer courses specifically on Java
Swing, catering to different levels of expertise.
Advanced Topics:
1. Custom Components: You can create custom Swing components by extending existing ones or
combining multiple components.
2. Layout Management: Swing provides layout managers to arrange components within containers.
Common layout managers include `FlowLayout`, `BorderLayout`, `GridLayout`, and
`GridBagLayout`.
3. Concurrency: When building responsive applications, consider Swing's threading model and how
to handle long-running tasks using `SwingWorker`.
 Swing remains relevant for developing desktop applications in Java despite newer
technologies like JavaFX. It offers flexibility, a rich set of components, and good
136
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

community support. Exploring Swing will give you a solid foundation in building Java
desktop applications.
xxxxxxxxxxxxxxxx
UNIT III – QUESTION BANK
ONE MARK QUESTIONS
1. What is the main purpose of the Applet class in Java?
- A) To create standalone desktop applications. - B) To handle web-based GUI applications.
- C) To manage server-side programming. - D) To manage file I/O operations.
Answer: B) To handle web-based GUI applications.
2. Which method is responsible for initializing an applet?
- A) `init()` - B) `start()` - C) `run()` - D) `paint()`
Answer: A) `init()`
3. Swing is built on which existing Java GUI framework?
- A) JavaFX - B) AWT (Abstract Window Toolkit)
- C) Java Servlets - D) Java Beans
Answer: B) AWT (Abstract Window Toolkit)
4. What are two key features of Swing that distinguish it from AWT?
- A) Heavyweight components and event handling.
- B) Lightweight components and platform independence.
- C) Rich graphics capabilities and integrated database support.
- D) Multithreading and networking capabilities.
Answer: B) Lightweight components and platform independence.
5. In Swing, which component represents the controller in the MVC (Model-View-Controller)
architecture?
- A) `JFrame` - B) `JPanel` - C) `JButton` - D) `ActionListener`
Answer: D) `ActionListener`
6. Which Swing class is used for creating a windowed GUI application?
- A) `JPanel` - B) `JApplet` - C) `JFrame` - D) `JButton`
Answer: C) `JFrame`
7. Which package contains the core Swing classes in Java?
- A) `java.awt` - B) `javax.swing` - C) `java.util` - D) `java.io`
Answer: B) `javax.swing`
8. What is the primary benefit of using Swing for GUI programming in Java?
- A) Cross-platform compatibility - B) Integration with web services
- C) Real-time data processing - D) Hardware acceleration
137
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Answer: A) Cross-platform compatibility


9. Which method in the Applet class is responsible for painting graphics on the applet window?
- A) `paint()` - B) `start()` - C) `init()` - D) `update()`
Answer: A) `paint()`
10. How can parameters be passed to an applet?
- A) Through a configuration file - B) Using command-line arguments
- C) Via HTTP request parameters - D) Through the `init()` method parameters
Answer: D) Through the `init()` method parameters
FIVE MARK & TEN MARK QUESTIONS
1. Explain the basic architecture of the Applet class in Java.
2. Discuss the lifecycle methods of an applet.
3. Describe the structure of an applet skeleton. What are the essential components required to create
a basic applet in Java?
4. Explain the significance of display methods in the Applet class. How are methods such as
`paint()` and `update()` utilized to render graphical content within an applet window?
5. Discuss the role of the status window in applet programming.
6. Describe the process of passing parameters to an applet.
7. Introduce Swing as a GUI toolkit in Java.
8. Explain two key features of Swing that enhance its usability and flexibility in GUI programming.
9. Discuss the Model-View-Controller (MVC) connection in Swing applications.
10. Explore the Swing packages in Java. What are the core packages and classes that form the
foundation of Swing GUI programming?
xxxxxxxxxxxxxxxx UNIT III END xxxxxxxxxxxxxxxx

138
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

UNIT- IV
Java Beans: Introduction - Advantages of Beans – Introspection - The JavaBeans API - A Bean
Example. Servlets: Life Cycle Simple Servlet-Servlet API-Packages-Cookies session tracking.
xxxxxxxxxxxxxxxx
JAVA BEANS: INTRODUCTION
Java Beans are reusable software components designed for the Java platform. They are
encapsulated, reusable objects that can be manipulated visually in development environments. Here are
the key aspects of Java Beans:
1. Definition: Java Beans are Java classes that adhere to certain conventions. These conventions make
them easily reusable across different applications and development environments.
2. Characteristics:
- Properties: Beans have properties that can be accessed and manipulated. These properties typically
have getter and setter methods (`getXXX` and `setXXX`).
- Events: Beans can generate and respond to events. Event handling is typically achieved through
listeners.
- Methods: Beans can have methods that perform specific actions or computations.
- Serialization: Beans can be serialized, meaning they can be saved to persistent storage and later
restored, maintaining their state.
3. Purpose:
- Reusability: Java Beans promote software reuse by encapsulating frequently used functionality into
components.
- Ease of Use: They are designed to be easily manipulated in visual development tools like IDEs
(Integrated Development Environments) and GUI builders.
- Interoperability: Beans can be used in various Java environments and can interact with other
components seamlessly.
4. Conventions:
- Naming: Beans follow naming conventions for properties (`propertyName`) and methods
(`getPropertyName`, `setPropertyName`).
- Serializable: Beans often implement the `Serializable` interface to support serialization.
5. Components:
- Beans can represent a wide range of components, from simple data objects to complex GUI
components (like buttons, text fields) and business logic components.
6. Examples:
- Simple Bean Example:
```java
import java.io.Serializable;

139
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class PersonBean implements Serializable {


private String name;
private int age;

public PersonBean() {
// Default constructor
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
```
- This example defines a simple Java Bean `PersonBean` with properties `name` and `age`.
- Java Beans provide a standardized way to create reusable components in Java, making development
more efficient and promoting code reuse across different applications and environments.
xxxxxxxxxxxxxxxx
ADVANTAGES OF BEANS
Java Beans offer several advantages that contribute to their widespread adoption and usage in
Java development. Here are the key advantages of Java Beans:

140
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
1. Reusability: Java Beans are designed to be reusable components. They encapsulate behaviors and
properties that can be easily reused in different parts of an application or across different applications
altogether. This promotes modular and maintainable code.

2. Customization: Beans allow developers to customize and extend their functionality through
properties, events, and methods. Properties can be set and retrieved using standard naming conventions
(`getXXX` and `setXXX`), making it straightforward to configure beans for specific requirements.

3. Introspection: Java Beans support introspection, which enables tools and applications to analyze
beans dynamically at runtime. Introspection allows IDEs (Integrated Development Environments) and
other tools to discover and manipulate a bean's properties, methods, and events programmatically.

4. Event Handling: Beans can generate and respond to events. This event-driven architecture is crucial
for building interactive and responsive applications. Event listeners can be attached to beans to handle
user interactions or system events, enhancing flexibility in application design.

5. Serialization: Java Beans can implement the `Serializable` interface, allowing them to be serialized
into a stream of bytes. This enables beans to be stored persistently in files or transmitted over networks,
maintaining their state across different sessions or environments.

6. Platform Independence: Java Beans are platform-independent. They can run on any Java Virtual
Machine (JVM), regardless of the underlying operating system or hardware architecture. This makes
beans highly portable and suitable for cross-platform development.

7. Integration with Development Tools: Beans integrate seamlessly with visual development tools and
IDEs. Developers can visually design and manipulate beans using drag-and-drop interfaces, simplifying
the development of graphical user interfaces (GUIs) and other complex applications.

8. Component-based Development: Beans facilitate component-based development, where large


applications are built by integrating smaller, self-contained components (beans). This approach
promotes code reusability, modularity, and scalability in software development projects.

9. Standardization: Java Beans adhere to well-defined conventions and design patterns, promoting
consistency and best practices in Java programming. This standardization enhances code readability,
maintainability, and collaboration among developers.

141
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

 Java Beans offer a powerful mechanism for building modular, reusable, and scalable
applications in Java.
 Their advantages in terms of reusability, customization, introspection, event handling,
serialization, platform independence, integration with development tools, and adherence to
standards make them a preferred choice for Java developers aiming to achieve efficient and
maintainable software solutions.
xxxxxxxxxxxxxxxx
INTROSPECTION
Java introspection refers to the ability of a Java program to examine or introspect its own
structure, properties, and methods at runtime. This capability allows Java applications to inspect and
manipulate objects dynamically, which is particularly useful in scenarios such as:

1. Dynamic Loading: Loading classes and objects dynamically at runtime based on configuration or
user input.
2. Bean Manipulation: Working with JavaBeans (POJOs with getter and setter methods) to dynamically
access or modify their properties.
3. Serialization: Analyzing and serializing/deserializing objects based on their runtime structure.
4. Frameworks: Many Java frameworks use introspection to provide features like dependency injection
(Spring Framework), object-relational mapping (Hibernate), and graphical user interface construction
(JavaFX).
How Introspection Works in Java
Java provides several mechanisms for introspection, including:
- Reflection: The primary mechanism for introspection in Java is reflection, which allows programs to
inspect classes, interfaces, fields, and methods at runtime. Reflection provides APIs (`Class`, `Method`,
`Field`, `Constructor`, etc.) to dynamically examine and manipulate classes and objects.
- JavaBeans API: JavaBeans specification defines a set of conventions for creating reusable software
components (beans) in Java. Introspection APIs (`Introspector` and `PropertyDescriptor`) are provided
to examine the properties, methods, and events of JavaBeans.
Example of Introspection using Reflection
Here's a simple example demonstrating how reflection can be used for introspection in Java:
```java
import java.lang.reflect.;

public class IntrospectionExample {


public static void main(String[] args) throws Exception {
// Get the class object for a specific class (e.g., Person)

142
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
Class<?> personClass = Class.forName("com.example.Person");

// Get all declared fields of the Person class


Field[] fields = personClass.getDeclaredFields();
System.out.println("Fields of Person class:");
for (Field field : fields) {
System.out.println(field.getName());
}

// Get all declared methods of the Person class


Method[] methods = personClass.getDeclaredMethods();
System.out.println("\nMethods of Person class:");
for (Method method : methods) {
System.out.println(method.getName());
}
}
}
```
Use Cases for Introspection
- Serialization: When serializing objects to JSON/XML or other formats, introspection helps in
identifying the properties of an object dynamically.
- GUI Programming: In frameworks like JavaFX, introspection can be used to dynamically create UI
components based on object properties.
- Dependency Injection: Frameworks like Spring use introspection to inject dependencies into objects
based on their annotations or configurations.
- Java introspection, primarily facilitated by reflection, enables powerful runtime capabilities for
examining and manipulating classes, methods, and properties dynamically. This flexibility is leveraged
by many Java frameworks and libraries to provide sophisticated features and functionalities.
xxxxxxxxxxxxxxxx
THE JAVABEANS API
The JavaBeans API is a set of conventions and guidelines that define a component model
for Java. JavaBeans are reusable software components that follow these conventions, making them
easily manipulable by development tools and frameworks. Here are the key aspects of the
JavaBeans API:
Conventions of JavaBeans

143
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

1. Properties: JavaBeans expose properties using getter and setter methods following the naming
conventions `getProperty` and `setProperty`. For example, a property `name` would have methods
`getName()` and `setName(String name)`.
2. Events: JavaBeans can generate events and are expected to provide methods to register and
unregister event listeners. Events are typically associated with actions or changes in state within the
bean.
3. Persistence: JavaBeans should support serialization to persist their state, allowing them to be
saved to and restored from streams or databases.
4. Customization: Beans can provide customization through various methods such as implementing
interfaces like `java.io.Serializable`, providing custom editors, or using customizer classes.
JavaBeans API Components
The JavaBeans API includes several core classes and interfaces:
- `java.beans.BeanInfo`: This interface allows beans to provide explicit information about their
properties, methods, and events. It enables tools and frameworks to introspect beans accurately.
- `java.beans.PropertyDescriptor`: Represents a property of a bean. It encapsulates details about a
property, such as its name, getter and setter methods, and editor.
- `java.beans.Introspector`: A utility class that allows applications to obtain BeanInfo objects using
reflection and introspection techniques. It caches BeanInfo classes to improve performance.
- `java.beans.EventHandler`: A utility class introduced in Java SE 6 that simplifies event handling
for beans by reducing the amount of boilerplate code needed to connect event sources and listeners.
Example of JavaBeans
Here‟s a simple example of a JavaBean:
```java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;

// Constructor
public Person() {
}

// Getter and Setter methods


public String getName() {
return name;
144
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
```
In this example, `Person` is a JavaBean with properties `name` and `age`, each having a getter and
setter method following the JavaBeans naming conventions.
Benefits and Usage
- Tool Compatibility: JavaBeans can be easily integrated with IDEs and development tools due to
their standard naming conventions and introspection support.
- Component Reusability: By following JavaBeans conventions, components become reusable and
interchangeable, facilitating modular and scalable application development.
- Integration with Frameworks: Many Java frameworks and libraries, such as JavaFX and Spring
Framework, rely on JavaBeans conventions for dependency injection, graphical user interface
construction, and other functionalities.
In summary, the JavaBeans API provides a structured approach to creating reusable components in
Java, promoting interoperability and ease of use across different development environments and
frameworks.
xxxxxxxxxxxxxxxx
A BEAN EXAMPLE
```java
import java.io.Serializable;
// Define a JavaBean class
public class Person implements Serializable {
// Private fields (properties)
145
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

private String name;


private int age;

// Constructor
public Person() {
}
// Getter and Setter methods for 'name' property
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter methods for 'age' property
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
1. Class Definition:
- The `Person` class is a simple JavaBean that represents a person with `name` and `age`
properties.
2. Properties:
- `name` and `age` are private fields (`private String name;` and `private int age;`) encapsulated
within the `Person` class.
3. Constructor:
- A default constructor `public Person() {}` is provided, which initializes a new instance of
`Person`.
4. Getter and Setter Methods:
- Each property (`name` and `age`) has corresponding getter methods (`getName()` and
`getAge()`) and setter methods (`setName(String name)` and `setAge(int age)`). These methods

146
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

follow the JavaBeans naming conventions, allowing other code to access and modify the object's
state.
5. Serializable Interface:
- The `Person` class implements `Serializable` interface to support serialization. This enables
instances of `Person` to be converted into byte streams, which can be stored, transmitted over
networks, or reconstructed later.
Usage Example:
```java
public class Main {
public static void main(String[] args) {
// Create a new instance of Person
Person person = new Person();

// Set properties using setter methods


person.setName("Alice");
person.setAge(30);

// Retrieve properties using getter methods


String name = person.getName();
int age = person.getAge();

// Print out the details


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
```
1. Creating an Instance:
- `Person person = new Person();` creates a new instance of `Person`.
2. Setting Properties:
- `person.setName("Alice");` and `person.setAge(30);` set the `name` and `age` properties of the
`person` object.
3. Getting Properties:
- `String name = person.getName();` and `int age = person.getAge();` retrieve the `name` and
`age` properties of the `person` object.
147
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

4. Output:
- The program prints out the values of `name` and `age` using `System.out.println()`.
Benefits of JavaBeans:
- Encapsulation: JavaBeans encapsulate their state (properties) and behavior (getter and setter
methods), promoting good object-oriented design principles.
- Interoperability: JavaBeans follow a standard naming convention (`getPropertyName()` and
`setPropertyName()`) that allows them to be easily integrated with various Java frameworks and
tools.
- Reusability: JavaBeans are reusable components that can be instantiated and used in different
parts of an application or even in different applications altogether.
- JavaBeans provide a straightforward and structured way to create reusable components in Java,
facilitating modular and maintainable software development practices.
xxxxxxxxxxxxxxxx
SERVLETS
Servlets are Java classes that extend the capabilities of servers to handle requests and
generate responses for web applications. They are part of the Java EE (Enterprise Edition) platform
and provide a robust way to build server-side applications. Here's a comprehensive overview of
servlets:

What are Servlets?


Servlets are Java classes that are deployed on a web server to process client requests and
generate dynamic responses. They are designed to handle various types of requests such as HTTP
requests (GET, POST, PUT, DELETE, etc.) and can respond with dynamically generated HTML,
XML, JSON, or any other format.

Key Features and Characteristics:


1. Platform Independence: Servlets are written in Java and are platform-independent, making them
capable of running on any web server that supports the Java EE specification.
2. Lifecycle Methods: Servlets follow a lifecycle managed by the servlet container (such as
Tomcat, Jetty, or others). Key lifecycle methods include `init()`, `service()`, and `destroy()`.
3. Request Handling: Servlets handle HTTP requests and can extract information from requests
(parameters, headers, etc.) using methods provided by the `ServletRequest` object.
4. Response Generation: Servlets generate responses dynamically using methods of the
`ServletResponse` object, typically writing HTML or other content directly to the response stream.

148
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

5. Session Management: Servlets can manage user sessions using mechanisms provided by the
servlet container (such as session tracking using cookies or URL rewriting).
6. Concurrency: Servlets are designed to handle multiple requests concurrently. The servlet
container manages thread safety and ensures that multiple threads can safely access servlet
instances.
Example of a Simple Servlet:
```java
import java.io.;
import javax.servlet.;
import javax.servlet.http.;

public class HelloWorldServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set content type and other response headers


response.setContentType("text/html");

// Get the PrintWriter object to write the HTML response


PrintWriter out = response.getWriter();

// Write the HTML response content


out.println("<html>");
out.println("<head><title>Hello World Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello, World!</h1>");
out.println("<p>This is a simple servlet example.</p>");
out.println("</body></html>");
}
}
```
- Class Definition: `HelloWorldServlet` extends `HttpServlet`, making it a servlet capable of
handling HTTP requests.
149
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- `doGet` Method: This method overrides the `doGet` method of `HttpServlet`. It is called by the
servlet container (e.g., Tomcat) when a GET request is sent to this servlet.

- Response Handling:
- `response.setContentType("text/html");` sets the content type of the response to HTML.
- `PrintWriter out = response.getWriter();` obtains a `PrintWriter` object to write HTML content
to the response.
- The `out.println()` statements generate a simple HTML page as the response.
Deploying a Servlet:
To deploy a servlet:
1. Compile: Compile your servlet class using the Java compiler (`javac`).
2. WAR File: Package your servlet along with other web resources (HTML files, JSP files, etc.)
into a WAR (Web ARchive) file.
3. Deploy: Deploy the WAR file to a servlet container (e.g., Tomcat) by placing it in the container's
`webapps` directory.
4. Access: Access your servlet using its URL, typically `http://localhost:8080/<webapp-
name>/<servlet-mapping>` where `<webapp-name>` is the name of your WAR file and `<servlet-
mapping>` is the URL pattern mapped to your servlet in the `web.xml` file or using annotations
(`@WebServlet`).
Servlet API:
The Servlet API provides interfaces and classes for developing servlets. Key classes include
`HttpServletRequest`, `HttpServletResponse`, `HttpServlet`, and `ServletConfig`.
Use Cases:
- Dynamic Web Applications: Servlets are used to generate dynamic content such as web pages,
XML, JSON, etc., based on user input or other factors.
- Middleware Components: Servlets serve as middleware components in enterprise applications,
integrating with databases, messaging systems, or other services.
- Web Services: Servlets can be used to implement web services (RESTful or SOAP-based) that
expose functionality over HTTP.
xxxxxxxxxxxxxxxx
LIFE CYCLE SIMPLE SERVLET
The lifecycle of a servlet in Java defines the phases from its initialization to its destruction.
Understanding the servlet lifecycle is crucial for developing and managing servlet-based
applications efficiently. Here's an overview of the lifecycle phases of a servlet:
150
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Servlet Lifecycle Phases


1. Loading and Instantiation:
- When a servlet container (like Tomcat or Jetty) starts or when the servlet is first accessed, the
container loads the servlet class.
- The container then creates an instance of the servlet by calling its no-argument constructor
(`public MyServlet()`).
2. Initialization (`init` method):
- After creating an instance, the servlet container initializes the servlet by calling its
`init(ServletConfig)` method.
- This method is typically used for one-time initialization tasks such as loading configuration
settings, establishing database connections, or initializing resources.
- The `init` method is called only once during the lifecycle of the servlet.
```java
@Override
public void init(ServletConfig config) throws ServletException {
// Initialization code here
}
```
3. Request Handling (`service` method):
- Once initialized, the servlet can handle client requests. Each time a request is received, the
servlet container calls the servlet's `service(ServletRequest, ServletResponse)` method.
- This method is responsible for processing the request and generating a response.
- Depending on the HTTP method (`GET`, `POST`, `PUT`, `DELETE`, etc.), the `service`
method dispatches the request to the appropriate handler method (`doGet`, `doPost`, etc.) defined in
the servlet class.
```java
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Request handling code here
}
```
4. Request Handling Methods (`doGet`, `doPost`, etc.):
- Servlets provide specific methods (`doGet`, `doPost`, `doPut`, `doDelete`, etc.) to handle
different types of HTTP requests.
151
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- These methods are called by the `service` method based on the request method (`GET`, `POST`,
etc.).

```java
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling GET request
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handling POST request
}
```
5. Destruction (`destroy` method):
- When the servlet container decides to remove the servlet instance (typically during shutdown or
when the servlet is no longer needed), it calls the servlet's `destroy()` method.
- This method allows the servlet to release any resources it has allocated and perform cleanup
tasks.
- The `destroy` method is called only once during the lifecycle of the servlet, just before the
servlet instance is removed from memory.

```java
@Override
public void destroy() {
// Cleanup code here
}
```
Example Lifecycle of a Simple Servlet
```java
import javax.servlet.;
import javax.servlet.http.;
import java.io.;
152
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class LifecycleServlet extends HttpServlet {

// Initialization method
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet initialization...");
}

// Service method handling requests


@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Servlet handling request...");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, Servlet!</h1>");
out.println("</body></html>");
}

// Destruction method
@Override
public void destroy() {
System.out.println("Servlet destruction...");
}
}
```
Lifecycle Execution Flow
- Initialization: When the servlet container loads the servlet, it calls `init(ServletConfig)` to perform
initialization tasks.
- Request Handling: Each time a client sends a request (e.g., accessing the servlet URL), the servlet
container calls `service(HttpServletRequest, HttpServletResponse)` to handle the request.
- Destruction: When the servlet container shuts down or decides to remove the servlet instance, it
calls `destroy()` to allow the servlet to clean up resources.
xxxxxxxxxxxxxxxx

153
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

SERVLET API
The Servlet API in Java provides a framework for creating and managing servlets, which
are Java classes that handle requests and responses between a client and a server. Servlets are part
of the Java Enterprise Edition (Java EE) platform and are widely used for building dynamic web
applications. Here‟s an overview of the Servlet API:
Key Components of the Servlet API
1. Servlet Interface (`javax.servlet.Servlet`):
- The `Servlet` interface defines methods that servlets must implement. It includes methods for
initialization, service handling, and destruction.
- Servlet classes typically extend `GenericServlet` or `HttpServlet`, which provide default
implementations for these methods.
2. GenericServlet (`javax.servlet.GenericServlet`):
- `GenericServlet` is an abstract class that implements the `Servlet` interface. It provides a
generic, protocol-independent servlet.
- Servlets can extend `GenericServlet` to handle any type of protocol, but it requires
implementing the `service(ServletRequest, ServletResponse)` method for request handling.
3. HttpServlet (`javax.servlet.http.HttpServlet`):
- `HttpServlet` extends `GenericServlet` and provides specific methods to handle HTTP requests
(`GET`, `POST`, `PUT`, `DELETE`, etc.).
- Servlets that handle HTTP requests often extend `HttpServlet` and override methods like
`doGet(HttpServletRequest, HttpServletResponse)` and `doPost(HttpServletRequest,
HttpServletResponse)`.
4. ServletRequest (`javax.servlet.ServletRequest`) and ServletResponse
(`javax.servlet.ServletResponse`):
- `ServletRequest` represents a client's request to the servlet container and provides methods to
access parameters, headers, and other request information.
- `ServletResponse` represents the servlet's response to the client and provides methods to set
headers, cookies, and write response data.
5. HttpServletRequest (`javax.servlet.http.HttpServletRequest`) and HttpServletResponse
(`javax.servlet.http.HttpServletResponse`):
- `HttpServletRequest` extends `ServletRequest` and provides additional methods specific to
HTTP requests, such as accessing HTTP headers, parameters, and session information.
- `HttpServletResponse` extends `ServletResponse` and provides methods to set HTTP status
codes, headers, and write data back to the client.

154
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

6. ServletConfig (`javax.servlet.ServletConfig`) and ServletContext


(`javax.servlet.ServletContext`):
- `ServletConfig` provides configuration information to a servlet during initialization, such as
initialization parameters specified in the deployment descriptor (`web.xml`) or annotations.
- `ServletContext` represents the servlet container and provides access to web application
resources, such as servlets, attributes, and context-wide parameters.
7. Session Management:
- The Servlet API supports session management using `HttpSession`
(`javax.servlet.http.HttpSession`), which allows servlets to maintain stateful conversations with
clients across multiple requests.
- Sessions can store user-specific data, such as shopping cart contents or user authentication
tokens, using attributes.
Example Usage:
```java
import javax.servlet.;
import javax.servlet.http.;
import java.io.;

public class HelloServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set content type and other response headers


response.setContentType("text/html");

// Get the PrintWriter object to write the HTML response


PrintWriter out = response.getWriter();

// Write the HTML response content


out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello, Servlet!</h1>");
155
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

out.println("<p>This is a simple example of HttpServlet.</p>");


out.println("</body></html>");
}
}
```
Deployment and Configuration:
Servlets are typically packaged as part of a web application in a WAR (Web ARchive) file,
which contains the servlet classes, configuration files (`web.xml` or annotations), and other
resources. The deployment descriptor (`web.xml`) specifies mappings between URLs and servlet
classes.
Servlet Container:
A servlet container (such as Apache Tomcat, Jetty, or WildFly) is responsible for managing
servlet lifecycle, routing requests to servlets, and providing runtime environment for servlet
execution.
Benefits of Servlet API:
- Platform Independence: Servlets are written in Java, making them platform-independent and
compatible with any servlet container that supports the Java Servlet API.
- Extensibility: Servlet API provides a flexible framework for building dynamic web applications,
supporting various protocols and handling different types of requests.
- Integration: Servlets can be integrated with other Java EE technologies (like JSP, JDBC, EJB) and
frameworks (like Spring MVC) to build scalable and robust web applications.
xxxxxxxxxxxxxxxx
PACKAGES
In Java, packages are used to organize classes and interfaces into namespaces, providing a
way to avoid naming conflicts and to manage dependencies effectively. Here's a comprehensive
overview of packages in Java:
What is a Package?
A package in Java is a namespace that organizes a set of related classes and interfaces. It
helps in categorizing the classes and provides access protection and namespace management.
Packages allow you to group classes logically, making it easier to locate and use them within large
projects.
Benefits of Using Packages:
1. Namespace Management: Packages prevent naming conflicts by grouping classes under unique
package names. For example, classes named `util.List` and `io.List` can coexist in different
packages (`util` and `io`, respectively).
156
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

2. Access Control: Classes within the same package have default (package-private) access,
allowing them to access each other's members without using explicit access modifiers (e.g.,
`public`, `private`, `protected`). This promotes encapsulation and controlled visibility.
3. Organization and Maintainability: Packages provide a hierarchical structure for organizing
classes. This helps in locating classes quickly, improving code readability, and maintaining large
codebases.
4. Modularity and Reusability: Packages facilitate modularity by allowing developers to group
related classes together. This modular design promotes code reuse and enhances maintainability.
Package Naming Convention:
- Packages are typically named using a reversed domain name (e.g., `com.example.packageName`).
This convention helps ensure package names are unique and minimizes the risk of naming
conflicts.
- Example: `com.example.util`, `com.example.data`, `org.apache.commons`, etc.
Package Declaration:
- A Java source file can explicitly declare its package using the `package` keyword as the first
statement in the file.
- Example:
```java
package com.example.util;

public class MyClass {


// Class implementation
}
```
- If no package declaration is provided, the classes are placed in the default package, which is not
recommended for production code due to potential naming conflicts.
Importing Packages:
- To use classes from another package, you can import them using the `import` statement. This
allows you to refer to the imported classes by their simple names.
- Example:
```java
package com.example.app;

import com.example.util.MyClass;

157
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
// Use obj and other classes from imported packages
}
}
```
- Wildcard imports (`import com.example.util.;`) can be used to import all classes from a package
but should be used judiciously to avoid importing unnecessary classes.
Java Platform Packages:
- Java provides several built-in packages (`java.lang`, `java.util`, `java.io`, etc.) that contain
fundamental classes and interfaces used in most Java applications.
- Example usage:
```java
import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
```
Creating Custom Packages:
- To create your own packages, organize your classes into directories matching the package
structure (`com/example/util/MyClass.java`).
- Use the `package` declaration at the beginning of each source file to specify the package name.
Package Visibility:
- Classes and members with default access (no explicit access modifier) are accessible only within
the same package.
- Classes and members marked `public` are accessible from any other package.

158
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Classes and members marked `protected` are accessible within the same package and by
subclasses (even if they are in different packages).
- Classes and members marked `private` are accessible only within the same class.
xxxxxxxxxxxxxxxx
COOKIES SESSION TRACKING
Cookies and session tracking are essential concepts in web development, particularly in
managing stateful interactions between web servers and clients. They are crucial for maintaining
user sessions, personalizing experiences, and managing user authentication across multiple
requests. Here‟s an overview of cookies and session tracking in the context of web applications:
Cookies
Cookies are small pieces of data sent from a web server to a user's browser and stored
locally on the user's machine. They are used to store information about the user's session or
preferences and are sent back to the server with every subsequent request from the same client.
Key Characteristics:
1. Purpose: Cookies are commonly used for session management, user authentication,
personalization, tracking user behavior, and storing user preferences.
2. Attributes: Cookies have attributes such as name, value, domain, path, expiration time, and
secure flag.
3. Types:
- Session Cookies: These cookies are stored temporarily in the browser's memory and are deleted
when the browser is closed.
- Persistent Cookies: These cookies are stored on the user's device for a specified period (defined
by the `maxAge` or `expires` attribute) and persist across browser sessions.
4. Access: Cookies can be accessed and manipulated both on the server-side (via HTTP headers)
and on the client-side (via JavaScript).
Example of Setting and Retrieving Cookies in Java Servlet:
```java
import javax.servlet.;
import javax.servlet.http.;
import java.io.;
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

159
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// Create a cookie
Cookie cookie = new Cookie("username", "john_doe");

// Set the cookie path and maximum age


cookie.setPath("/");
cookie.setMaxAge(24 60 60); // 1 day in seconds

// Add the cookie to the response


response.addCookie(cookie);

// Write response content


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<p>Cookie set successfully!</p>");
out.println("</body></html>");
}
}
```
Retrieving Cookies:
```java
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
// Process cookie data
}
}
```
Session Tracking
Session tracking refers to the process of maintaining stateful information about a user's
interactions with a web application across multiple requests. Unlike cookies, which are stored on
the client-side, session tracking typically involves storing session data on the server-side.

160
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Techniques for Session Tracking:


1. Cookies: The most common technique uses cookies to store a session identifier (session ID) on
the client side. The server uses this ID to retrieve session data stored on the server.
2. URL Rewriting: Session IDs can be appended to URLs as query parameters (`URL rewriting`).
This allows the server to track sessions without relying on cookies.
3. Hidden Form Fields: Session IDs can be stored in hidden form fields and submitted with each
form submission.
4. HTTP Session Object: In Java EE web applications, session tracking is often managed using the
`HttpSession` object provided by the servlet container. This object allows storing session attributes
accessible across multiple requests.
Example of Using HttpSession in Java Servlet:
```java
import javax.servlet.;
import javax.servlet.http.;
import java.io.;
public class SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get or create the HttpSession object
HttpSession session = request.getSession();

// Set session attributes


session.setAttribute("username", "john_doe");

// Write response content


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<p>Session attribute set successfully!</p>");
out.println("</body></html>");
}
}
```

161
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Retrieving Session Attributes:


```java
HttpSession session = request.getSession(false); // false means do not create new session if not
exists
if (session != null) {
String username = (String) session.getAttribute("username");
// Process session data
}
```
Security Considerations:
- Sensitive Information: Avoid storing sensitive information in cookies due to potential security
risks (use secure cookies for sensitive data).
- Session Fixation: Protect against session fixation attacks by generating a new session ID after
successful authentication.
xxxxxxxxxxxxxxxx
UNIT IV QUESTION BANK
ONE MARK QUESTIONS
1. Which of the following statements best describes Java Beans?
- A) Java Beans are software components that can be manipulated visually in design-time
environments.
- B) Java Beans are data storage containers used exclusively in server-side applications.
- C) Java Beans are a type of coffee-based Java programming language feature.
- D) Java Beans are hardware components used to enhance Java applications.
Answer: A) Java Beans are software components that can be manipulated visually in
design-time environments.
2. What is one of the advantages of using Java Beans in software development?
- A) They are suitable only for desktop applications.
- B) They cannot be serialized.
- C) They encourage reusability and easy integration due to standardized interfaces.
- D) They require a separate runtime environment.
Answer: C) They encourage reusability and easy integration due to standardized interfaces.
3. What does introspection allow developers to do in Java Beans?
- A) Modify the internal structure of beans at runtime.
- B) Inspect and modify the properties and methods of beans dynamically.
- C) Access private methods of Java classes.
162
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- D) Automatically generate Java classes.


Answer: B) Inspect and modify the properties and methods of beans dynamically.
4. Which API is used for developing and manipulating Java Beans?
- A) Java EE API - B) Java SE API - C) JavaBeans API - D) JavaFX API
Answer: C) JavaBeans API
5. Which of the following is an example of a Java Bean?
- A) A static method in a utility class
- B) A simple POJO (Plain Old Java Object) with private fields and public getter and setter
methods
- C) A database connection pool
- D) A singleton class with a private constructor
Answer: B) A simple POJO (Plain Old Java Object) with private fields and public getter
and setter methods
6. What is the purpose of the servlet life cycle in Java?
- A) To handle HTTP requests and generate responses dynamically
- B) To manage database connections
- C) To create static web pages - D) To debug Java applications
Answer: A) To handle HTTP requests and generate responses dynamically
7. Which package contains the core classes and interfaces for servlet development in Java?
- A) java.io - B) javax.servlet - C) java.net - D) javax.swing
Answer: B) javax.servlet
8. How do servlets typically maintain session state information across multiple client requests?
- A) Using HTTP headers - B) Using annotations - C) Using cookies
- D) Using JavaBeans
Answer: C) Using cookies
9. Which component of the Servlet API is responsible for managing client sessions?
- A) HttpSession - B) HttpServletResponse
- C) ServletConfig - D) ServletContext
Answer: A) HttpSession
10. What is a simple way to initiate a servlet‟s execution?
- A) By invoking its `main()` method
- B) By deploying it as a standalone application
- C) By mapping it to a URL in a deployment descriptor (web.xml)
- D) By embedding it within an applet
Answer: C) By mapping it to a URL in a deployment descriptor (web.xml)
163
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

FIVE MARK & TEN MARK QUESTIONS


1. Describe the concept of Java Beans. What are the key characteristics that define a Java Bean?
2. Discuss five advantages of using Java Beans in software development.
3. Explain the process of introspection in Java Beans.
4. Describe the JavaBeans API.
5. Provide a detailed example of a Java Bean. Include its properties, methods, and events.
6. Explain the lifecycle of a servlet in Java.
7. Discuss the servlet API in Java.
8. Explain the concept of cookies in servlet-based web applications.
9. Describe the session tracking mechanisms supported by servlets.
10. Provide an example of a simple servlet that demonstrates session tracking using cookies.
xxxxxxxxxxxxxxxx UNIT IV END xxxxxxxxxxxxxxxx

164
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

UNIT – V
Network Programming: Working with URLs- Working with Sockets - Remote Method
Invocation. Introduction to Database Management Systems - Tables, Rows, and Columns -
Introduction to the SQL SELECT Statement - Inserting Rows - Updating and Deleting Existing
Rows - Creating and Deleting Tables - Creating a New Database with JDBC - Scrollable Result
Sets.
xxxxxxxxxxxxxxxx
NETWORK PROGRAMMING
Java network programming involves developing applications that communicate over the
network using Java's networking capabilities. Here are some key aspects and topics typically
covered in Java network programming:
1. Socket Programming:
- Understanding sockets, which are endpoints for communication between machines over a
network.
- Differentiating between client sockets (Socket) and server sockets (ServerSocket).
- Implementing basic client-server communication using sockets.
2. TCP/IP and UDP Protocols:
- Understanding TCP (Transmission Control Protocol) and UDP (User Datagram Protocol), the
two primary protocols used for communication over the Internet.
- Differences between TCP and UDP in terms of reliability, connection-oriented vs.
connectionless communication.
3. URL Handling:
- Using Java's URL and URLConnection classes to work with URLs and retrieve data from web
servers.
- Handling HTTP connections and parsing responses using HttpURLConnection.
4. Multithreaded Network Programming:
- Implementing multithreaded servers to handle multiple client connections concurrently.
- Managing thread synchronization and communication between threads in a networked
environment.
5. Datagram Programming:
- Understanding datagram packets and DatagramSocket for connectionless communication using
UDP.
- Implementing simple client-server applications using DatagramSocket.
6. Networking APIs and Libraries:
- Overview of Java's java.net package and its classes for networking tasks.
165
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Using higher-level APIs like java.nio for non-blocking I/O operations.


7. Network Security:
- Basics of securing network communications using SSL/TLS.
- Implementing secure client-server communication with Java's SSLSocket and
SSLServerSocket.
8. Remote Method Invocation (RMI):
- Overview of Java RMI for building distributed applications where Java objects on different
JVMs can communicate with each other.
- Implementing RMI servers and clients using java.rmi package.
9. Asynchronous Programming:
- Using java.nio and java.nio.channels for asynchronous I/O operations.
- Implementing non-blocking network communication using Selectors and Channels.
10. Proxy Servers and Sockets:
- Configuring Java applications to communicate through proxy servers using Proxy class.
- Handling socket connections through proxies using ProxySelector and Proxy classes.
- Java's robust networking capabilities make it suitable for developing a wide range of networked
applications, from simple client-server interactions to complex distributed systems. Mastering Java
network programming involves understanding these concepts and effectively utilizing Java's APIs
to implement reliable and efficient networked applications.
xxxxxxxxxxxxxxxx
WORKING WITH URLS
Working with URLs in Java involves several classes in the `java.net` package, primarily
`URL` and `URLConnection`. Here‟s a basic overview of how you can work with URLs in Java:
1. Creating a URL Object
You can create a `URL` object using its constructor, which accepts a string representation of the
URL.

```java
import java.net.URL;
public class URLExample {
public static void main(String[] args) throws Exception {
// Create a URL object
URL url = new URL("https://www.example.com");

// You can also specify a specific resource on the URL


166
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

// URL url = new URL("https://www.example.com/path/to/resource");

// Use the URL object


System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("File: " + url.getFile());
}
}
```
2. Reading from a URL
To read data from a URL, you typically use a `URLConnection` object obtained from the
`openConnection()` method of a `URL` object.
```java
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
// Open a connection stream
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
// Read the data from the URL
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Close the reader
reader.close();
}
}
167
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```
3. Handling Exceptions
When working with URLs in Java, you need to handle exceptions that may occur due to network
issues or incorrect URLs. Make sure to catch and handle these exceptions appropriately.

```java
import java.net.URL;
import java.net.MalformedURLException;

public class URLExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");

// Use the URL object


System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host: " + url.getHost());
System.out.println("Port: " + url.getPort());
System.out.println("Path: " + url.getPath());
System.out.println("File: " + url.getFile());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
```
4. More Advanced Operations
For more advanced operations such as sending data to a server (HTTP POST requests), setting
request headers, or handling different types of content, you may need to use additional classes like
`HttpURLConnection` or third-party libraries like Apache HttpClient.

xxxxxxxxxxxxxxxx

168
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

WORKING WITH SOCKETS


Working with sockets in Java allows you to create network connections between two
devices (client and server) for communication. Java provides classes in the `java.net` package to
work with sockets, primarily `Socket` for client-side and `ServerSocket` for server-side operations.
Client-side Socket Example
To establish a client-side socket connection:
1. Creating a Socket:
Use the `Socket` class to create a socket and connect it to a specified server and port.
```java
import java.io.;
import java.net.;
public class ClientSocketExample {
public static void main(String[] args) {
String serverName = "localhost"; // Replace with your server's IP or hostname
int port = 12345; // Replace with your server's port

try {
// Create a socket to connect to the server
Socket socket = new Socket(serverName, port);

// Open input and output streams


OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);

// Write data to the server


out.writeUTF("Hello from client " + socket.getLocalSocketAddress());

// Close the connection


socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
169
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Server-side Socket Example


To create a server-side socket that listens for incoming connections:
1. Creating a ServerSocket:
Use the `ServerSocket` class to create a server socket that listens on a specified port.
2. Accepting Connections:
Use the `accept()` method of `ServerSocket` to accept incoming client connections.
```java
import java.io.;
import java.net.;
public class ServerSocketExample {
public static void main(String[] args) {
int port = 12345; // Port on which the server will listen
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(port);

// Wait for client connection


System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();

System.out.println("Connected to " + server.getRemoteSocketAddress());

// Open input and output streams


InputStream inFromClient = server.getInputStream();
DataInputStream in = new DataInputStream(inFromClient);

// Read data from the client


System.out.println("Client says: " + in.readUTF());

// Close the connection


server.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
170
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

}
}
```
Key Points:
- Client-side: Use `Socket` to connect to a server by specifying its IP address or hostname and port
number. Use `OutputStream` or `DataOutputStream` to send data to the server.
- Server-side: Use `ServerSocket` to listen on a specific port for incoming client connections. Use
`accept()` to accept a client connection, then use `InputStream` or `DataInputStream` to receive
data from the client.
- Exception Handling: Always handle `IOException` which may occur during socket operations
due to network issues or other errors.
- Closing Sockets: Always close sockets properly using `close()` method to release resources and
properly terminate connections.Working with sockets allows Java applications to communicate
over a network, enabling various types of client-server and peer-to-peer interactions.
xxxxxxxxxxxxxxxx
REMOTE METHOD INVOCATION
Remote Method Invocation (RMI) is a Java technology that allows an object running in one
Java virtual machine (VM) to invoke methods on an object running in another Java VM, possibly
on a different physical machine. RMI enables distributed computing by providing a mechanism
similar to calling a method on a local object, but the actual implementation resides on a remote
server.
Components of RMI:
1. Remote Interface:
- Define the interface that declares the methods which can be invoked remotely. This interface
must extend `java.rmi.Remote` and each method must declare `java.rmi.RemoteException` in its
throws clause.
```java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteInterface extends Remote {
// Remote method declaration
public String sayHello() throws RemoteException;
}
```

171
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

2. Remote Implementation:
- Implement the remote interface with the actual functionality of the methods. This class will
extend `java.rmi.server.UnicastRemoteObject`.
```java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class RemoteImplementation extends UnicastRemoteObject implements RemoteInterface
{
public RemoteImplementation() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello, World!";
}
}
```
3. Server Setup:
- Create a server that binds an instance of the remote object to a name in the RMI registry.
```java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
// Create an instance of the remote object
RemoteInterface remoteObj = new RemoteImplementation();

// Create RMI registry on default port 1099


Registry registry = LocateRegistry.createRegistry(1099);

// Bind the remote object to the registry with a name


registry.rebind("RemoteObject", remoteObj);

System.out.println("Server is running...");
172
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

} catch (Exception e) {
e.printStackTrace();
}
}
}
```
4. Client Setup:
- Create a client that looks up the remote object from the RMI registry and invokes methods on it.
```java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
// Get the registry
Registry registry = LocateRegistry.getRegistry("localhost", 1099);

// Lookup the remote object from the registry


RemoteInterface remoteObj = (RemoteInterface) registry.lookup("RemoteObject");

// Invoke remote method


String result = remoteObj.sayHello();
System.out.println("Response from server: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
Key Points:
- Interface Inheritance: Remote interfaces extend `java.rmi.Remote` and methods declare
`java.rmi.RemoteException` to handle remote method invocation errors.
- Server Binding: The server binds an instance of the remote object to a name in the RMI registry
using `Registry.rebind()`.

173
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Client Lookup: The client obtains a reference to the remote object from the RMI registry using
`Registry.lookup()` and casts it to the remote interface type.
- Exceptions: Both server and client code should handle `RemoteException` which may occur
during network communication or RMI-specific errors.
- RMI Registry: Acts as a mediator between clients and remote objects, mapping names to remote
object references. Remote Method Invocation simplifies the process of invoking methods on
objects residing in different Java VMs, providing a powerful tool for building distributed
applications in Java.
xxxxxxxxxxxxxxxx
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS
A Database Management System (DBMS) is a software system that allows for the creation,
management, and use of databases. It is a crucial component in modern software applications,
providing a structured and efficient way to store, retrieve, modify, and organize data. Here's an
introduction to the key concepts and components of Database Management Systems:
Components of a DBMS:
1. Data Definition Language (DDL):
- DDL is used to define the structure of the database, including defining data types, relationships
between tables, and constraints (e.g., primary keys, foreign keys). Examples include `CREATE`,
`ALTER`, `DROP` statements.
2. Data Manipulation Language (DML):
- DML is used to manipulate the data stored in the database. This includes operations such as
inserting, updating, deleting, and retrieving data from tables. Examples include `INSERT`,
`UPDATE`, `DELETE`, and `SELECT` statements.
3. Query Language:
- DBMS provides a query language to interact with the database. The most commonly used query
language is SQL (Structured Query Language), which allows users and applications to perform
various operations on the database.
4. Transaction Management:
- DBMS ensures ACID properties (Atomicity, Consistency, Isolation, Durability) for
transactions. It manages concurrent access to data to ensure consistency and prevents data
corruption.
5. Storage Management:
- DBMS manages how data is stored physically on storage devices (hard drives, SSDs, etc.). It
optimizes storage allocation and retrieval for efficient data access and performance.

174
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

6. Indexing and Optimization:


- DBMS uses indexing techniques to improve the speed of data retrieval operations. It analyzes
queries and decides the most efficient way to execute them using query optimization techniques.
7. Concurrency Control:
- DBMS ensures that multiple users or applications can access the database concurrently without
interfering with each other's operations. It manages locking mechanisms and transaction isolation
levels.
8. Backup and Recovery:
- DBMS provides mechanisms for data backup and recovery to protect against data loss due to
hardware failure, human error, or other disasters. It supports full and incremental backups, as well
as recovery to a consistent state.
Types of DBMS:
1. Relational DBMS (RDBMS):
- Organizes data into tables with rows and columns, where each row represents a record and each
column represents an attribute. Examples include MySQL, PostgreSQL, Oracle Database.

2. NoSQL DBMS:
- Non-relational databases designed to handle large volumes of unstructured or semi-structured
data. Types include document-oriented (e.g., MongoDB), key-value stores (e.g., Redis), column-
family stores (e.g., Cassandra).

3. Object-Oriented DBMS (OODBMS):


- Stores objects rather than data in tables. Suitable for object-oriented programming languages.
Examples include db4o, ObjectDB.

4. Graph DBMS:
- Stores data in graph structures with nodes, edges, and properties. Suitable for applications
requiring complex relationships and network analysis. Examples include Neo4j, OrientDB.

Advantages of Using DBMS:


- Data Integration: Centralized data management allows for easier integration and sharing of data
across multiple applications.
- Data Security: DBMS provides security mechanisms to control access to data, ensuring only
authorized users can modify or view sensitive information.

175
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Data Consistency: Ensures data integrity and consistency across the database, preventing
anomalies and maintaining reliability.
- Data Independence: Separates the physical storage of data from its logical structure, allowing
applications to access data without needing to know its physical location.
- Scalability: Supports scalability by handling large volumes of data and accommodating growth in
users and transactions.
xxxxxxxxxxxxxxxx
TABLES, ROWS, AND COLUMNS
In the context of Database Management Systems (DBMS), tables, rows, and columns are
fundamental concepts that define the structure and organization of data within a relational database.
Here‟s an overview of each:

Tables:
- Definition:
- A table is a structured representation of data in a DBMS. It consists of rows and columns where
each row represents a record and each column represents an attribute of that record.
- Characteristics:
- Name: Tables have unique names within a database schema.
- Structure: Tables are organized into rows and columns.
- Schema: Defines the structure of the table, including column names, data types, constraints, etc.
- Relationships: Tables can have relationships with other tables through keys (e.g., primary keys,
foreign keys).
- Example:
- Consider a `Users` table in a social media application:
| user_id | username | email | birthdate |
|---------|-------------|----------------------|------------|
|1 | john_doe | [email protected] | 1990-05-15 |
|2 | jenny_smith | [email protected] | 1988-09-20 |
|3 | robert_jones| [email protected]| 1995-03-10 |
Rows:
- Definition:
- A row, also known as a tuple, is a horizontal entity in a table that represents a single record or
data point. Each row contains data values for each column defined in the table schema.
- Characteristics:
- Uniqueness: Each row in a table is unique and identified by a primary key (if defined).
176
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Order: Rows are not inherently ordered unless specified by an ORDER BY clause in SQL
queries.
- Attributes: Each row contains values for all columns defined in the table schema.

- Example:
- In the `Users` table example:
- Row 1: (1, john_doe, [email protected], 1990-05-15)
- Row 2: (2, jenny_smith, [email protected], 1988-09-20)
- Row 3: (3, robert_jones, [email protected], 1995-03-10)

Columns:
- Definition:
- A column, also known as a field or attribute, is a vertical entity in a table that represents a
specific data type and holds a particular type of data. Columns define the structure of the table and
provide context to the data stored in the rows.
- Characteristics:
- Data Type: Each column has a defined data type (e.g., integer, varchar, date).
- Name: Columns are identified by unique names within a table.
- Constraints: Columns can have constraints (e.g., NOT NULL, UNIQUE) to enforce data
integrity.
- Example:
- In the `Users` table example:
- `user_id`, `username`, `email`, and `birthdate` are columns.
- Each column has a specific data type (e.g., `user_id` might be an integer, `username` and
`email` might be strings, `birthdate` might be a date).
Summary:
- Tables organize data into structured collections of rows and columns.
- Rows represent individual records or data points within a table.
- Columns define the attributes or fields that hold specific types of data in a table. Understanding
tables, rows, and columns is essential for designing and interacting with relational databases
effectively. These concepts provide a foundation for creating schemas, querying data, and
maintaining data integrity within a DBMS environment.
xxxxxxxxxxxxxxxxxxxxxxxxxxx

177
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

INTRODUCTION TO THE SQL SELECT STATEMENT


The SQL `SELECT` statement is fundamental to retrieving data from a database. It allows
you to specify which columns of data you want to retrieve from one or more tables, along with
optional filtering and sorting criteria. Here‟s an introduction to the SQL `SELECT` statement:

Syntax:

```sql
SELECT column1, column2, ...
FROM table_name;
```
- `SELECT`: Specifies the columns that you want to retrieve data from.
- `FROM`: Specifies the table or tables from which to retrieve the data.

Example:
Consider a simple `Users` table with columns `user_id`, `username`, `email`, and `birthdate`.
Here‟s how you might use the `SELECT` statement to retrieve data from this table:

```sql
-- Select all columns from the Users table
SELECT
FROM Users;
```
```sql
-- Select specific columns from the Users table
SELECT user_id, username, email
FROM Users;
```
Additional Clauses:
1. `WHERE` Clause:
- Allows you to filter rows based on specific conditions.

```sql
-- Select users with user_id greater than 10
SELECT user_id, username
178
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

FROM Users
WHERE user_id > 10;
```
2. `ORDER BY` Clause:
- Sorts the result set based on one or more columns.

```sql
-- Select users and order them by username in ascending order
SELECT user_id, username, email
FROM Users
ORDER BY username ASC;
```
3. `LIMIT` Clause (or `TOP` in some SQL dialects):
- Limits the number of rows returned by the query.
```sql
-- Select the top 5 users ordered by user_id descending
SELECT
FROM Users
ORDER BY user_id DESC
LIMIT 5;
```
4. Aggregate Functions:
- Perform calculations on sets of rows and return a single value.

```sql
-- Calculate the average age of users
SELECT AVG(YEAR(NOW()) - YEAR(birthdate)) AS average_age
FROM Users;
```

5. Grouping and Aggregation (`GROUP BY` and `HAVING`):


- Groups rows that have the same values into summary rows, and filter groups based on specified
conditions.

```sql
179
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

-- Count the number of users born in each year and filter those with more than 10 users
SELECT YEAR(birthdate) AS birth_year, COUNT() AS num_users
FROM Users
GROUP BY birth_year
HAVING COUNT() > 10;
```
Key Points:
- SQL (`Structured Query Language`) is the standard language for interacting with relational
databases.
- SELECT statements retrieve data from one or more tables based on specified criteria.
- WHERE clause filters rows based on conditions.
- ORDER BY sorts the result set.
- LIMIT (or `TOP`) limits the number of rows returned.
- Aggregate functions perform calculations on sets of rows.
- GROUP BY and HAVING allow for grouping and filtering of aggregated data. Understanding
how to use the `SELECT` statement effectively is crucial for querying and manipulating data in
relational databases. It forms the foundation for retrieving specific data sets, performing
calculations, and analyzing trends within your database tables.
xxxxxxxxxxxxxxxxxxxxxxxxxx
INSERTING ROWS
Inserting rows into a table is a basic operation in SQL that allows you to add new data into a
database table. Here‟s an introduction to inserting rows using the SQL `INSERT` statement:

Syntax:
```sql
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
```
- `INSERT INTO`: Specifies the table where you want to insert data.
- `VALUES`: Specifies the values to be inserted into the columns.
Example:
Consider a `Users` table with columns `user_id`, `username`, `email`, and `birthdate`.
Here‟s how you might insert a new row into this table:

180
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```sql
INSERT INTO Users (username, email, birthdate)
VALUES ('john_doe', '[email protected]', '1990-05-15');
```
Inserting Multiple Rows:
You can also insert multiple rows at once by specifying multiple sets of values in the `VALUES`
clause:
```sql
INSERT INTO Users (username, email, birthdate)
VALUES ('jane_smith', '[email protected]', '1988-09-20'),
('robert_jones', '[email protected]', '1995-03-10');
```
Inserting Values into All Columns:
If you want to insert values into all columns of a table, you can omit the column names in
the `INSERT INTO` statement. However, it‟s generally good practice to specify column names
explicitly to avoid errors and ensure clarity:

```sql
-- Inserting values into all columns
INSERT INTO Users
VALUES (1, 'john_doe', '[email protected]', '1990-05-15');
```
Key Points to Remember:
- Data Types: Ensure that the data types of the values being inserted match the data types of the
columns in the table.
- Primary Keys: If a table has a primary key defined, ensure that the values being inserted do not
violate the uniqueness constraint of the primary key.
- Single vs. Batch Inserts: Use single `INSERT` statements for inserting one or a few rows, and
batch inserts (multiple sets of values) for inserting multiple rows at once, which can be more
efficient.
Handling Generated Values:
Some databases support auto-generated values for certain columns, such as auto-
incrementing primary keys. Here‟s an example using an auto-incrementing primary key (`user_id`):

181
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

```sql
INSERT INTO Users (username, email, birthdate)
VALUES ('john_doe', '[email protected]', '1990-05-15');
```
If `user_id` is configured to auto-increment, the database will automatically generate the
next value for `user_id`.
Inserting rows into a database table is a fundamental operation in SQL. It allows you to add
new data into your database, enabling applications to store and manage information effectively.
Understanding how to construct and execute `INSERT` statements is essential for building and
maintaining databases in SQL-based systems.
xxxxxxxxxxxxxxxxxxxxxxxxx
UPDATING AND DELETING EXISTING ROWS
Updating and deleting existing rows are essential operations in SQL for modifying data
within database tables. These operations allow you to change existing data or remove unwanted
records. Here‟s how you can perform updates and deletions using SQL:

Updating Rows:
To update existing rows in a table, use the `UPDATE` statement. This statement modifies
existing data based on specified conditions.
Syntax:
```sql
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
```
- `UPDATE`: Specifies the table where you want to update data.
- `SET`: Specifies the columns to be updated along with their new values.
- `WHERE`: Specifies the condition(s) that must be met for the rows to be updated. If omitted, all
rows in the table will be updated.
Example:
Assume we have a `Users` table with columns `user_id`, `username`, `email`, and
`birthdate`. Here‟s how you might update the email address of a user:
```sql
UPDATE Users
SET email = '[email protected]'
182
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

WHERE username = 'john_doe';


```
This statement updates the `email` column of the `Users` table where the `username` is
`'john_doe'`.
Deleting Rows:
To delete existing rows from a table, use the `DELETE` statement. This statement removes records
based on specified conditions.
Syntax:
```sql
DELETE FROM table_name
WHERE condition;
```
- `DELETE FROM`: Specifies the table from which you want to delete data.
- `WHERE`: Specifies the condition(s) that must be met for the rows to be deleted. If omitted, all
rows in the table will be deleted.
Example:
Continuing with our `Users` table example, suppose you want to delete a user record based on their
`user_id`:
```sql
DELETE FROM Users
WHERE user_id = 1;
```
This statement deletes the row from the `Users` table where the `user_id` is `1`.
Key Points to Remember:
- Safety: Always be cautious when using `UPDATE` and `DELETE` statements, especially without
a `WHERE` clause, as they can affect large portions of data or even all data in a table if not used
carefully.
- Transactions: Wrap multiple update or delete operations within a transaction to ensure
consistency and rollback capabilities in case of errors.
- Performance: Consider the impact of updates and deletions on database performance, especially in
large tables. Use appropriate indexing and optimization techniques.
- Logging and Recovery: Database systems often provide transaction logs to track changes,
enabling recovery to a previous state if necessary.
Example of Using Both Operations:

183
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

You might update records to correct or modify existing data, and then delete records that are no
longer needed. For instance:
```sql
-- Update email address for a user
UPDATE Users
SET email = '[email protected]'
WHERE user_id = 2;
-- Delete inactive users
DELETE FROM Users
WHERE last_login_date < '2023-01-01';
```
These statements demonstrate how updates and deletions can be used in combination to
maintain and manage data within a database table effectively.
Understanding how to properly use `UPDATE` and `DELETE` statements is crucial for
maintaining data integrity and managing databases efficiently in SQL-based systems.
xxxxxxxxxxxxxxxxxxxxxxxxxx
CREATING AND DELETING TABLES
Creating and deleting tables are fundamental operations in SQL for defining
and managing database structures. These operations allow you to create new tables to
store data and delete existing tables when they are no longer needed. Here‟s how you
can create and delete tables using SQL:

Creating Tables:
To create a new table in a database, use the `CREATE TABLE` statement.
This statement defines the structure of the table, including its columns, data types,
constraints, and indexes.

Syntax:

```sql
CREATE TABLE table_name (
column1 datatype constraints,
184
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

column2 datatype constraints,


...
PRIMARY KEY (one or more columns),
FOREIGN KEY (column) REFERENCES parent_table(parent_column)
);
```
- `CREATE TABLE`: Specifies the name of the table to be created.
- `column1, column2, ...`: Define the columns of the table along with their data types
and any constraints (e.g., `NOT NULL`, `UNIQUE`).
- `PRIMARY KEY`: Specifies one or more columns as the primary key for the table.
A primary key uniquely identifies each row in the table.
- `FOREIGN KEY`: Defines a foreign key constraint, which establishes a link
between two tables. It ensures referential integrity.
Example:
Let's create a `Users` table with columns `user_id`, `username`, `email`, and
`birthdate`:
```sql
CREATE TABLE Users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
birthdate DATE
);
```
In this example:
- `user_id` is an integer column and serves as the primary key with auto-increment
(`AUTO_INCREMENT` in MySQL) to generate unique values automatically.
- `username` is a varchar column with a maximum length of 50 characters and is
required (`NOT NULL`).

185
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- `email` is a varchar column with a maximum length of 100 characters, must be


unique (`UNIQUE`), and is required (`NOT NULL`).
- `birthdate` is a date column to store the user's birthdate.

Deleting Tables:
To delete an existing table from a database, use the `DROP TABLE` statement. This
operation permanently removes the table and all its data from the database.
Syntax:
```sql
DROP TABLE table_name;
```
- `DROP TABLE`: Specifies the name of the table to be deleted.
Example:
Suppose you want to delete the `Users` table created earlier:
```sql
DROP TABLE Users;
```
Considerations:
- Data Loss: Deleting a table using `DROP TABLE` removes all data stored in that
table. Ensure that you have backed up any important data before performing this
operation.
- Dependencies: If the table has dependencies, such as foreign keys referencing it
from other tables, you may need to drop those foreign key constraints first before
dropping the table itself.
- Permissions: Ensure that you have sufficient permissions to create and delete tables
in the database.
Example of Using Both Operations:
Here‟s an example of creating a table and then deleting it:
```sql
-- Create a new table
186
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

CREATE TABLE Products (


product_id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
category VARCHAR(50)
);
-- Delete the Products table
DROP TABLE Products;
```
 These statements illustrate how to create a new table (`Products`) with
specified columns and constraints, and then delete that table when it's no
longer needed.
 Understanding how to create and delete tables in SQL is essential for database
administrators and developers managing database structures and ensuring data
organization and integrity within applications.
xxxxxxxxxxxxxxxxxxx
CREATING A NEW DATABASE WITH JDBC
Creating a new database using JDBC (Java Database Connectivity) involves connecting to a
database server and executing SQL statements to create the database schema. Here‟s a step-by-step
guide on how to create a new database using JDBC:

Step 1: Include JDBC Driver


Ensure you have the JDBC driver for your database (e.g., MySQL, PostgreSQL) included in
your Java project. You typically download the JDBC driver from the database vendor's website and
add it to your project's classpath or dependencies.
Step 2: Establish Database Connection
First, establish a connection to your database server using JDBC. This involves creating a
connection object (`Connection`) using the appropriate connection URL, username, and password.
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
187
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

public class CreateDatabaseExample {


public static void main(String[] args) {
// JDBC URL for MySQL database
String jdbcUrl = "jdbc:mysql://localhost:3306/";
String username = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {


if (conn != null) {
System.out.println("Connected to the database");

// Proceed to create a new database


String dbName = "new_database";
String sql = "CREATE DATABASE " + dbName;

// Execute SQL statement to create the database


conn.createStatement().executeUpdate(sql);

System.out.println("Database created successfully: " + dbName);


}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
Explanation:
- JDBC URL: Specifies the connection URL to your database server. Modify
`jdbc:mysql://localhost:3306/` according to your database server's host, port, and any additional
configuration.
- Connection: Uses `DriverManager.getConnection()` to establish a connection to the database
server using the provided username and password.

188
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Creating the Database: Executes an SQL `CREATE DATABASE` statement within the
established connection to create a new database.
- Ensure you have appropriate permissions and privileges to create databases on the database
server.
- Replace `"your_username"` and `"your_password"` with your actual database username and
password.
- Modify the JDBC URL (`jdbc:mysql://localhost:3306/`) based on your database type (e.g.,
MySQL, PostgreSQL) and configuration.
Handling Exceptions:
Make sure to handle `SQLException` properly, as shown in the example, to catch any
potential errors that may occur during database connection or SQL statement execution.
Creating a new database using JDBC involves establishing a connection to the database
server and executing an SQL `CREATE DATABASE` statement within that connection. This
example provides a basic framework for creating databases programmatically using Java and
JDBC.
Adjust the specifics based on your database server and environment configuration.
xxxxxxxxxxxxxxxxxxxxxxxxx
SCROLLABLE RESULT SETS
In JDBC (Java Database Connectivity), a `Scrollable ResultSet` allows you to navigate
through the result set of a query in both forward and backward directions. This capability is
particularly useful when you need to move back and forth within the result set to retrieve data
efficiently without re-executing the query. Here‟s how you can work with scrollable result sets in
JDBC:

Enabling Scrollability in JDBC:


To create a scrollable result set in JDBC, you need to specify the type of scrolling and
sensitivity when creating the statement object. The types of scrollable result sets supported by
JDBC include:
1. TYPE_FORWARD_ONLY: Default type where you can only move forward through the result
set once.
2. TYPE_SCROLL_INSENSITIVE: Allows both forward and backward navigation through the
result set. Changes made to the data in the database are not visible in the result set.
3. TYPE_SCROLL_SENSITIVE: Similar to `TYPE_SCROLL_INSENSITIVE`, but changes made
to the data in the database are visible in the result set.

189
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

Example of Using Scrollable Result Sets:


Here‟s an example demonstrating how to create a scrollable result set in JDBC:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ScrollableResultSetExample {


public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {


if (conn != null) {
System.out.println("Connected to the database");

// Create a statement with scrollable result set


Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

String sql = "SELECT FROM Users";


ResultSet rs = stmt.executeQuery(sql);

// Move cursor to the last row


rs.last();

// Retrieve data from the last row


int userId = rs.getInt("user_id");
String username = rs.getString("username");
String email = rs.getString("email");

System.out.println("Last User ID: " + userId);


190
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

System.out.println("Last Username: " + username);


System.out.println("Last Email: " + email);

// Move cursor to the first row


rs.beforeFirst();

// Iterate through the result set


while (rs.next()) {
// Process each row
int id = rs.getInt("user_id");
String name = rs.getString("username");
String userEmail = rs.getString("email");

System.out.println("User ID: " + id + ", Username: " + name + ", Email: " +
userEmail);
}

// Close result set and statement


rs.close();
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
Explanation:
- Connection: Establishes a connection to the database using `DriverManager.getConnection()`.
- Statement: Creates a `Statement` object with `ResultSet.TYPE_SCROLL_INSENSITIVE` and
`ResultSet.CONCUR_READ_ONLY` to enable a scrollable and insensitive result set.
- ResultSet: Executes the query (`SELECT FROM Users`) and retrieves the result set. The cursor
is moved to the last row (`rs.last()`) to retrieve data from the last row. Then, it's moved back to the
first row (`rs.beforeFirst()`) to iterate through the result set.

191
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

- Iteration: Uses `rs.next()` to move through each row of the result set and retrieve data (`getInt()`,
`getString()`) from each column.
- Closing Resources: Ensures proper resource management by closing the result set and statement
objects in the `finally` block or using try-with-resources (`try (...) {...}`) in Java 7 and later.
- Performance Considerations: Scrollable result sets may have performance implications, especially
when dealing with large result sets. Use them judiciously based on your application's requirements.
- Database Support: Not all databases may support scrollable result sets with full functionality.
Always check the JDBC driver documentation and database compatibility.
- Concurrency: The `ResultSet.CONCUR_READ_ONLY` parameter ensures that the result set is
read-only, preventing accidental updates to the database.
- By using scrollable result sets in JDBC, you can efficiently navigate and process data retrieved
from database queries, enhancing the flexibility and usability of your Java database applications.
Adjust the scrolling type (`TYPE_SCROLL_SENSITIVE`, `TYPE_SCROLL_INSENSITIVE`)
based on your specific requirements and database capabilities.
xxxxxxxxxxxxxxxxxxx

UNIT V QUESTION BANK


ONE MARK QUESTIONS
1. Which class in Java is used to represent a URL connection and allows interaction with the
resource pointed to by the URL?
A) `URL` B) `URLConnection` C) `HttpURLConnection` D) `Socket`
Answer: B) `URLConnection`
2. Which protocol is commonly used with sockets for real-time data transmission over the
Internet?
A) SMTP B) HTTP C) TCP/IP D) UDP
Answer: C) TCP/IP
3. What does RMI stand for in Java?
A) Remote Method Invocation B) Real Method Interface
C) Remote Messaging Interface D) Remote Method Interface
Answer: A) Remote Method Invocation
4. Which component of a DBMS ensures data integrity by enforcing constraints and rules?
A) Query Optimizer B) Data Dictionary
C) Data Manipulation Language D) Data Integrity Manager
Answer: D) Data Integrity Manager

192
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

5. In a relational database table, a column represents:


A) A unique identifier for each row. B) A collection of related records.
C) A specific attribute or field. D) A set of joined tables.
Answer: C) A specific attribute or field.
6. What does the SQL `SELECT` statement do?
A) Deletes data from a database table. B) Updates existing rows in a database.
C) Inserts new rows into a database table. D) Retrieves data from one or more database tables.
Answer: D) Retrieves data from one or more database tables.
7. Which SQL statement is used to insert new rows into a database table?
A) `DELETE` B) `UPDATE` C) `INSERT` D) `SELECT`
Answer: C) `INSERT`
8. Which SQL statement is used to update existing rows in a database table?
A) `INSERT` B) `UPDATE` C) `DELETE` D) `SELECT`
Answer: B) `UPDATE`
9. Which SQL statement is used to delete a table from a database?
A) `REMOVE` B) `DROP` C) `DELETE` D) `DESTROY`
Answer: B) `DROP`
10. Which method is used to establish a connection to a database using JDBC?
A) `Driver.connect()` B) `DriverManager.getConnection()`
C) `Database.openConnection()` D) `Database.connect()`
Answer: B) `DriverManager.getConnection()`
11. Which type of `ResultSet` in JDBC allows both forward and backward navigation through the
result set?
A) `TYPE_FORWARD_ONLY` B) `TYPE_SCROLL_INSENSITIVE`
C) `TYPE_SCROLL_SENSITIVE` D) `TYPE_SCROLLABLE`
Answer: B) `TYPE_SCROLL_INSENSITIVE`

FIVE MARK AND TEN MARK QUESTIONS


1. Explain the process of working with URLs in Java network programming.
2. Describe the fundamental principles of socket programming in Java.
3. Discuss the architecture and key components involved in Remote Method Invocation (RMI) in
Java.
4. Define Database Management Systems (DBMS) and discuss their role in modern software
applications.
5. Explain the concepts of tables, rows, and columns in the context of a relational database.
193
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming

6. Provide a detailed explanation of the SQL `SELECT` statement.


7. Discuss the process of inserting new rows into a database table using SQL.
8. Describe the SQL operations for updating and deleting existing rows in a database table.
9. Explain the SQL commands for creating and deleting tables in a database
10. Discuss the process of creating a new database using JDBC (Java Database Connectivity).
xxxxxxxxxxxxxxxx UNIT V END xxxxxxxxxxxxxxxx

194
AVS College of Arts & Science (Autonomous)

You might also like