[Go to site: main page, start]

0% found this document useful (0 votes)
14 views34 pages

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, detailing its structure, advantages, and specific implementations like ArrayList and LinkedList. It highlights key features such as reusability, speed, and ease of maintenance, along with the dynamic nature of ArrayLists and the linked structure of LinkedLists. Additionally, it covers file handling in Java, including the use of streams for input and output operations and basic file operations like creation, reading, and writing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views34 pages

Java Collections Framework Overview

The document provides an overview of the Java Collections Framework, detailing its structure, advantages, and specific implementations like ArrayList and LinkedList. It highlights key features such as reusability, speed, and ease of maintenance, along with the dynamic nature of ArrayLists and the linked structure of LinkedLists. Additionally, it covers file handling in Java, including the use of streams for input and output operations and basic file operations like creation, reading, and writing.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Notes

Collections in Java

The Collection in Java is a framework that provides architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on data such as searching, sorting, insertion, manipulation,
and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque)
and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
A Collection represents a single unit of objects, i.e., a group.

Advantages of the Java Collection Framework

The Java Collections Framework offers significant advantages that enhance development practices, code quality, and
application performance:

1. Reusability: The framework provides a comprehensive set of common classes and utility methods applicable across
various types of collections. This feature promotes code reusability, sparing developers the need to write duplicate
code for common operations.

2. Quality: Leveraging the Java Collections Framework elevates the quality of programs. The components within the
framework have been extensively tested and are widely used by a vast community of developers, ensuring reliability
and stability in your applications.

3. Speed: Developers often report an increase in development speed when using the Collections Framework. It allows
them to concentrate on the core business logic of their applications rather than on implementing generic collection
functionalities, thus speeding up the development process.

4. Maintenance: The open-source nature of the Java Collections Framework, coupled with readily available API
documentation, facilitates easier code maintenance. Code written using the framework can be easily understood and
taken over by other developers, ensuring continuity and ease of maintenance.

5. Reduces Effort to Design New APIs: An additional benefit is the reduced necessity for API designers and
implementers to create new collection mechanisms for each new API. They can instead rely on the standard
collection interfaces provided by the framework, streamlining the API development process and ensuring consistency
across Java applications.

Hierarchy of Collection Framework


Let's see the hierarchy of Collection framework. The [Link] package contains all the classes and interfaces for the Collection
framework.
Java ArrayList

ArrayList in Java is a dynamic array implementation that belongs to the Java Collections Framework. This is a big array that
grows on its own as more elements are added to it.
ArrayLists come from the [Link] package and are quite commonly used for their ease of use and flexibility. They offer
flexibility in that you do not need to determine the size of the ArrayList at the time of its creation, which is like standard arrays
in Java. So, it is much more flexible than the traditional array. The ArrayList in Java can also have duplicate elements. It
implements the List interface so that we can use all the methods of the List interface here. The ArrayList maintains the
insertion order internally.
It inherits the AbstractList class and implements List interface.

Soumick Adhikary 2
import [Link];
import [Link];
import [Link];
import [Link];

public class ArrayListExample {


public static void main(String[] args) {
List<Integer> AL = new LinkedList<Integer>();
int x = 1;
for(int i = 0; i < 5; i++) {
[Link](x);
x++;
}
[Link](AL);
Iterator it = [Link]();
while([Link]()) {
[Link]([Link]() + " ");
}

[Link](4, 6);
[Link](9);

for(int i: AL) {
[Link](i);
}

[Link](2);
for(int i = 0; i < [Link](); i++) {
[Link]([Link](i) + " ");
}
}
}

The important points about the Java ArrayList class are:

o Maintains Insertion Order: Java ArrayList guarantees the order in which elements are fed into it. When going through
the ArrayList with the iterating process, elements are accessed in the same sequence they were added.

o Non-Synchronized: Unlike some other Java collection classes (for instance, Vector), ArrayList is not synchronized.
This fact implies that ArrayList is not thread-safe; therefore, concurrent modification issues might arise if multiple
threads access ArrayList concurrently.

