Java Lab Manual It
Java Lab Manual It
AND TECHNOLOGY
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
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.
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
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
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.
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
pg. 3
PROGRAM 1
Write a Java program to illustrate the concept of class with method overloading
SOURCE CODE
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;
int sum = 0;
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.");
}
}
pg. 8
}
}
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:
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.
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.
pg. 15
PROGRAM 5
Write a program to explain the concept of String class, String Builder class and String
Buffer class.
SOURCE CODE
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).
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);
}
}
}
}
pg. 23
Explanation:
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.
o This class implements the Runnable interface and overrides the run() method to print
letters from 'A' to 'E'.
3. Main method:
o We create an instance of NumberPrinter and call the start() method to start the thread for
printing numbers.
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;
pg. 26
// Display final score
public synchronized void displayScore() {
System.out.println("Final Score - Runs: " + runs + ", Wickets: " + wickets);
}
}
@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;
@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);
}
}
}
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.*;
System.out.println("ArrayList Example:");
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");
arrayList.add("Grapes");
// Removing an element
arrayList.remove("Banana");
System.out.println();
pg. 31
// Example 2: Using LinkedList (List interface)
System.out.println("LinkedList Example:");
linkedList.add("Cat");
linkedList.add("Dog");
linkedList.add("Rabbit");
linkedList.add("Elephant");
linkedList.addFirst("Tiger");
linkedList.removeLast();
System.out.println();
System.out.println("HashMap Example:");
hashMap.put(1, "One");
hashMap.put(2, "Two");
hashMap.put(3, "Three");
hashMap.put(4, "Four");
pg. 32
// Print all elements (Key-Value pairs)
hashMap.remove(2);
System.out.println();
System.out.println("TreeMap Example:");
treeMap.put(10, "Ten");
treeMap.put(5, "Five");
treeMap.put(15, "Fifteen");
treeMap.put(3, "Three");
treeMap.remove(5);
System.out.println();
pg. 33
Explanation:
1. ArrayList:
o Example:
We add some fruit names to the ArrayList, remove one, and access an element by
index.
2. LinkedList:
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 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:
pg. 34
OUTPUT:
ArrayList Example:
LinkedList Example:
LinkedList after adding at the beginning: [Tiger, Cat, Dog, Rabbit, Elephant]
HashMap Example:
TreeMap Example:
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:
import java.util.*;
pg. 36
namesVector.add("Data Science");
namesVector.add("Internet of Things");
namesVector.add("Artifical Intelligence and Machine Learning");
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:
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;
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.");
}
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
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.*;
fos.write(contentBytes);
} catch (IOException e) {
e.printStackTrace();
pg. 43
int byteRead;
fileContent.append((char) byteRead);
System.out.println(fileContent.toString());
} catch (IOException e) {
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:
pg. 44
Output:
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
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:
import java.io.*;
private static final long serialVersionUID = 1L; // Unique ID to ensure class compatibility during
deserialization
// Constructor
this.name = name;
this.age = age;
// Getters
return name;
pg. 46
return age;
@Override
// Serialization method
oos.writeObject(person);
System.out.println("Serialization successful!");
} catch (IOException e) {
e.printStackTrace();
} }
// Deserialization method
return person;
e.printStackTrace();
} return null;
pg. 47
}
serializePerson(person1, filename);
if (deserializedPerson != null) {
} }
Explanation:
1. Person Class:
o The Person class implements the Serializable interface, which marks the class as eligible
for serialization.
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.
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.
Output:
Serialization successful!
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.
NOTE:
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:
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.*;
@Override
setBackground(Color.white);
addMouseListener(new MouseAdapter() {
@Override
@Override
repaint();
pg. 50
}
@Override
repaint();
} });
addMouseMotionListener(new MouseMotionAdapter() {
@Override
repaint();
});
addKeyListener(new KeyAdapter() {
@Override
@Override
repaint();
pg. 51
} });
setFocusable(true);}
@Override
g.setColor(Color.BLACK);
g.setColor(Color.BLACK);
}}
Explanation:
1. Imports:
o java.awt.event.*: Contains classes for handling various event types, including mouse and
key events.
mouseClicked: Captures mouse clicks and stores the coordinates of the click.
pg. 52
o MouseMotionListener: This listener captures mouse movements. We use an anonymous
subclass of MouseMotionAdapter.
keyPressed: Captures when a key is pressed and displays the name of the key.
4. Focusability:
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.
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>
pg. 53
</body>
</html>
1. Save the Java Code: Save the above Java code in a file named MouseKeyEventApplet.java.
javac MouseKeyEventApplet.java
3. Create the HTML File: Save the HTML code in a file named applet.html.
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:
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 SimpleCalculator() {
frame.setLayout(new BorderLayout());
pg. 55
textField.setFont(new Font("Arial", Font.BOLD, 24));
textField.setEditable(false);
frame.add(textField, BorderLayout.NORTH);
String[] buttons = {
};
button.addActionListener(new ButtonClickListener());
panel.add(button);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pg. 56
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
@Override
if (command.equals("=")) {
// Perform calculation
try {
num2 = Double.parseDouble(currentInput);
textField.setText(String.valueOf(result));
currentInput = String.valueOf(result);
operator = "";
textField.setText("Error");
currentInput = "";
operator = "";
} else if (command.equals("C")) {
// Clear everything
currentInput = "";
num1 = 0;
pg. 57
num2 = 0;
operator = "";
textField.setText("");
if (!currentInput.isEmpty()) {
num1 = Double.parseDouble(currentInput);
operator = command;
currentInput = "";
} else {
currentInput += command;
textField.setText(currentInput);
switch (operator) {
case "+":
case "-":
case "*":
pg. 58
return num1 * num2;
case "/":
if (num2 != 0) {
} else {
textField.setText("Error");
return 0;
case "%":
default:
return 0;
SwingUtilities.invokeLater(new Runnable() {
@Override
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:
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.
5. ActionListener:
o A nested class (ButtonClickListener) that listens for button clicks and performs actions
based on the button pressed:
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.
o The program clears the current input and resets the state when the clear button is pressed.
Features:
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:
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
SOURCE CODE
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.*;
ResultSet rs = null;
try {
String sql = "SELECT id, username, email FROM users WHERE email = ?";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
pg. 62
// Step 5: Process the ResultSet
while (rs.next()) {
int id = rs.getInt("id");
System.out.println("-----------------------------");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
} catch (SQLException e) {
e.printStackTrace();
pg. 63
Explanation:
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
SOURCE CODE
import java.applet.Applet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@Override
setLayout(new BorderLayout());
// Create a JCheckBox
pg. 65
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(listScrollPane, BorderLayout.CENTER);
panel.add(uppercaseCheckBox, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
uppercaseCheckBox.addItemListener(new ItemListener() {
@Override
if (selectedFruit != null) {
if (uppercaseCheckBox.isSelected()) {
showMessage(selectedFruit.toUpperCase());
} else {
showMessage(selectedFruit);
} else {
});
pg. 66
// Method to show the selected fruit in the applet's message
Graphics g = getGraphics();
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"}.
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.
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>
</body>
</html>
javac JListAndCheckBoxApplet.java
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.
Key Features:
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