KEMBAR78
Java Lab Manual It | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
3 views69 pages

Java Lab Manual It

The document is a lab manual for the Java Programming Lab (IT492PC) at Nawab Shah Alam Khan College of Engineering and Technology, prepared by Ms. Tahera Abid. It includes a list of 17 programming tasks covering various Java concepts such as OOP, exception handling, threading, and JDBC. Each task is accompanied by source code examples and explanations to aid students in understanding Java programming.

Uploaded by

tahuraabid1331
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)
3 views69 pages

Java Lab Manual It

The document is a lab manual for the Java Programming Lab (IT492PC) at Nawab Shah Alam Khan College of Engineering and Technology, prepared by Ms. Tahera Abid. It includes a list of 17 programming tasks covering various Java concepts such as OOP, exception handling, threading, and JDBC. Each task is accompanied by source code examples and explanations to aid students in understanding Java programming.

Uploaded by

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

NAWABSHAH ALAM KHAN COLLEGE OF ENGINEERING

AND TECHNOLOGY

LAB NAME: JAVA PROGRAMMING LAB MANUAL


LAB CODE : IT492PC
YEAR/ BRANCH: II B.E IV SEM
BRANCH: IT
SECTION: (A &B)

PREPARED BY:
Ms. TAHERA ABID
ASSISTANT PROFESSOR
IT DEPT

pg. 1
Course Title: OOPs using JAVA Lab Manual
Course Code: IT492PC
Department: Information Technology
Prepared By : Ms Tahera Abid

PAGE
S.NO LIST OF PROGRAMS
NO
1 Write a Java program to illustrate the concept of class with method overloading.
2 Write a Java Program that reads a line of integers, and then displays each integer, and the sum
of all the integers
3 Write a Java program to illustrate the concept of Single level and Multi level Inheritance

4 Write a Java program to demonstrate the Interfaces & Abstract Classes

5 Write a program to explain the concept of String class, String Builder class and String Buffer
class.
6 Write a Java program to implement the concept of exception handling.

7 Write a Java program to illustrate the concept of threading using Thread Class and runnable
Interface.

8 Write a Java program to illustrate the concept of Thread synchronization.

9 Write a Java program to illustrate collection classes like Array List, LinkedList, Tree map and
Hash map.

10 Write a Java program to illustrate Legacy classes like Vector, Hash table

11 Write a Java program that reads a file name from the user, and then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file
and the length of the file in bytes.
12 Write a Java program to illustrate the concept of I/O Streams

13 Write a Java program to implement Serialization and Deserialization concept

14 Write a Java applet program for handling mouse & key events
15 Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for
the digits and for the +,-, *, % operations. Add a text field to display the result

16 Write an example for JDBC prepared statement with Result Set

17 Program to create a simple JList and JCheckBox

pg. 2
Course Title: OOPs using JAVA Lab Course Code: IT492PC
1. Write a Java program to illustrate the concept of class with method overloading.
2. Write a Java Program that reads a line of integers, and then displays each integer, and
the sum of all the integers (Use String Tokenizer class of java.util)
3. Write a Java program to illustrate the concept of Single level and Multi level
Inheritance.
4. Write a Java program to demonstrate the Interfaces & Abstract Classes.
5. Write a program to explain the concept of String class, String Builder class and String
Buffer class.
6. Write a Java program to implement the concept of exception handling.
7. Write a Java program to illustrate the concept of threading using Thread Class and
runnable Interface.
8.Write a Java program to illustrate the concept of Thread synchronization.
9. Write a Java program to illustrate collection classes like Array List, LinkedList, Tree
map and Hash map.

10.Write a Java program to illustrate Legacy classes like Vector, Hash table

11. Write a Java program that reads a file name from the user, and then displays
information about whether the file exists, whether the file is readable, whether the file is
writable, the type of file and the length of the file in bytes.

12. Write a Java program to illustrate the concept of I/O Streams

13. Write a Java program to implement Serialization and Deserialization concept.

14. Write a Java applet program for handling mouse & key events

15. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +,-, *, % operations. Add a text field to display the result.

16. Write an example for JDBC prepared statement with Result Set

17. Program to create a simple JList and JCheckBox

pg. 3
PROGRAM 1

Write a Java program to illustrate the concept of class with method overloading

SOURCE CODE

// Class to demonstrate method overloading


public class Calculator {

// Method to add two integers

public int add(int a, int b) {


return a + b;
}

// Overloaded method to add three integers

public int add(int a, int b, int c) {


return a + b + c;
}

// Overloaded method to add two doubles

public double add(double a, double b) {


return a + b;
}

public static void main (String[] args) {


// Creating an object of Calculator class

Calculator calc = new Calculator();

// Calling the add method with two integers

System.out.println("Sum of 5 and 10: " + calc.add(5, 10));

// Calling the add method with three integers

System.out.println("Sum of 5, 10, and 15: " + calc.add(5, 10, 15));

// Calling the add method with two doubles

System.out.println("Sum of 5.5 and 10.5: " + calc.add(5.5, 10.5));

pg. 4
}
}

Explanation:
We have a Calculator class with three add methods.
 The first method adds two integers.
 The second method adds three integers.
 The third method adds two double values.

Method overloading is achieved because all the methods have the same name (add), but they differ in
the number or type of parameters.

OUTPUT:
Sum of 5 and 10: 15
Sum of 5, 10, and 15: 30
Sum of 5.5 and 10.5: 16.0

pg. 5
PROGRAM 2
Write a Java Program that reads a line of integers, and then displays each integer, and
the sum of all the integers (Use String Tokenizer class of java.util)
SOURCE CODE
import java.util.Scanner;
import java.util.StringTokenizer;

public class SumIntegers {


public static void main(String[] args) {
// Create a scanner to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a line of integers
System.out.print("Enter a line of integers separated by spaces: ");
String input = scanner.nextLine();
// Create a StringTokenizer to split the input string by spaces
StringTokenizer tokenizer = new StringTokenizer(input);

int sum = 0;

// Display each integer and add it to the sum


System.out.println("The integers are:");
while (tokenizer.hasMoreTokens()) {
// Get the next token (integer in string form) and parse it to an integer
int num = Integer.parseInt(tokenizer.nextToken());

// Display the integer


System.out.println(num);

// Add the integer to the sum


sum += num;
}

pg. 6
// Display the sum of all integers
System.out.println("The sum of all integers is: " + sum);
// Close the scanner to prevent resource leak
scanner.close();
}
}
Explanation:
1. Input: The program prompts the user to enter a line of integers separated by spaces.
2. StringTokenizer: The StringTokenizer is used to break the input string into individual tokens
based on whitespace.
3. Processing: Each token (which is a number in string format) is parsed to an integer, printed, and
then added to the sum.
4. Output: Each integer is displayed, followed by the total sum of all integers.

OUTPUT:
Enter a line of integers separated by spaces: 1 2 3 4 5 6 7 8 9 10
The integers are:
1
2
3
4
5
6
7
8
9
10
The sum of all integers is: 55