Soumick Adhikary 3
o Supports Random Access: ArrayList allows the implementation of fast random access operations using the
elements' index positions. This is because an array structure is used for internal implementation, which ensures
constant-time access to elements via index.

o Slower Manipulation compared to LinkedList: Manipulation operations, such as insertion and deletion, can be
slower in ArrayList than in LinkedList. Thus, ArrayList has to perform the shifting of the elements when items are
inserted or removed from anywhere except the end of the list. However, it is effortless to add or delete an element in a
LinkedList, and no shifting will be needed.

o Requires Wrapper Classes for Primitive Types: ArrayList does not have a direct support for primitive data types such
as `int`, `float`, and `char`. Instead, it requires the wrapper classes like `Integer`, `Float`, `Character`, etc., to
hold for these primitive types. For example:

ArrayList<Integer> integerList = new ArrayList<>();


[Link](10); // Here, 10 is automatically boxed into an Integer object

o Dynamic Resizing: ArrayList expands or contracts when adding or removing elements to meet the required new size.
Due to adaptive resizing, online collections can be managed without physical resizing.

o Capacity: ArrayList has an initial capacity, which is the number of elements it can keep without reallocation. If the
number of elements cannot fit into this capacity, the List automatically enlarges the size to accommodate the rest of
the elements. Copying all the elements to the new, larger array may be involved.

o Iterable: ArrayList implements the `Iterable` interface. Therefore, we can easily iterate the elements using enhanced
for loops or iterators.

o Dynamic Initialization: Java ArrayList is initialized without specifying its size. Unlike traditional arrays, where you
must declare a fixed size, ArrayList dynamically adjusts its size based on the number of elements added or removed.
This dynamic sizing eliminates the need to preallocate memory or worry about exceeding array bounds, providing
more flexibility in managing collections.

Java LinkedList Class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the
AbstractList class and implements List and Deque interfaces.

In Java, a LinkedList is a class that implements the List interface and represents a linked list data structure. Unlike arrays,
which store elements in contiguous memory locations, a linked list stores elements as nodes, where each node contains the
element itself and a reference (or pointer) to the next node in the sequence.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.

o Java LinkedList class maintains insertion order.

o Java LinkedList class is non synchronized.

o In Java LinkedList class, manipulation is fast because no shifting needs to occur.

o Java LinkedList class can be used as a list, stack or queue.

Soumick Adhikary 4
Hierarchy of LinkedList Class
The List interface extends the Collection interface and represents an ordered collection of elements. Lists allow duplicate
elements and provide methods to access elements by their integer index. The LinkedList class implements the List interface
and represents a doubly linked list data structure.

A LinkedList consists of a series of nodes, where each node contains a reference to the next node and the previous node in the
sequence. It allows for efficient insertion and deletion operations, as each node only needs to update its neighboring nodes'
references. However, accessing elements by index in a LinkedList is less efficient compared to an ArrayList, as it requires
traversing the list from the beginning or end to reach the desired element.

