Advanced Java
Advanced Java
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
xxxxxxxxxxxxxxxx
3
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
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;
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);
}
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
// Default values
int defaultValue; // 0
double defaultDouble; // 0.0
boolean defaultBoolean; // false
// Type conversion
int intValue = 100;
long longValue = intValue; // Widening conversion (implicit)
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.
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:
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
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
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();
}
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;
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")
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
java
printNumbers(1, 2, 3); // Passing individual arguments
printNumbers(new int[]{4, 5, 6}); // Passing an array
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;
}
}
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.
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
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.
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:
// 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,
==, 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;
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
Example:
import java.io.;
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
Example:
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.
// 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.
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
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-
class operators {
public static void main(String[] args)
{
class Person {
}
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.
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
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
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.
35
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
Calculation.java
Calculation.java
}
}
}
Output:
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.
Calculation .java
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:
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.
Calculation.java
38
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
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
Calculation.java
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
}
}
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
}
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;
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.;
}
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();
Multiple Inheritance
51
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
interface One {
public void print_geek();
}
interface Two {
public void print_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:-
class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
53
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
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
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
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
```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);
68
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!";
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
```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
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.;
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:
```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
```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();
} 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
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
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();
baos.write(byteRead);
}
// 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
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.;
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();
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
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.
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;
// 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)
}
// 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
- 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;
Example Usage
```java
import java.applet.Applet;
import java.awt.Graphics;
@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
```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
@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
114
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
// Create a JLabel
115
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
// Create a JButton
JButton button = new JButton("Click Me!");
```java
116
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
import javax.swing.;
import java.awt.;
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.
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
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
public CounterModel() {
count = 0;
}
```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.;
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
- 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.
130
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);
}
});
frame.add(label, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
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
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 PersonBean() {
// Default constructor
}
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.
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.;
142
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
Class<?> personClass = Class.forName("com.example.Person");
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() {
}
// 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();
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:
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.;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
- `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
- 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
// Initialization method
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Servlet initialization...");
}
// 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
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
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;
import com.example.util.MyClass;
157
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
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");
160
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
161
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
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
```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");
```
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;
xxxxxxxxxxxxxxxx
168
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
try {
// Create a socket to connect to the server
Socket socket = new Socket(serverName, port);
}
}
```
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();
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);
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
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).
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.
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
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;
```
```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
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
185
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
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
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:
189
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
System.out.println("User ID: " + id + ", Username: " + name + ", Email: " +
userEmail);
}
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
192
AVS College of Arts & Science (Autonomous)
I - M.C.A. Advanced Java Programming
194
AVS College of Arts & Science (Autonomous)