pg. 7
PROGRAM 3
Write a Java program to illustrate the concept of Single level and Multi level
Inheritance.
SOURCE CODE
// Single-level Inheritance
class College { // Superclass
public void collegeName() {
System.out.println("Welcome to Nawab Shah Alam Khan College of Engineering and
Technology!");
}
public void collegeAddress() {
System.out.println("Located in the heart of the city, XYZ Road, City.");
}
}

class Department extends College { // Subclass of College (Single-level inheritance)


public void departmentName() {
System.out.println("Department of Information Technology.");
}
}
// Multi-level Inheritance
class Department1 extends College { // Superclass
public void departmentName() {
System.out.println("Department of Information Technology.");
}
}
class Student extends Department1 { // Subclass of Department1 (Multi-level inheritance)
public void studentDetails() {
System.out.println("Student Name: Ali Khan");
System.out.println("Student ID: IT12345");
System.out.println("Student Enrollment Year: 2024");

pg. 8
}
}

public class CollegeExample {


public static void main(String[] args) {
// Demonstrating Single-Level Inheritance
System.out.println("Single Level Inheritance:");
Department dept = new Department();
dept.collegeName(); // Inherited from College
dept.collegeAddress(); // Inherited from College
dept.departmentName(); // Defined in Department

// Demonstrating Multi-Level Inheritance


System.out.println("\nMulti-Level Inheritance:");
Student student = new Student();
student.collegeName(); // Inherited from College (via Department1)
student.collegeAddress(); // Inherited from College (via Department1)
student.departmentName(); // Inherited from Department1
student.studentDetails(); // Defined in Student
}
}
Explanation:
 Single-level inheritance: The College class will represent the college (Nawab Shah Alam
Khan College of Engineering and Technology), and the Department class will represent the
Information Technology department, inheriting from the College class.
 Multi-level inheritance: We will add a Student class, which will inherit from the Department
class to represent a student in the Information Technology department.
1. Single-level Inheritance:
 College: This is the superclass, which contains basic information about the college,
such as the collegeName() and collegeAddress() methods.
 Department: This is a subclass of College and represents the Information Technology
department. It inherits the methods collegeName() and collegeAddress() from the

pg. 9
College class, and adds its own method departmentName() to specify the department
name.
 We create an object of Department, which allows us to access the methods from both
the College class and the Department class.
2. Multi-level Inheritance:
 Department1: This class extends the College class, so it inherits the methods
collegeName() and collegeAddress(). It represents the Information Technology
department and adds the departmentName() method.
 Student: This class extends Department1 and inherits the methods from both
Department1 and College. It adds its own method studentDetails() to display details
about a student.
 When we create an object of Student, it can access the inherited methods from both
Department1 and College and its own method studentDetails().

OUTPUT:

Single Level Inheritance:


Welcome to Nawab Shah Alam Khan College of Engineering and Technology!
Located in the heart of the city, XYZ Road, City.
Department of Information Technology.

Multi-Level Inheritance:
Welcome to Nawab Shah Alam Khan College of Engineering and Technology!
Located in the heart of the city, XYZ Road, City.
Department of Information Technology.
Student Name: Ali Khan
Student ID: IT12345
Student Enrollment Year: 2024

pg. 10
PROGRAM 4
Write a Java program to demonstrate the Interfaces & Abstract Classes.
SOURCE CODE
// Interface: College - Common behaviors for any College
interface College {
String collegeName(); // Method to return the college name
int collegeRank(); // Method to return the college rank
}
// Abstract Class: Department - Common properties and behavior for all departments
abstract class Department {
String departmentName;
String headOfDepartment;
// Constructor to initialize department name and head of department
public Department(String departmentName, String headOfDepartment) {
this.departmentName = departmentName;
this.headOfDepartment = headOfDepartment;
}
// Concrete method: Display department information
public void departmentInfo() {
System.out.println("Department: " + departmentName);
System.out.println("Head of Department: " + headOfDepartment);
}
// Abstract method: Each department will define its own function
public abstract void departmentFunction();
}
// Concrete Class: Nawab Shah Alam Khan College of Engineering and Technology implementing College interface
class NawabShahAlamKhanCollege implements College {
String collegeName;
int collegeRank;
// Constructor for the college
public NawabShahAlamKhanCollege(String collegeName, int collegeRank) {
this.collegeName = collegeName;
this.collegeRank = collegeRank;
}

pg. 11
// Implementing methods from College interface
@Override
public String collegeName() {
return collegeName;
}
@Override
public int collegeRank() {
return collegeRank;
}
// Function to describe the college
public void collegeFunction() {
System.out.println(collegeName + " offers a wide range of undergraduate and postgraduate courses
in various engineering fields.");
}
}
// Concrete Class: CSE (Computer Science and Engineering) Department
class CSE extends Department {
// Constructor for CSE department
public CSE(String headOfDepartment) {
super("Computer Science and Engineering", headOfDepartment);
}
// Implementing departmentFunction for CSE
@Override
public void departmentFunction() {
System.out.println("The CSE department offers courses in programming, data structures, artificial
intelligence, and machine learning.");
}
}
// Concrete Class: IT (Information Technology) Department
class IT extends Department {
// Constructor for IT department
public IT(String headOfDepartment) {
super("Information Technology", headOfDepartment);
}

pg. 12
// Implementing departmentFunction for IT
@Override
public void departmentFunction() {
System.out.println("The IT department offers courses in networking, databases, cybersecurity, and
cloud computing.");
}
}
// Main Class: Nawab Shah Alam Khan College of Engineering and Technology
public class NawabShahAlamKhanCollegeDemo {
public static void main(String[] args) {
// Creating an instance of Nawab Shah Alam Khan College
NawabShahAlamKhanCollege college = new NawabShahAlamKhanCollege("Nawab Shah Alam
Khan College of Engineering and Technology", 8);
// Creating department objects
CSE cseDept = new CSE("M.A.RAWOOF");
IT itDept = new IT("Dr G.S.S.RAO");
// Displaying college information
System.out.println("College Information:");
System.out.println("College Name: " + college.collegeName());
System.out.println("College Rank: " + college.collegeRank());
college.collegeFunction();
System.out.println("\nDepartment Information:");
// Displaying information about CSE Department
cseDept.departmentInfo();
cseDept.departmentFunction();
// Displaying information about IT Department
itDept.departmentInfo();
itDept.departmentFunction();
}
}

pg. 13
Key Elements:
1. Interface: College
o The interface defines two methods:
 collegeName(): Returns the name of the college.
 collegeRank(): Returns the rank of the college.
2. Abstract Class: Department
o The abstract class represents a department and contains:
 Two fields: departmentName and headOfDepartment.
 A constructor to initialize these fields.
 A concrete method departmentInfo(), which prints out department and head
information.
 An abstract method departmentFunction(), which is meant to be implemented by
each department class to describe the functions and courses specific to that
department.
3. Concrete Class: NawabShahAlamKhanCollege
o This class implements the College interface and provides concrete implementations for
the collegeName() and collegeRank() methods.
o It also includes a method collegeFunction() to provide a description of what the college
offers.
4. Concrete Classes: CSE and IT
o These classes extend the abstract Department class and implement the
departmentFunction() method to describe the specific functions and courses offered by
the Computer Science and Engineering (CSE) and Information Technology (IT)
departments.
5. Main Class: NawabShahAlamKhanCollegeDemo
o The main() method creates instances of NawabShahAlamKhanCollege, CSE, and IT.
o It displays information about the college and both departments, showcasing how
abstract classes and interfaces can be used together to model real-world systems.

Explanation of Key Concepts:


 Interface (College):
o The interface defines common behaviors for colleges, such as getting the college name
and rank. The NawabShahAlamKhanCollege class implements these methods to
provide the actual functionality.
 Abstract Class (Department):
o The abstract class allows for shared properties (like departmentName and
headOfDepartment) and behavior (like departmentInfo()). Each department must
implement its own specific functionality using the departmentFunction() method.
 Concrete Classes (CSE and IT):
o These classes implement the abstract method departmentFunction() to describe what
each department specifically offers (e.g., courses).

pg. 14
OUTPUT

College Information:
College Name: Nawab Shah Alam Khan College of Engineering and Technology
College Rank: 8
Nawab Shah Alam Khan College of Engineering and Technology offers a wide range of
undergraduate and postgraduate courses in various engineering fields.

Department Information:
Department: Computer Science and Engineering
Head of Department: M.A.RAWOOF
The CSE department offers courses in programming, data structures, artificial intelligence,
and machine learning.

Department: Information Technology


Head of Department: Dr G.S.S.RAO
The IT department offers courses in networking, databases, cybersecurity, and cloud
computing.

pg. 15
PROGRAM 5
Write a program to explain the concept of String class, String Builder class and String
Buffer class.
SOURCE CODE

public class StringExample {


public static void main(String[] args) {
// Demonstrating String class (Immutable)
String str1 = "Hello";
String str2 = "World";
// Concatenation creates a new String object
String str3 = str1 + " " + str2; // str3 = "Hello World"
System.out.println("Using String class:");
System.out.println("str1: " + str1);
System.out.println("str2: " + str2);
System.out.println("str3 (concatenated): " + str3);
// Modifying str1 won't change it as String is immutable
str1 = str1.concat(" Java");
System.out.println("str1 after modification: " + str1);
// Demonstrating StringBuilder class (Mutable, not synchronized)
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");

sb.append(" from StringBuilder");


System.out.println("\nUsing StringBuilder class:");
System.out.println("sb: " + sb.toString());
// Modifying StringBuilder is fast, no new object created
sb.insert(6, "Beautiful ");
System.out.println("sb after insert: " + sb.toString());
// Demonstrating StringBuffer class (Mutable, synchronized)
StringBuffer sbf = new StringBuffer("Hello");

pg. 16
sbf.append(" World");
sbf.append(" from StringBuffer");
System.out.println("\nUsing StringBuffer class:");
System.out.println("sbf: " + sbf.toString());
// StringBuffer also allows modification without creating new objects
sbf.reverse();
System.out.println("sbf after reverse: " + sbf.toString());
}
}

Concepts:
1. String Class:
o Immutable: Once a String object is created, its value cannot be changed.
o Concatenation of strings creates a new object.
2. StringBuilder Class:
o Mutable: StringBuilder objects can be modified without creating new objects.
o Designed for performance when performing frequent modifications like appending or
inserting.
o Not thread-safe.
3. StringBuffer Class:
o Mutable: Like StringBuilder, but it is thread-safe.
o Suitable for multi-threaded environments where strings are modified by multiple
threads.

Explanation:
1. String Class:
 String objects are immutable. Once a string object is created, its content cannot be
changed.
 In the example, we concatenate str1 and str2 to create str3, and we use the concat()
method to modify str1. However, when modifying str1, a new string is created because
strings are immutable in Java.
2. StringBuilder Class:

pg. 17
 StringBuilder is mutable and allows modification of the string without creating a new
object each time.
 The example demonstrates append() and insert() methods, which modify the content of
the StringBuilder object in place. The changes happen directly on the original object.
 StringBuilder is not synchronized, meaning it is not thread-safe, but it performs better
in scenarios where strings are frequently modified in a single thread.
3. StringBuffer Class:
 StringBuffer is mutable and similar to StringBuilder, but it is synchronized, which
makes it thread-safe.
 In the example, we demonstrate the use of append() and reverse() methods.
 StringBuffer is used when thread safety is required, but it generally has slightly lower
performance compared to StringBuilder due to synchronization overhead.

OUTPUT:
Using String class:
str1: Hello
str2: World
str3 (concatenated): Hello World
str1 after modification: Hello Java
Using StringBuilder class:
sb: Hello World from StringBuilder
sb after insert: Hello Beautiful World from StringBuilder
Using StringBuffer class:
sbf: Hello World from StringBuffer
sbf after reverse: rebmuSgnirtS morf dlroW olleH

pg. 18
PROGRAM 6
Write a Java program to implement the concept of exception handling.
SOURCE CODE
import java.util.Scanner;
public class ArrayExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Taking array size from the user
System.out.print("Enter the size of the array: ");
int arraySize = scanner.nextInt();
// Checking if the array size is valid
if (arraySize <= 0) {
System.out.println("Array size should be a positive integer.");
return;
}
// Creating an array with the user-defined size
int[] numbers = new int[arraySize];
// Filling the array with values from the user
System.out.println("Enter " + arraySize + " elements for the array:");
for (int i = 0; i < arraySize; i++) {
try {
numbers[i] = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
scanner.nextLine(); // Clear the buffer
i--; // Decrement to retry the current index
} }
// Trying to access and display elements in the array
System.out.print("Enter the index of the element to display: ");
int index = scanner.nextInt();

pg. 19
// Handling ArrayIndexOutOfBoundsException if index is invalid
try {
System.out.println("Element at index " + index + ": " + numbers[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index out of bounds. Please enter a valid index.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a valid integer for the array size.");
} finally {
// Close the scanner to prevent resource leak
scanner.close();
System.out.println("Program execution completed.");
} } }
Explanation:
1. Array Size Input:
 The program first takes the array size from the user. If the user enters a non-positive
number (0 or negative), the program will print an error message and exit.
 We use a try-catch block to handle the possibility of the user entering a non-integer value
for the array size, causing an InputMismatchException.
2. Filling the Array:
 We prompt the user to enter elements to fill the array. This is done inside a for loop, and
each element is taken from the user input. If the user enters something that's not an integer
(e.g., a string), the program catches the InputMismatchException and prompts the user to
re-enter the value for that index. We use scanner.nextLine() to clear the buffer to avoid
entering invalid data.
3. Array Access:
 We ask the user for an index and attempt to access the array at that index. If the index is
out of bounds, we catch the ArrayIndexOutOfBoundsException and print a meaningful
error message.
4. Finally Block:
 The finally block ensures that the Scanner is closed properly, releasing the resource.

pg. 20
OUTPUT:
Case 1: Valid Input
Enter the size of the array: 5
Enter 5 elements for the array:
1
2
3
4
5
Enter the index of the element to display: 3
Element at index 3: 4
Program execution completed.
Case 2: Invalid Index Access
Enter the size of the array: 3
Enter 3 elements for the array:
10
20
30
Enter the index of the element to display: 5
Error: Index out of bounds. Please enter a valid index.
Program execution completed.
Case 3: Invalid Input for Array Size
Enter the size of the array: abc
Invalid input! Please enter a valid integer for the array size.
Program execution completed.
Case 4: Invalid Input for Array Element
Enter the size of the array: 3
Enter 3 elements for the array:
10
abc
Invalid input! Please enter an integer.

pg. 21
20
30
Enter the index of the element to display: 1
Element at index 1: 20
Program execution completed.

PROGRAM 7
Write a Java program to illustrate the concept of threading using Thread Class and
runnable Interface
SOURCE CODE
Example: A Task Simulation Using Thread Class and Runnable Interface
In this example, we'll simulate two types of workers:
1. Worker 1: This worker will perform a task of printing numbers in a sequence
(using the Thread class).
2. Worker 2: This worker will print letters from A to Z (using the Runnable
interface).

// Example 1: Using the Thread Class


class NumberPrinter extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " - Number: " + i);
try {
Thread.sleep(500); // Simulating a task that takes time (half a second)
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

pg. 22
// Example 2: Using the Runnable Interface
class LetterPrinter implements Runnable {
public void run() {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println(Thread.currentThread().getId() + " - Letter: " + c);
try {
Thread.sleep(300); // Simulating a task that takes time (three hundred milliseconds)
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class ThreadExample {


public static void main(String[] args) {
// Using Thread class
NumberPrinter numberPrinter = new NumberPrinter();
numberPrinter.start(); // Starting the number printing thread

// Using Runnable interface


Runnable letterPrinter = new LetterPrinter();
Thread letterThread = new Thread(letterPrinter);
letterThread.start(); // Starting the letter printing thread

// Adding another thread using Thread class


NumberPrinter anotherNumberPrinter = new NumberPrinter();
anotherNumberPrinter.start(); // Starting another number printing thread
}
}

pg. 23
Explanation:

1. NumberPrinter (using Thread class):

o This class extends the Thread class and overrides the run() method to print numbers from
1 to 5.

o The Thread.sleep(500) simulates a delay between each number print to make it more
noticeable.

2. LetterPrinter (using Runnable interface):

o This class implements the Runnable interface and overrides the run() method to print
letters from 'A' to 'E'.

o The Thread.sleep(300) simulates a delay between each letter print.

3. Main method:

o We create an instance of NumberPrinter and call the start() method to start the thread for
printing numbers.

o We create an instance of LetterPrinter (which implements Runnable), pass it to a Thread


object, and call the start() method to start the thread for printing letters.

o We also create and start another NumberPrinter thread for illustration.

Key Points:

 Thread Class: We created a class that extends Thread and overrides the run() method. The start()
method was called to begin the execution of the thread.

 Runnable Interface: We created a class that implements Runnable, and passed it to a Thread
object, which was then started.

 Thread.sleep(): This was used to simulate some time-consuming work within the threads.

pg. 24
OUTPUT:

The output will show the execution of threads in an interleaved manner (due to the concurrent nature of
threads):

1 - Number: 1
3 - Letter: A
1 - Number: 2
3 - Letter: B
2 - Number: 1
3 - Letter: C
2 - Number: 2
3 - Letter: D
1 - Number: 3
3 - Letter: E
1 - Number: 4
2 - Number: 3
1 - Number: 5
2 - Number: 4
2 - Number: 5

pg. 25
PROGRAM 8
Write a Java program to illustrate the concept of Thread synchronization.

SOURCE CODE
In this example:
 We'll have a CricketScore class that manages the score of a cricket match.
 Multiple threads will attempt to update the score (e.g., scoring runs, updating the score for
boundaries, or wickets) concurrently.
 We'll use synchronization to ensure that only one thread can modify the score at a time to avoid
inconsistencies.
Program Explanation:
1. CricketScore Class: This class manages the score (runs, wickets) of the match. It will have
synchronized methods to update runs and wickets to ensure that only one thread can modify the
score at a time.
2. ScorerThread Class: This class represents a thread that simulates scoring runs or taking
wickets in the cricket match.
3. Main Class: This class creates multiple threads to simulate the update of the cricket score by
different players.
class CricketScore {
private int runs = 0;
private int wickets = 0;

// Synchronized method to add runs to the score


public synchronized void addRuns(int runs) {
this.runs += runs;
System.out.println(Thread.currentThread().getName() + " scored " + runs + " runs. Total runs: " +
this.runs);
}

// Synchronized method to add wickets


public synchronized void addWicket() {
this.wickets++;
System.out.println(Thread.currentThread().getName() + " took a wicket. Total wickets: " +
this.wickets);
}

pg. 26
// Display final score
public synchronized void displayScore() {
System.out.println("Final Score - Runs: " + runs + ", Wickets: " + wickets);
}
}

class ScorerThread extends Thread {


private CricketScore score;
private int runsToScore;

// Constructor to initialize the CricketScore object and runs to score


public ScorerThread(CricketScore score, int runsToScore) {
this.score = score;
this.runsToScore = runsToScore;
}

@Override
public void run() {
// Scoring the runs
for (int i = 0; i < runsToScore; i++) {
score.addRuns(1); // Scoring one run
try {
Thread.sleep(100); // Simulate time between runs
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

pg. 27
class WicketThread extends Thread {
private CricketScore score;

public WicketThread(CricketScore score) {


this.score = score;
}

@Override
public void run() {
// Simulating taking a wicket
score.addWicket();
try {
Thread.sleep(200); // Simulate time between wickets
} catch (InterruptedException e) {
System.out.println(e);
}
}
}

public class CricketScoreApp {


public static void main(String[] args) throws InterruptedException {
CricketScore cricketScore = new CricketScore();

// Creating threads for scoring runs


ScorerThread player1 = new ScorerThread(cricketScore, 10); // Player 1 scores 10 runs
ScorerThread player2 = new ScorerThread(cricketScore, 5); // Player 2 scores 5 runs

// Creating threads for taking wickets


WicketThread bowler1 = new WicketThread(cricketScore);
WicketThread bowler2 = new WicketThread(cricketScore);

pg. 28
// Starting threads
player1.start();
player2.start();
bowler1.start();
bowler2.start();
// Waiting for all threads to finish
player1.join();
player2.join();
bowler1.join();
bowler2.join();
// Displaying the final score
cricketScore.displayScore();
}
}
Explanation of the Program:
1. CricketScore Class:
o It has two variables: runs and wickets to hold the current score.
o The addRuns(int runs) method is synchronized so that only one thread can increment
the runs at a time.
o The addWicket() method is synchronized so that only one thread can increment the
wickets count at a time.
o The displayScore() method prints the final score after all threads have finished.
2. ScorerThread Class:
o This class extends Thread and represents a player who scores runs. It accepts the
number of runs to score as a parameter and calls the addRuns() method in a loop to
simulate scoring.
3. WicketThread Class:
o This class extends Thread and represents a bowler who takes a wicket. It calls the
addWicket() method to simulate taking a wicket.
4. Main Method:
o The main method creates instances of CricketScore, ScorerThread, and WicketThread.
o It starts the threads and waits for all threads to finish using join().
o Finally, it calls displayScore() to print the final score.

pg. 29
OUTPUT:
Thread-0 scored 1 runs. Total runs: 1
Thread-1 scored 1 runs. Total runs: 2
Thread-0 scored 1 runs. Total runs: 3
Thread-1 scored 1 runs. Total runs: 4
Thread-0 scored 1 runs. Total runs: 5
Thread-1 scored 1 runs. Total runs: 6
Thread-0 scored 1 runs. Total runs: 7
Thread-1 scored 1 runs. Total runs: 8
Thread-0 scored 1 runs. Total runs: 9
Thread-1 scored 1 runs. Total runs: 10
Thread-2 took a wicket. Total wickets: 1
Thread-2 took a wicket. Total wickets: 2
Final Score - Runs: 15, Wickets: 2

Key Points:
1. Thread Synchronization: The addRuns() and addWicket() methods are synchronized, ensuring
that only one thread can modify the score (runs or wickets) at a time.

2. Concurrency: The program simulates the concurrent nature of a cricket match where multiple
threads can score runs or take wickets simultaneously. However, because of synchronization, the
updates to the score are done safely.

3. Race Conditions: Without synchronization, if multiple threads tried to update the runs or wickets
simultaneously, it could lead to inconsistencies (e.g., two threads updating the score at the same
time, causing a lost update). Synchronization prevents this issue.

By using synchronization, we ensure that the cricket score is updated correctly even when multiple
threads are running concurrently.

pg. 30
PROGRAM 9
Write a Java program to illustrate collection classes like Array List, LinkedList, Tree
map and Hash map.
SOURCE CODE
Below is a Java program that demonstrates the use of some of the most commonly used collection
classes: ArrayList, LinkedList, HashMap, and TreeMap. This example will illustrate how to add, remove,
and access elements in each of these collections.

import java.util.*;

public class CollectionExample {

public static void main(String[] args) {

// Example 1: Using ArrayList (List interface)

System.out.println("ArrayList Example:");

List<String> arrayList = new ArrayList<>();

arrayList.add("Apple");

arrayList.add("Banana");

arrayList.add("Orange");

arrayList.add("Grapes");

// Print all elements

System.out.println("ArrayList: " + arrayList);

// Accessing an element by index

System.out.println("Element at index 2: " + arrayList.get(2));

// Removing an element

arrayList.remove("Banana");

System.out.println("ArrayList after removal: " + arrayList);

System.out.println();

pg. 31
// Example 2: Using LinkedList (List interface)

System.out.println("LinkedList Example:");

List<String> linkedList = new LinkedList<>();

linkedList.add("Cat");

linkedList.add("Dog");

linkedList.add("Rabbit");

linkedList.add("Elephant");

// Print all elements

System.out.println("LinkedList: " + linkedList);

// Adding an element at the beginning

linkedList.addFirst("Tiger");

System.out.println("LinkedList after adding at the beginning: " + linkedList);

// Removing the first element

linkedList.removeLast();

System.out.println("LinkedList after removal from Last: " + linkedList);

System.out.println();

// Example 3: Using HashMap (Map interface)

System.out.println("HashMap Example:");

Map<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "One");

hashMap.put(2, "Two");

hashMap.put(3, "Three");

hashMap.put(4, "Four");

pg. 32
// Print all elements (Key-Value pairs)

System.out.println("HashMap: " + hashMap);

// Accessing a value by key

System.out.println("Value for key 3: " + hashMap.get(3));

// Removing a key-value pair

hashMap.remove(2);

System.out.println("HashMap after removal of key 2: " + hashMap);

System.out.println();

// Example 4: Using TreeMap (Map interface)

System.out.println("TreeMap Example:");

Map<Integer, String> treeMap = new TreeMap<>();

treeMap.put(10, "Ten");

treeMap.put(5, "Five");

treeMap.put(15, "Fifteen");

treeMap.put(3, "Three");

// Print all elements (Key-Value pairs in sorted order)

System.out.println("TreeMap: " + treeMap);

// Accessing a value by key

System.out.println("Value for key 15: " + treeMap.get(15));

// Removing a key-value pair

treeMap.remove(5);

System.out.println("TreeMap after removal of key 5: " + treeMap);

System.out.println();

pg. 33
Explanation:

1. ArrayList:

o ArrayList is a resizable array implementation of the List interface.

o It allows duplicate elements and maintains the insertion order.

o Example:

 We add some fruit names to the ArrayList, remove one, and access an element by
index.

2. LinkedList:

o LinkedList is a doubly linked list implementation of the List interface.

o It allows fast insertions and deletions at both ends, but random access is slower than an
ArrayList.

o Example:

 We add and remove elements at the beginning using addFirst() and removeFirst()
methods.

3. HashMap:

o HashMap is a map that stores key-value pairs, and the keys are unordered.

o It allows only one null key and multiple null values.

o Example:

 We store integer keys with string values and demonstrate adding, accessing, and
removing key-value pairs.

4. TreeMap:

o TreeMap is a map that stores key-value pairs in a sorted order, based on the natural
ordering of the keys or by a custom comparator.

o Example:

 We store integer keys in a TreeMap, which automatically sorts them in ascending


order.

pg. 34
OUTPUT:

ArrayList Example:

ArrayList: [Apple, Banana, Orange, Grapes]

Element at index 2: Orange

ArrayList after removal: [Apple, Orange, Grapes]

LinkedList Example:

LinkedList: [Cat, Dog, Rabbit, Elephant]

LinkedList after adding at the beginning: [Tiger, Cat, Dog, Rabbit, Elephant]

LinkedList after removal from beginning: [Cat, Dog, Rabbit, Elephant]

HashMap Example:

HashMap: {1=One, 2=Two, 3=Three, 4=Four}

Value for key 3: Three

HashMap after removal of key 2: {1=One, 3=Three, 4=Four}

TreeMap Example:

TreeMap: {3=Three, 5=Five, 10=Ten, 15=Fifteen}

Value for key 15: Fifteen

TreeMap after removal of key 5: {3=Three, 10=Ten, 15=Fifteen}

Key Points:

1. ArrayList: Provides fast random access and is suitable when you need to access elements by
index frequently.

2. LinkedList: Suitable when you frequently add and remove elements from the beginning or end
of the list.

pg. 35
3. HashMap: Allows storing key-value pairs with fast access using keys. It does not maintain any
order of elements.

4. TreeMap: Stores key-value pairs in a sorted order based on keys. It is useful when you need the
elements to be ordered.

These collection classes are part of the Java Collections Framework, and they help you store, manage,
and manipulate data efficiently based on the use case.

PROGRAM 10
Write a Java program to illustrate Legacy classes like Vector, Hash table
SOURCE CODE
In this code:

1. We'll store 5 names in a Vector.

2. We'll store 5 names with their associated IDs in a Hashtable.

import java.util.*;

public class LegacyClassesNamesExample {


public static void main(String[] args) {

// 1. Using Vector to store 5 names


System.out.println("---- Vector Example: Storing 5 names ----");

// Creating a Vector to store names


Vector<String> namesVector = new Vector<>();

// Adding names to the Vector


namesVector.add("Information Technology");
namesVector.add("Computer Science and Engg.");

pg. 36
namesVector.add("Data Science");
namesVector.add("Internet of Things");
namesVector.add("Artifical Intelligence and Machine Learning");

// Printing all names stored in the Vector


System.out.println("Names stored in Vector: ");
for (String name : namesVector) {
System.out.println(name);
}

// 2. Using Hashtable to store 5 names with associated IDs


System.out.println("\n---- Hashtable Example: Storing 5 names with IDs ----");

// Creating a Hashtable to store names with their corresponding ID


Hashtable<Integer, String> namesHashtable = new Hashtable<>();

// Adding names with IDs (key-value pairs) to the Hashtable


namesHashtable.put(737, "Information Technology");
namesHashtable.put(733, "Computer Science and Engg.");
namesHashtable.put(750, "Data Science");
namesHashtable.put(749, "Internet of Things");
namesHashtable.put(748, "Artifical Intelligence and Machine Learning");

// Printing all names stored in the Hashtable


System.out.println("Names stored in Hashtable with their IDs: ");
for (Map.Entry<Integer, String> entry : namesHashtable.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}

pg. 37
Explanation of the Code:
1. Vector Example:
o We create a Vector<String> to store names.
o The add() method is used to insert names into the Vector.
o We then iterate through the Vector and print each name using an enhanced for loop.
2. Hashtable Example:
o We create a Hashtable<Integer, String> to store names with corresponding IDs (as key-
value pairs).
o The put() method is used to add names along with IDs into the Hashtable.
o We then iterate through the Hashtable using entrySet() to print both the ID (key) and the
associated name (value).

OUTPUT:

---- Vector Example: Storing 5 names ----


Names stored in Vector:
Information Technology
Computer Science and Engg.
Data Science
Internet of Things
Artifical Intelligence and Machine Learning

---- Hashtable Example: Storing 5 names with IDs ----


Names stored in Hashtable with their IDs:
ID: 733, Name: Computer Science and Engg.
ID: 750, Name: Data Science
ID: 749, Name: Internet of Things
ID: 748, Name: Artifical Intelligence and Machine Learning
ID: 737, Name: Information Technology

pg. 38
PROGRAM 11
Write a Java program that reads a file name from the user, and then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file and the
length of the file in bytes using an example

SOURCE CODE
File Information
java
Copy
import java.io.File;
import java.util.Scanner;

public class FileInfo {


public static void main(String[] args) {
// Create a scanner object to take user input
Scanner scanner = new Scanner(System.in);

// Prompt user to enter a file name


System.out.print("Enter the file name (with path if necessary): ");
String fileName = scanner.nextLine();

// Create a File object for the given file name


File file = new File(fileName);

// Check if the file exists


if (file.exists()) {
System.out.println("File exists.");

// Check if the file is readable


System.out.println("File is readable: " + file.canRead());

// Check if the file is writable


System.out.println("File is writable: " + file.canWrite());

pg. 39
// Check if the file is a directory or a regular file
if (file.isDirectory()) {
System.out.println("It is a directory.");
} else if (file.isFile()) {
System.out.println("It is a regular file.");
// Print the length of the file in bytes
System.out.println("File length (in bytes): " + file.length());
}
} else {
System.out.println("File does not exist.");
}

// Close the scanner


scanner.close();
}
}
Explanation:
1. Scanner Input:
o The program uses a Scanner to prompt the user to enter the name of a file (it can
include the path if the file is not in the current directory).
2. File Object:
o A File object is created using the file name input by the user.
3. File Existence:
o The program checks if the file exists using file.exists(). If the file doesn't exist, it prints
a message and terminates.
4. Readability and Writability:
o The program checks if the file is readable using file.canRead() and if it is writable using
file.canWrite().
5. File Type:
o The program checks if the file is a directory using file.isDirectory() or a regular file
using file.isFile().

pg. 40
6. File Length:
o If the file is a regular file, the program prints the length of the file in bytes using
file.length().

Example Execution:
Example 1: Regular File
Let's assume the file example.txt exists in the same directory as the program.
Input:
Enter the file name (with path if necessary): example.txt
Output:
File exists.
File is readable: true
File is writable: true
It is a regular file.
File length (in bytes): 1024
Example 2: Directory
Let's assume the directory /home/user/documents exists.
Input:
Enter the file name (with path if necessary): /home/user/documents
Output:
File exists.
File is readable: true
File is writable: true
It is a directory.
Example 3: File Does Not Exist
Let's assume the file nonexistentfile.txt does not exist.
Input:
Enter the file name (with path if necessary): nonexistentfile.txt
Output:
File does not exist.
Key Methods Used:
 exists(): Checks if the file or directory exists.

pg. 41
 canRead(): Checks if the file is readable.
 canWrite(): Checks if the file is writable.
 isFile(): Checks if the file is a regular file.
 isDirectory(): Checks if the file is a directory.
 length(): Returns the size of the file in bytes (only applicable to regular files).
Conclusion:
This program demonstrates how to use the File class in Java to retrieve various properties of a file,
including checking its existence, readability, writability, type, and size. It gives the user a detailed
overview of the file's properties based on the provided input

pg. 42
PROGRAM 12

Write a Java program to illustrate the concept of I/O Streams

SOURCE CODE

In Java, I/O Streams are used to read from and write to files, consoles, and other input/output devices.
There are two main types of streams in Java: Byte Streams and Character Streams.

Here's a simple Java program that demonstrates both File InputStream and File OutputStream, which
are examples of byte streams. The program writes data to a file and then reads it back.

import java.io.*;

public class IOStreamsExample {

public static void main(String[] args) {

// Define file path for the output and input files

String filePath = "example.txt";

// Write data to the file using FileOutputStream

try (FileOutputStream fos = new FileOutputStream(filePath)) {

String content = "This is an example of I/O Streams in Java!";

byte[] contentBytes = content.getBytes();

// Writing the content to the file

fos.write(contentBytes);

System.out.println("Data has been written to the file.");

} catch (IOException e) {

System.out.println("An error occurred while writing to the file.");

e.printStackTrace();

// Read data from the file using FileInputStream

try (FileInputStream fis = new FileInputStream(filePath)) {

pg. 43
int byteRead;

StringBuilder fileContent = new StringBuilder();

// Reading the content of the file byte by byte

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

fileContent.append((char) byteRead);

System.out.println("Data read from the file: ");

System.out.println(fileContent.toString());

} catch (IOException e) {

System.out.println("An error occurred while reading from the file.");

e.printStackTrace();

Explanation:

1. FileOutputStream:

o We use FileOutputStream to write data to a file. The write() method writes bytes to the
file. In this example, we convert a string to bytes and write those bytes to the file.

2. FileInputStream:

o We use FileInputStream to read data from a file. The read() method reads one byte at a
time from the file. The while loop continues until we reach the end of the file (indicated
by -1).

3. Try-with-resources:

o This is used to automatically close resources (FileOutputStream and FileInputStream)


after the operations are completed, making sure there are no resource leaks.

pg. 44
Output:

The program will output:

1. A message indicating that the data was written to the file.

2. The contents read from the file (which should be the string you initially wrote).

Make sure the file path example.txt is accessible and writable in your environment.

You can modify this program to use character streams like FileReader and FileWriter for working with
text files instead of byte streams.

pg. 45
PROGRAM 13

Write a Java program to implement Serialization and Deserialization concept.

SOURCE CODE

Serialization and Deserialization in Java are mechanisms that allow you to convert an object into
a byte stream (serialization) and restore an object from the byte stream (deserialization). This is often
used when saving objects to a file or sending objects over a network.

Steps:

1. Serialization: Convert an object into a byte stream.

2. Deserialization: Convert the byte stream back into an object.

import java.io.*;

// Step 1: Create a class to be serialized and deserialized

class Person implements Serializable {

private static final long serialVersionUID = 1L; // Unique ID to ensure class compatibility during
deserialization

private String name;

private int age;

// Constructor

public Person(String name, int age) {

this.name = name;

this.age = age;

// Getters

public String getName() {

return name;

public int getAge() {

pg. 46
return age;

// Override toString method to display the object in a readable way

@Override

public String toString() {

return "Person{name='" + name + "', age=" + age + '}';

public class SerializationExample {

// Serialization method

public static void serializePerson(Person person, String filename) {

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {

oos.writeObject(person);

System.out.println("Serialization successful!");

} catch (IOException e) {

e.printStackTrace();

} }

// Deserialization method

public static Person deserializePerson(String filename) {

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {

Person person = (Person) ois.readObject();

return person;

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

} return null;

pg. 47
}

public static void main(String[] args) {

// Create an object of Person

Person person1 = new Person("Mohsin", 31);

// Serialize the person object to a file

String filename = "person.ser";

serializePerson(person1, filename);

// Deserialize the object from the file

Person deserializedPerson = deserializePerson(filename);

// Display the deserialized object

if (deserializedPerson != null) {

System.out.println("Deserialized Person: " + deserializedPerson);

} }

Explanation:

1. Person Class:

o The Person class implements the Serializable interface, which marks the class as eligible
for serialization.

o It has two fields: name (String) and age (int).

o We also override the toString() method to make it easier to print the object.

2. Serialization:

o The serializePerson method takes a Person object and a filename, and serializes the object
into the specified file using an ObjectOutputStream.

o The FileOutputStream is used to write the serialized data to a file.

3. Deserialization:

pg. 48
o The deserializePerson method reads the serialized object from the file using an
ObjectInputStream.

o The FileInputStream is used to read the data, and ObjectInputStream restores the object.

4. Main Method:

o In the main method, we create a Person object, serialize it into a file named person.ser,
and then deserialize it back from the file.

o Finally, we print the deserialized object.

Output:

Serialization successful!

Deserialized Person: Person{name='Mohsin', age=31}

Key Points:

 Serializable Interface: A class must implement the Serializable interface to be eligible for
serialization. This is a marker interface (i.e., it doesn't contain any methods).

 serialVersionUID: This is a unique identifier for the class used during the deserialization
process. It's used to ensure that the sender and receiver have loaded classes that are compatible
with serialization and deserialization. If the serialVersionUID doesn't match, an
InvalidClassException is thrown.

 ObjectOutputStream: Used for writing objects to a file (serialization).

 ObjectInputStream: Used for reading objects from a file (deserialization).

NOTE:

 Only objects of classes that implement Serializable can be serialized.

 Non-serializable fields (like transient variables) are not serialized. If a class has fields that you
don't want to serialize, mark them with the transient keyword.

Example:

private transient int temporaryData;

pg. 49
PROGRAM 14

Write a Java applet program for handling mouse & key events

SOURCE CODE

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class MouseKeyEventApplet extends Applet {

// Variables to store mouse and key event information

private String mouseEventInfo = "";

private String keyEventInfo = "";

@Override

public void init() {

// Set the background color of the applet

setBackground(Color.white);

// Set up mouse listener to capture mouse events

addMouseListener(new MouseAdapter() {

@Override

public void mouseClicked(MouseEvent e) {

mouseEventInfo = "Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")";

repaint(); // Refresh the applet to show the new message

@Override

public void mouseEntered(MouseEvent e) {

mouseEventInfo = "Mouse Entered the Applet";

repaint();

pg. 50
}

@Override

public void mouseExited(MouseEvent e) {

mouseEventInfo = "Mouse Exited the Applet";

repaint();

} });

// Set up mouse motion listener to capture mouse movements

addMouseMotionListener(new MouseMotionAdapter() {

@Override

public void mouseMoved(MouseEvent e) {

mouseEventInfo = "Mouse Moved to (" + e.getX() + ", " + e.getY() + ")";

repaint();

});

// Set up key listener to capture key events

addKeyListener(new KeyAdapter() {

@Override

public void keyPressed(KeyEvent e) {

keyEventInfo = "Key Pressed: " + KeyEvent.getKeyText(e.getKeyCode());

repaint(); // Refresh the applet to show the key event

@Override

public void keyReleased(KeyEvent e) {

keyEventInfo = "Key Released: " + KeyEvent.getKeyText(e.getKeyCode());

repaint();

pg. 51
} });

// Make the applet focusable so it can capture key events

setFocusable(true);}

@Override

public void paint(Graphics g) {

// Display the mouse event information

g.setColor(Color.BLACK);

g.drawString("Mouse Event Info: " + mouseEventInfo, 20, 50);

// Display the key event information

g.setColor(Color.BLACK);

g.drawString("Key Event Info: " + keyEventInfo, 20, 70);

}}

Explanation:

1. Imports:

o java.applet.Applet: The class for creating the applet.

o java.awt.*: Contains classes for managing graphics, colors, events, etc.

o java.awt.event.*: Contains classes for handling various event types, including mouse and
key events.

2. Mouse Event Handling:

o MouseListener: A listener that detects mouse-related actions. We use an anonymous


subclass of MouseAdapter, which implements the MouseListener interface. This class
allows us to override only the methods we need (e.g., mouseClicked, mouseEntered,
mouseExited).

 mouseClicked: Captures mouse clicks and stores the coordinates of the click.

 mouseEntered: Captures when the mouse enters the applet area.

 mouseExited: Captures when the mouse exits the applet area.

pg. 52
o MouseMotionListener: This listener captures mouse movements. We use an anonymous
subclass of MouseMotionAdapter.

 mouseMoved: Captures the mouse's position as it moves.

3. Key Event Handling:

o KeyListener: A listener that detects keyboard events. We use KeyAdapter, which


implements the KeyListener interface. This allows us to override only the methods we
need (e.g., keyPressed, keyReleased).

 keyPressed: Captures when a key is pressed and displays the name of the key.

 keyReleased: Captures when a key is released.

4. Focusability:

o setFocusable(true): This is essential because an applet must be focusable in order to


capture key events. By default, applets are not focusable, but calling this method allows
the applet to receive keyboard input.

5. Graphics:

o The paint(Graphics g) method is used to render text (mouse and key event information)
on the applet. The drawString() method displays the event information on the applet's
window.

6. Background Color:

o The applet background color is set to white using setBackground(Color.white) for a clean
interface.

HTML File to Run the Applet:

To run the applet, you need an HTML file that references the applet's class. Here’s how you can set up
the HTML file:

<html>

<body>

<applet code="MouseKeyEventApplet.class" width="400" height="300">

</applet>

pg. 53
</body>

</html>

How to Run the Applet:

1. Save the Java Code: Save the above Java code in a file named MouseKeyEventApplet.java.

2. Compile the Java Applet:

javac MouseKeyEventApplet.java

3. Create the HTML File: Save the HTML code in a file named applet.html.

4. Run the Applet:

o Use the appletviewer tool to run the applet (available in older Java versions):

appletviewer applet.html

o Alternatively, use an IDE that supports applet execution, like older versions of Eclipse or
IntelliJ IDEA.

Expected Output:

 Mouse Events:

o When the mouse clicks inside the applet, it will display the coordinates of the click.

o When the mouse enters or exits the applet, it will display corresponding messages.

o When the mouse moves, it will show the current mouse position.

 Key Events:

o When a key is pressed, it will display the key pressed.

o When a key is released, it will display the key released.

Key Features:

 MouseEvent: Detects and displays mouse-related actions (click, enter, exit, move).

 KeyEvent: Detects and displays key-related actions (key press, key release).

 Applets: The program runs inside an applet, allowing interaction with the mouse and keyboard.

pg. 54
PROGRAM 15

Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits
and for the +,-, *, % operations. Add a text field to display the result.

SOURCE CODE:

Java program that creates a basic calculator using Swing components. It uses a GridLayout to arrange
buttons for digits and operations (+, -, *, /, %) along with a text field to display the result.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SimpleCalculator {

// Frame to hold the components

private JFrame frame;

private JTextField textField;

// Variables for the current calculation state

private String currentInput = "";

private double num1 = 0;

private double num2 = 0;

private String operator = "";

// Constructor to setup the calculator UI

public SimpleCalculator() {

// Set up the frame

frame = new JFrame("Simple Calculator");

frame.setLayout(new BorderLayout());

// Create a text field to display the result

textField = new JTextField();

pg. 55
textField.setFont(new Font("Arial", Font.BOLD, 24));

textField.setEditable(false);

frame.add(textField, BorderLayout.NORTH);

// Panel to hold the buttons with a GridLayout

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 10, 10));

// Create and add buttons to the panel

String[] buttons = {

"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"0", ".", "=", "+"

};

// Adding digits and operation buttons to the panel

for (String text : buttons) {

JButton button = new JButton(text);

button.setFont(new Font("Arial", Font.PLAIN, 24));

button.addActionListener(new ButtonClickListener());

panel.add(button);

// Add panel to the frame

frame.add(panel, BorderLayout.CENTER);

// Set frame properties

frame.setSize(400, 500);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pg. 56
frame.setLocationRelativeTo(null); // Center the frame

frame.setVisible(true);

// ActionListener for button clicks

private class ButtonClickListener implements ActionListener {

@Override

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if (command.equals("=")) {

// Perform calculation

try {

num2 = Double.parseDouble(currentInput);

double result = performCalculation(num1, num2, operator);

textField.setText(String.valueOf(result));

currentInput = String.valueOf(result);

operator = "";

} catch (NumberFormatException ex) {

textField.setText("Error");

currentInput = "";

operator = "";

} else if (command.equals("C")) {

// Clear everything

currentInput = "";

num1 = 0;

pg. 57
num2 = 0;

operator = "";

textField.setText("");

} else if (command.equals("+") || command.equals("-") || command.equals("*") ||


command.equals("/") || command.equals("%")) {

// Set operator and store first number

if (!currentInput.isEmpty()) {

num1 = Double.parseDouble(currentInput);

operator = command;

currentInput = "";

} else {

// Append digit or decimal point to the input

currentInput += command;

textField.setText(currentInput);

// Perform the calculation based on the operator

private double performCalculation(double num1, double num2, String operator) {

switch (operator) {

case "+":

return num1 + num2;

case "-":

return num1 - num2;

case "*":

pg. 58
return num1 * num2;

case "/":

if (num2 != 0) {

return num1 / num2;

} else {

textField.setText("Error");

return 0;

case "%":

return num1 % num2;

default:

return 0;

// Main method to run the program

public static void main(String[] args) {

// Invoke the constructor on the Event Dispatch Thread

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

new SimpleCalculator();

});

} }

pg. 59
Explanation:

1. JFrame:

o The main container for the application, where components like the text field and buttons
are added.

2. JTextField:

o Used to display the current input or the result of the calculation.

o It is set to non-editable so users cannot directly modify the text.

3. GridLayout:

o This layout manager is used to arrange the calculator buttons in a 4x4 grid. We use
GridLayout(4, 4) to create four rows and four columns, allowing space for all the buttons.

4. JButton:

o Buttons for digits (0-9), operations (+, -, *, /, %), and the equals (=) button are created
and added to the panel.

o Each button is assigned an ActionListener to handle button clicks.

5. ActionListener:

o A nested class (ButtonClickListener) that listens for button clicks and performs actions
based on the button pressed:

 If a digit or decimal point is pressed, it's appended to the current input.

 If an operator is pressed, the current number is saved and the operator is stored.

 When the equals (=) button is pressed, the calculation is performed and displayed.

 The calculation is performed by the performCalculation method, which handles


addition, subtraction, multiplication, division, and modulus.

6. Clear Operation (C button):

o The program clears the current input and resets the state when the clear button is pressed.

Features:

 Grid Layout arranges the buttons neatly in rows and columns.

pg. 60
 Basic Operations: Addition, subtraction, multiplication, division, and modulus are supported.

 Input Handling: Appends numbers and operators to the display and calculates the result when
= is pressed.

How to Run:

1. Copy the code into a .java file (e.g., SimpleCalculator.java).

2. Compile and run it using a Java IDE or the command line:

o javac SimpleCalculator.java

o java SimpleCalculator

Output:

The program will launch a window with a simple calculator interface. You can click on the buttons to
perform calculations. For example:

Input: 2 + 3 = 5

Input: 8 * 7 = 56

PROGRAM 16

Write an example for JDBC prepared statement with Result Set

SOURCE CODE

Using JDBC PreparedStatement with ResultSet

pg. 61
Let's assume we have a users table in a database with the following columns:

 id (int)

 username (String)

 email (String)

import java.sql.*;

public class JDBCExample {

public static void main(String[] args) {

// Database connection details

String url = "jdbc:mysql://localhost:3306/your_database"; // Replace with your database URL

String user = "root"; // Replace with your database username

String password = "password"; // Replace with your database password

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

// Step 1: Establish a connection to the database

conn = DriverManager.getConnection(url, user, password);

// Step 2: Prepare the SQL query using PreparedStatement

String sql = "SELECT id, username, email FROM users WHERE email = ?";

pstmt = conn.prepareStatement(sql);

// Step 3: Set parameters for the PreparedStatement

pstmt.setString(1, "example@example.com"); // Set the email parameter

// Step 4: Execute the query and get the ResultSet

rs = pstmt.executeQuery();

pg. 62
// Step 5: Process the ResultSet

while (rs.next()) {

int id = rs.getInt("id");

String username = rs.getString("username");

String email = rs.getString("email");

// Print the results

System.out.println("ID: " + id);

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

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

System.out.println("-----------------------------");

} catch (SQLException e) {

e.printStackTrace();

} finally {

// Step 6: Close resources

try {

if (rs != null) rs.close();

if (pstmt != null) pstmt.close();

if (conn != null) conn.close();

} catch (SQLException e) {

e.printStackTrace();

pg. 63
Explanation:

1. Establish Connection: We create a Connection object to connect to the database using


DriverManager.getConnection().

2. Prepare SQL Query: A PreparedStatement is used to avoid SQL injection and to handle
parameterized queries. The query selects id, username, and email from the users table where the
email matches a given parameter.

3. Set Parameters: The setString(1, "example@example.com") method sets the value for the first
parameter (email) in the SQL query.

4. Execute Query: The executeQuery() method runs the query, returning a ResultSet containing
the data.

5. Process the ResultSet: The ResultSet is processed by looping through its rows using the next()
method. We extract the column values using the getInt() and getString() methods.

6. Close Resources: We close the ResultSet, PreparedStatement, and Connection in the finally
block to ensure they are released, even if an exception occurs.

Output (Example):

If a user with the email example@example.com exists, the output could look like this:

ID: 1

Username: john_doe

Email: example@example.com

-----------------------------

Important Notes:

 Ensure that you have the appropriate JDBC driver for your database (e.g., MySQL, PostgreSQL).

 Replace the database URL, username, and password with your own credentials.

 Always close your ResultSet, PreparedStatement, and Connection in the finally block to prevent
resource leaks.

pg. 64
PROGRAM 17

Program to create a simple JList and JCheckBox(Using Applet)

SOURCE CODE

import java.applet.Applet;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JListAndCheckBoxApplet extends Applet {

// Declare the JList and JCheckBox components

private JList<String> fruitList;

private JCheckBox uppercaseCheckBox;

@Override

public void init() {

// Set the layout for the applet

setLayout(new BorderLayout());

// Create a list of fruits

String[] fruits = {"Apple", "Banana", "Orange", "Mango", "Pineapple"};

fruitList = new JList<>(fruits);

fruitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Allow only single


selection

// Wrap the JList in a JScrollPane for scrolling

JScrollPane listScrollPane = new JScrollPane(fruitList);

// Create a JCheckBox

uppercaseCheckBox = new JCheckBox("Show selected fruit in uppercase");

// Create a JPanel and add components to it

pg. 65
JPanel panel = new JPanel();

panel.setLayout(new BorderLayout());

panel.add(listScrollPane, BorderLayout.CENTER);

panel.add(uppercaseCheckBox, BorderLayout.SOUTH);

// Add the panel to the applet

add(panel, BorderLayout.CENTER);

// Add an ItemListener to the JCheckBox

uppercaseCheckBox.addItemListener(new ItemListener() {

@Override

public void itemStateChanged(ItemEvent e) {

String selectedFruit = fruitList.getSelectedValue();

if (selectedFruit != null) {

// If checkbox is selected, display the fruit in uppercase

if (uppercaseCheckBox.isSelected()) {

showMessage(selectedFruit.toUpperCase());

} else {

showMessage(selectedFruit);

} else {

showMessage("No fruit selected");

});

pg. 66
// Method to show the selected fruit in the applet's message

private void showMessage(String message) {

Graphics g = getGraphics();

g.clearRect(0, 0, getWidth(), getHeight()); // Clear the screen

g.drawString("Selected Fruit: " + message, 20, 150);

Explanation of the Program:

1. JApplet:

o The program extends the Applet class, which is the base class for applet programs in Java.
Although applets are outdated, they are still a good learning tool for basic UI components.

2. JList:

o A JList is used to display a list of fruits. It allows users to select a fruit from the list.

o The list of fruits is passed as an array of strings {"Apple", "Banana", "Orange", "Mango",
"Pineapple"}.

o The setSelectionMode(ListSelectionModel.SINGLE_SELECTION) method ensures that


only one item can be selected at a time.

3. JCheckBox:

o A JCheckBox is created with the label "Show selected fruit in uppercase". The user can
check or uncheck the box to decide if the selected fruit should be shown in uppercase.

4. JPanel:

o A JPanel is used to hold the JList and JCheckBox. The JPanel uses BorderLayout to
arrange the components in a way that the list is in the center and the checkbox is at the
bottom.

5. Event Handling:

pg. 67
o The ItemListener is added to the checkbox. It listens for changes in the checkbox state
(checked/unchecked). When the checkbox state changes, it checks if a fruit is selected
from the list.

o If a fruit is selected, it either displays the fruit in uppercase (if the checkbox is selected)
or in normal case (if the checkbox is unchecked).

6. Graphics:

o The showMessage() method uses the Graphics object to display the message about the
selected fruit directly on the applet's window.

How to Run the Applet:

1. Save the code into a file named JListAndCheckBoxApplet.java.

2. Create an HTML file to run the applet. Applets are usually run through an HTML file (or using
an applet viewer). Create a simple HTML file to load and run the applet:

<html>

<body>

<applet code="JListAndCheckBoxApplet.class" width="400" height="300">

</applet>

</body>

</html>

3. Compile the Java applet:

Use the command below to compile the applet:

javac JListAndCheckBoxApplet.java

4. Run the Applet:

To run the applet, you can use the appletviewer tool (provided in older JDK versions):

appletviewer AppletExample.html

pg. 68
Expected Output:

 List of fruits: A list of fruits appears, and the user can select one.

 Checkbox: A checkbox appears at the bottom that says, "Show selected fruit in uppercase".

 When a user selects a fruit and checks the checkbox, the fruit name will be displayed in
uppercase.

 If the checkbox is unchecked, the fruit name will be shown in its original form.

 If no fruit is selected, the message "No fruit selected" is displayed.

Key Features:

 JList: Displays a list of selectable items (fruits).

 JCheckBox: Lets users toggle whether the selected fruit should be shown in uppercase.

 Applet: Uses a basic applet window to display and interact with components.

 Event Handling: Listens for events when the checkbox is checked or unchecked and updates
the display accordingly.

pg. 69

You might also like