Soumick Adhikary 5
import [Link].*;
public class LinkedListExample{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
[Link]("Initial list of elements: "+ll);
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ajay");
[Link]("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
[Link](1, "Gaurav");
[Link]("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
[Link]("Sonoo");
[Link]("Hanumat");
//Adding second list elements to the first list
[Link](ll2);
[Link]("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
[Link]("John");
[Link]("Rahul");
//Adding second list elements to the first list at specific position
[Link](1, ll3);
[Link]("After invoking addAll(int index, Collection<? extends E> c) method: "+ll);
//Adding an element at the first position
[Link]("Lokesh");
[Link]("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
[Link]("Harsh");
[Link]("After invoking addLast(E e) method: "+ll);

}
}

Output:
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay, Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:

Soumick Adhikary 6
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]

Soumick Adhikary 7
import [Link].*;
public class WordsToNumber {
static ArrayList<String> units = new ArrayList<>([Link](
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
"seventeen", "eighteen", "nineteen" ));
static ArrayList<String> tens = new ArrayList<>([Link](
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"));
public static int convertWordsToNumber(String input) {
input = [Link]().trim();
String[] words = [Link]("\\s+");
int total = 0;
int current = 0;
for (String word : words) {
if ([Link](word)) {
current += [Link](word);
} else if ([Link](word)) {
current += [Link](word) * 10;
} else if ([Link]("hundred")) {
current *= 100;
} else if ([Link]("thousand")) {
current *= 1000;
total += current;
current = 0;
} else {
return -1; // Invalid word
}
}
return total + current;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter number in words (e.g., 'sixty seven'):");
String input = [Link]();
int result = convertWordsToNumber(input);

if (result == -1) {
[Link]("Invalid input!");
} else {
[Link]("Number: " + result);
}
[Link]();
}
}

Soumick Adhikary 8
File Handling in Java
In Java, with the help of File Class, we can work with files. This File Class is inside the [Link] package. The File class can be
used to create an object of the class and then specifying the name of the file.

Why File Handling is Required?

• File Handling is an integral part of any programming language as file handling enables us to store the output of any
particular program in a file and allows us to perform certain operations on it.

• In simple words, file handling means reading and writing data to a file.

What are Streams in java?


In Java, a sequence of data is known as a stream. This concept is used to perform I/O operations on a file. Below are the types
of Streams:

• Input Stream
• Output Stream

Input Stream: The Java InputStream class is the superclass of all input streams. The input stream is used to read data from
numerous input devices like the keyboard, network, etc. InputStream is an abstract class, and because of this, it is not useful
by itself. However, its subclasses are used to read data.

There are several subclasses of the InputStream class, which are as follows:

1. AudioInputStream

2. ByteArrayInputStream

3. FileInputStream

4. FilterInputStream

5. StringBufferInputStream

6. ObjectInputStream

Creating an InputStream:
// Creating an InputStream
InputStream obj = new FileInputStream();

Output Stream: The output stream is used to write data to numerous output devices like the monitor, file, etc. OutputStream
is an abstract superclass that represents an output stream. OutputStream is an abstract class and because of this, it is not
useful by itself. However, its subclasses are used to write data.

There are several subclasses of the OutputStream class which are as follows:

1. ByteArrayOutputStream

2. FileOutputStream

3. StringBufferOutputStream

4. ObjectOutputStream

5. DataOutputStream

6. PrintStream

Soumick Adhikary 9
Creating an OutputStream:

// Creating an OutputStream
OutputStream obj = new FileOutputStream();

Based on the data type, there are two types of streams:

1. Byte Stream

This stream is used to read or write byte data. The byte stream is again subdivided into two types which are as follows:

• Byte Input Stream: Used to read byte data from different devices.

• Byte Output Stream: Used to write byte data to different devices.

2. Character Stream

This stream is used to read or write character data. Character stream is again subdivided into 2 types which are as follows:

• Character Input Stream: Used to read character data from different devices.

• Character Output Stream: Used to write character data to different devices.

Java File class Methods:

Soumick Adhikary 10
File Operations:

The following are the several operations that can be performed on a file in Java:

• Create a File

• Read from a File

• Write to a File

• Delete a File

import [Link].*;
public class FileOperations {

public static void main(String[] args) {


String fileName = "D://[Link]";
// 1. Create a File
try {
File file = new File(fileName);
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred during file creation.");
[Link]();
}
// 2. Write to a File
try {
FileWriter writer = new FileWriter(fileName);
[Link]("Hello, this is a sample text written to the file.\n");
[Link]("Java makes file handling easy.");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred during writing to the file.");
[Link]();
}

Soumick Adhikary 11
// 3. Read from a File
try {
FileReader reader = new FileReader(fileName);
BufferedReader br = new BufferedReader(reader);
String line;
[Link]("\nContents of the file:");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (IOException e) {
[Link]("An error occurred during reading the file.");
[Link]();
}

// 4. Delete the File


File fileToDelete = new File(fileName);
if ([Link]()) {
[Link]("\nFile deleted: " + [Link]());
} else {
[Link]("\nFailed to delete the file.");
}
}
}

Java File class is a representation of a file or directory pathname. Because file and directory names have different formats on
different platforms, a simple string is not adequate to name them. Java File class contains several methods for working with
the pathname, deleting and renaming files, creating new directories, listing the contents of a directory, and determining
several common attributes of files and directories.

Features:

• It is an abstract representation of files and directory pathnames.

• A pathname, whether abstract or in string form can be either absolute or relative. The parent of an abstract pathname
may be obtained by invoking the getParent() method of this class.

• First of all, we should create the File class object by passing the filename or directory name to it. A file system may
implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing.
These restrictions are collectively known as access permissions.

• Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object
will never change.

Soumick Adhikary 12
import [Link];
//Program to check if a file or directory physically exists or not.
class CheckFileExist
{
public static void main(String[] args)
{

// Accept file name or directory name throughcommand line args


String fname = args[0];

// pass the filename or directory name to File object


File f = new File(fname);

// apply File class methods on File object


[Link]("File name :" + [Link]());
[Link]("Path: " + [Link]());
[Link]("Absolute path:" + [Link]());
[Link]("Parent:" + [Link]());
[Link]("Exists :" + [Link]());

if ([Link]()) {
[Link]("Is writable:" + [Link]());
[Link]("Is readable" + [Link]());
[Link]("Is a directory:" + [Link]());
[Link]("File Size in bytes " + [Link]());
}
}
}

Output:

Soumick Adhikary 13
JDBC (Java Database Connectivity)

JDBC is an API that helps applications to communicate with databases, it allows Java programs to connect to a database, run
queries, retrieve, and manipulate data. Because of JDBC, Java applications can easily work with different relational databases
like MySQL, Oracle, PostgreSQL, and more.

JDBC Architecture

Explanation:

• Application: It can be a Java application or servlet that communicates with a data source.

• The JDBC API: It allows Java programs to execute SQL queries and get results from the database. Some key
components of JDBC API include

o Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and Connection that helps managing different
database tasks.

o Classes like DriverManager, Types, Blob, and Clob that helps managing database connections.

• DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.

• JDBC drivers: These drivers handle interactions between the application and the database.

There are two types of JDBC architectures:

1. Two-Tier Architecture

A Java Application communicates directly with the database using a JDBC driver. It sends queries to the database and
then the result is sent back to the application. For example, in a client/server setup, the user’s system acts as a client that
communicates with a remote database server.

Structure:

Client Application (Java) -> JDBC Driver -> Database


Soumick Adhikary 14
2. Three-Tier Architecture

In this, user queries are sent to a middle-tier services, which interacts with the database. The database results are
processed by the middle tier and then sent back to the user.

Structure:

Client Application -> Application Server -> JDBC Driver -> Database

JDBC Components

There are generally 4 main components of JDBC through which it can interact with a database. They are as mentioned below:

1. JDBC API: It provides various methods and interfaces for easy communication with the database. It includes two key
packages

• [Link]: This package, is the part of Java Standard Edition (Java SE) , which contains the core interfaces and classes
for accessing and processing data in relational databases. It also provides essential functionalities like establishing
connections, executing queries, and handling result sets

• [Link]: This package is the part of Java Enterprise Edition (Java EE) , which extends the capabilities of [Link] by
offering additional features like connection pooling, statement pooling, and data source management.

It also provides a standard to connect a database to a client application.

2. JDBC Driver Manager: Driver manager is responsible for loading the correct database-specific driver to establish a
connection with the database. It manages the available drivers and ensures the right one is used to process user requests and
interact with the database.

3. JDBC Test Suite: It is used to test the operation (such as insertion, deletion, updating) being performed by JDBC Drivers.

4. JDBC Drivers: JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand

Classes and Interfaces in JDBC:

Soumick Adhikary 15
Steps to Connect to MySQL Database Using JDBC:

Step 1: Load the JDBC Driver

[Link](“[Link]”);

Step 2: Establish a Connection

Connection connection = [Link](

“jdbc:mysql://localhost:3306/your_database”,

“your_username”,

“your_password”

);

Step 3: Create a Statement

Statement statement = [Link]();

Step 4: Execute a Query

String query = “INSERT INTO students (id, name) VALUES (101, ‘John Doe’)”;

int rowsAffected = [Link](query);

[Link](“Rows affected: ” + rowsAffected);

Step 5: Close the Connection

[Link]();

[Link]();

Soumick Adhikary 16
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class JDBC_Connect {

public static void main(String[] args) {


// TODO Auto-generated method stub
String url="jdbc:mysql://localhost:3306/demodb";
String user="root";
String password="";
try {
[Link]("[Link]");
Connection con = [Link](url,user,password);
Statement st = [Link]();

//Inserting data to Database Table


String sql = "Insert into demotable(id, Name, PhoneNumber, Address) values
(2,'Swadesh','7895632010','Midnapur');";
[Link](sql);

//Displaying data from Database Table


String sql1 = "Select * from demotable";
ResultSet rs = [Link](sql1);
[Link]("ID \t Name \t Phone_No \t Address");
while([Link]()) {

[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3)+"\t"+[Link](4));
}
[Link]();
}
catch(Exception ex) {
[Link]();
}

Soumick Adhikary 17
Threads in Java

Threads in Java enable concurrent execution within a program. They are lightweight processes that allow multiple tasks to run
seemingly simultaneously, improving application performance, especially in multi-core systems. Every Java application starts
with a main thread, and developers can create additional threads to perform parallel tasks.

Multitasking

To help users, the operating system provides users with the privilege of multitasking, where users can perform multiple actions
simultaneously on the machine. This Multitasking can be enabled in two ways:

1. Process-Based Multitasking

2. Thread-Based Multitasking

1. Process-Based Multitasking (Multiprocessing): In this type of multitasking, processes are heavyweight, and each process
is allocated by a separate memory area and as the process is heavyweight the cost of communication between processes is
high and it takes a long time for switching between processes as it involves actions such as loading, saving in registers,
updating maps, lists, etc.

2. Thread-Based Multitasking: As we discussed above, threads are provided with lightweight nature and share the same
address space, and the cost of communication between threads is also low.

Life Cycle of Thread

During its lifetime, a thread transitions through several states, they are:

1. New State

2. Active State

3. Waiting/Blocked State

4. Timed Waiting State

5. Terminated State

Soumick Adhikary 18
1. New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run when the thread
is in this state. When a thread lies in the new state, its code is yet to be run and has not started to execute.

2. Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might actually be
running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to give the
thread, time to run. A multi-threaded program allocates a fixed amount of time to each individual thread. Each and
every thread get a small amount of time to run. After running for a while, a thread pauses and gives up the CPU so that
other threads can run.

3. Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is acquired by the
other thread. The thread will move from the blocked state to runnable state when it acquires the lock.

4. Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will move to the
runnable state when other thread will notify or that thread will be terminated.

5. Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A thread lies in
this state until the timeout is completed or until a notification is received. For example, when a thread calls sleep or a
conditional wait, it is moved to a timed waiting state.

6. Terminated State: A thread terminates because of either of the following reasons:

• Because it exits normally. This happens when the code of the thread has been entirely executed by the
program.

• Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled exception.

How to Create Threads in Java?

We can create threads in java using two ways, namely :

• Extending Thread Class

• Implementing a Runnable interface

Running Threads in Java

There are two methods used for running Threads in Java:

• run() Method in Java

• start() Method in Java

Thread States in Java

In Java, to get the current state of the thread, use [Link]() method to get the current state of the thread. Java
provides [Link] enum that defines the ENUM constants for the state of a thread, as a summary of which is
given below:

Soumick Adhikary 19
1. New

Thread state for a thread that has not yet started.

public static final [Link] NEW

2. Runnable

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting
for other resources from the operating system such as a processor.

public static final [Link] RUNNABLE

3. Blocked

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter
a synchronized block/method or reenter a synchronized block/method after calling [Link]().

public static final [Link] BLOCKED

4. Waiting

Thread state for a waiting thread. A thread is in the waiting state due to calling one of the following methods:

• [Link] with no timeout

• [Link] with no timeout

• [Link]

public static final [Link] WAITING

5. Timed Waiting

Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of the
following methods with a specified positive waiting time:

• [Link]

• [Link] with timeout

• [Link] with timeout

• [Link]

• [Link]

public static final [Link] TIMED_WAITING

6. Terminated

Thread state for a terminated thread. The thread has completed execution.

public static final [Link] TERMINATED

Soumick Adhikary 20
class MyThread extends Thread {

private String threadName;

MyThread(String name) {
threadName = name;
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](threadName + " - Count: " + i);
try {

[Link](1000);
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
[Link](threadName + " finished.");
}
}

public class MultiThreadingExample {


public static void main(String[] args) {

MyThread thread1 = new MyThread("Thread 1");


MyThread thread2 = new MyThread("Thread 2");
MyThread thread3 = new MyThread("Thread 3");

[Link]();
[Link]();
[Link]();

try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("All threads have finished.");
}
}

Soumick Adhikary 21
Output:

Soumick Adhikary 22
public class TimeCount implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 1; i <= 5; i++) {
try {
[Link](1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
[Link]("Thread Stopped");
}
if(i == 5) {
[Link]("Time's Up");
//[Link](0);
}
}
}
}

import [Link];
public class ThreadDemo {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
TimeCount TC = new TimeCount();
Thread th = new Thread(TC);
[Link](true);
[Link]();

[Link]("Enter Name in 5 Seconds");


String nm = [Link]();
[Link]("Hello " + nm);
}
}

Output:

Soumick Adhikary 23
Java Applet

An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the
entire Java API at its disposal.

Differences between an applet and a standalone Java application

• An applet is a Java class that extends the [Link] class.

• A main() method is not invoked on an applet, and an applet class will not define main().

• Applets are designed to be embedded within an HTML page.

• When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's
machine.

• A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate runtime
environment.

Life Cycle of an Applet in Java

Four methods in the Applet class gives you the framework on which you build any serious applet −

• init − This method is intended for whatever initialization is needed for your applet. It is called after the param tags
inside the applet tag have been processed.

• start − This method is automatically called after the browser calls the init method. It is also called whenever the user
returns to the page containing the applet after having gone off to other pages.

• stop − This method is automatically called when the user moves off the page on which the applet sits. It can,
therefore, be called repeatedly in the same applet.

• destroy − This method is only called when the browser shuts down normally. Because applets are meant to live on an
HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.

• paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the
browser. The paint() method is actually inherited from the [Link].

These import statements bring the classes into the scope of our applet class −

• [Link]

• [Link]

There are two standard ways in which you can run an applet:

1. Executing the applet within a Java-compatible web browser.

2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes your applet in a window.
This is generally the fastest and easiest way to test your applet.

Each of these methods is described next.

1. Using java enabled web browser

• To execute an applet in a web browser we have to write a short HTML text file that contains a tag that loads the applet.

Soumick Adhikary 24
• We can use APPLET or OBJECT tag for this purpose

• Using APPLET, here is the HTML file that executes HelloWorld

<applet code=”HelloWorld” width=200 height=60>

</applet>

The width and height statements specify the dimensions of the display area used by the applet. The APPLET tag contains
several other options. After you create this html file, you can use it to execute the applet.

Note: Chrome and Firefox no longer supports NPAPI (technology required for Java applets).

2. Using appletviewer

• This is the easiest way to run an applet.

• To execute HelloWorld with an applet viewer, you may also execute the HTML file shown earlier.

• For example, if the preceding HTML file is saved with [Link], then the following command line will run
HelloWorld.

appletviewer [Link]

Sample Example:

[Link]
import [Link];

import [Link].*;

class first extends Applet{

public void paint(Graphics g){

[Link]("First Applet Program", 100, 100);

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<applet code="[Link]" height="400" width="400"></applet>
</body>
</html>

Soumick Adhikary 25
Features of Applets over HTML

• Displaying dynamic web pages of a web application.

• Playing sound files.

• Displaying documents

• Playing animations

Restrictions imposed on Java applets

Due to security reasons, the following restrictions are imposed on Java applets:

• An applet cannot load libraries or define native methods.

• An applet cannot ordinarily read or write files on the execution host.

• An applet cannot read certain system properties.

• An applet cannot make network connections except to the host that it came from.

• An applet cannot start any program on the host that’s executing it.

Note: [Link] package has been deprecated in Java 9 and later versions, as applets are no longer widely used on the web.

Event Handling and AWT:

What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as
result of user interaction with the graphical user interface components. For example, clicking on a button.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism
have the code which is known as event handler that is executed when an event occurs.

Event ha following key participants namely:

• Source - The source is an object on which event occurs. Source is responsible for providing information of the
occurred event to it's handler. Java provide as with classes for source object.

• Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java
implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is
received , the listener process the event an then returns.

Flow of Event Handling

The event handling process in Java follows these steps:

1. User Interaction with a component is required to generate an event.

Soumick Adhikary 26
2. The object of the respective event class is created automatically after event generation, and it holds all information of
the event source.

3. The newly created object is passed to the methods of the registered listener.

4. The method executes and returns the result.

Java AWT

The Java Abstract Window Toolkit (AWT) is a GUI framework that provides a set of classes and methods for creating and
managing user interfaces in Java applications. One of the most important components in AWT is the ActionListener interface.
It is a key element for adding interactivity in Java applications by handling user actions.

The ActionListener interface is a part of the '[Link]' package. When you click on a button, menu item, or a check box,
the Java ActionListener is called. It is notified in reference to an ActionEvent. It only has one method, actionPerformed(). The
principle of an ActionListener is to record and respond to user interactions with GUI components.

Java Swing

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers
much-improved functionality over AWT, new components, expanded components features, and excellent event handling with
drag-and-drop support.

Difference between AWT and Swing

Soumick Adhikary 27
Features Of Swing Class

• Pluggable look and feel.

• Uses MVC architecture.

• Lightweight Components

• Platform Independent

• Advanced features such as JTable, JTabbedPane, JScollPane, etc.

Common methods used in Swing:

• add(Component c): Adds a component to another component, like adding a button to a panel.

• setLayout(LayoutManager m): Determines how components are arranged within a container.

• setVisible(boolean b): Controls the visibility of a component.

• setText(String text): Sets the text displayed by a component like a label or button.

• getText(): Retrieves the text from a component like a text field.

• setFont(Font font): Sets the font of the text displayed by a component.

• setForeground(Color color): Sets the text color of a component.

• setBackground(Color color): Sets the background color of a component.

• addActionListener(ActionListener l): Adds an ActionListener to the component, which is notified when an action
occurs (e.g., button click).

• setBounds(x,y,w,h): x: The horizontal position of the component's top-left corner, relative to its parent container. y: The
vertical position of the component's top-left corner, relative to its parent container. w: The width of the component.
h: The height of the component.

Program Example.

Java program to build a simple calculator using AWT and Swing

Soumick Adhikary 28
import [Link].*;
//import [Link];

import [Link].*;
import [Link].*;

class Calculator extends JFrame{


JLabel l1,l2;
JTextField t1,t2;
JButton b1,b2,b3,b4;
Calculator(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
l1 = new JLabel("Simple Calculator");
[Link](60,10,300,30);
[Link](new Font("Times New Roman",[Link],30));
add(l1);
t1 = new JTextField(60);
t2 = new JTextField(60);
b1 = new JButton("Add");
b2 = new JButton("Sub");
b3 = new JButton("Mult");
b4 = new JButton("Div");

[Link](100,60,120,30);
[Link](100,100,120,30);

[Link](100,140,60,30);
[Link](160,140,60,30);
[Link](100,180,60,30);
[Link](160,180,60,30);

l2 = new JLabel("Answer");
[Link](250,100,100,30);

add(l2);
add(b1);
add(b2);
add(b3);
add(b4);
add(t1);
add(t2);

Soumick Adhikary 29
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
[Link]("Sum = " + (n1+n2));
}
});
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
[Link]("Subtract = " + (n1-n2));
}
});
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
[Link]("Multiply = " + (n1*n2));
}
});
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
[Link]("Division= " + (n1/n2));
}
});
}
}
public class SimpleCalculator {

public static void main(String[] args) {


Calculator c = new Calculator();
[Link](400,200,400,300);
[Link](true);
}
}

Soumick Adhikary 30
final finalize() and finally

In Java, final, finalize(), and finally are three completely different concepts with different purposes. Here's a clear breakdown of
the differences:

1. final (Keyword)

• Type: Modifier (used with variables, methods, and classes)

• Purpose: To declare constants, prevent method overriding, or class inheritance.

• Examples:

o final int x = 10; → x cannot be changed.

o final void show() {} → Method can't be overridden.

o final class MyClass {} → Class can’t be subclassed.

2. finally (Block)

• Type: Part of exception handling (try-catch-finally)

• Purpose: To execute cleanup code regardless of whether an exception occurs.

• Behavior: Runs after try and/or catch, even if there is a return or an exception.

Example:

try {
// risky code
} catch (Exception e) {
// handle exception
} finally {
// cleanup code (always runs)
}

3. finalize() (Method)

• Type: Method in [Link]

• Purpose: Called by the garbage collector before an object is destroyed (deprecated in Java 9+).

• Usage: Meant for cleanup before object deletion, like closing resources (not reliable).

Example:

protected void finalize() throws Throwable {

[Link]("Object is being garbage collected");

Soumick Adhikary 31
public class FinalExample {

// final variable (cannot be changed once assigned)


final int value = 100;

// final method (cannot be overridden)


public final void displayFinal() {
[Link]("This is a final method.");
}

// finalize method (called before garbage collection, not reliable)


@Override
protected void finalize() throws Throwable {
[Link]("finalize() method called.");
[Link]();
}

public static void main(String[] args) {


FinalExample obj = new FinalExample();

// Demonstrating final variable


[Link]("Final variable value: " + [Link]);

// Demonstrating final method


[Link]();

// Demonstrating finally block


try {
[Link]("Inside try block.");
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("finally block executed.");
}

// Hinting the JVM to run garbage collector


obj = null;
[Link](); // finalize() might be called here
}
}

Note: The call to finalize() is not guaranteed to execute immediately (or at all) since it's managed by the garbage
collector, which runs on its own schedule.

Soumick Adhikary 32
Abstract class in Java

In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-abstract methods(methods
with bodies). An abstract is a Java modifier applicable for classes and methods in Java but not for Variables.

What is Abstract Class in Java?

Java abstract class is a class that can not be instantiated by itself, it needs to be subclassed by another class to use its
properties. An abstract class is declared using the “abstract” keyword in its class definition.

Illustration of Abstract class:


abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}

Some important features about abstract classes are as follows:

1. An instance of an abstract class can not be created.

2. Constructors are allowed.

3. We can have an abstract class without any abstract method.

4. There can be a final method in abstract class but any abstract method in class(abstract class) can not be declared as
final or in simpler terms final method can not be abstract itself as it will yield an error: “Illegal combination of
modifiers: abstract and final”

5. We can define static methods in an abstract class

6. We can use the abstract keyword for declaring top-level classes (Outer class) as well as inner classes as abstract

7. If a class contains at least one abstract method then compulsory should declare a class as abstract

8. If the Child class is unable to provide implementation to all abstract methods of the Parent class then we should
declare that Child class as abstract so that the next level Child class should provide implementation to the
remaining abstract method

Soumick Adhikary 33
abstract class Shape{
public abstract double calculateArea();

public void display() {


[Link]("The area is : " + calculateArea());
}
}

class Circle1 extends Shape{


int r;
public Circle1(int r) {
this.r = r;
}
@Override
public double calculateArea() {
return 3.14 * [Link](r, 2);
}
}

class Triangle extends Shape{


int h, b;
public Triangle(int h,int b){
this.h = h;
this.b = b;
}
@Override
public double calculateArea() {
return 0.5 * b * h;
}

}
public class codeRunner {

public static void main(String[] args) {


Shape shapes[]= {new Circle1(9), new Triangle(5,13)};

for(Shape s:shapes) {
[Link]();
}
}

Soumick Adhikary 34

You might also like