0% found this document useful (0 votes)
4 views45 pages

Lab Manual for Programming Exercises

The document is a lab manual for students at City College of Management and Science, detailing mandatory items to bring, attendance policies, and lab conduct rules. It includes programming exercises in Java, covering topics such as summing integers, calculating factorials, converting between decimal and binary, checking for prime numbers, and demonstrating string functions. Additionally, it discusses creating and manipulating a 'Distance' class with methods for normalization, addition, and cloning of distance objects.

Uploaded by

ccmasacademic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views45 pages

Lab Manual for Programming Exercises

The document is a lab manual for students at City College of Management and Science, detailing mandatory items to bring, attendance policies, and lab conduct rules. It includes programming exercises in Java, covering topics such as summing integers, calculating factorials, converting between decimal and binary, checking for prime numbers, and demonstrating string functions. Additionally, it discusses creating and manipulating a 'Distance' class with methods for normalization, addition, and cloning of distance objects.

Uploaded by

ccmasacademic
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

\

CITY COLLEGE OF MANAGEMENT AND SCIENCE


SAI PRIYA NAGAR, 3RD LANE, RAYAGADA-765001

LAB MANUAL

LAB NAME: ______________________________________________________

LAB CODE______________________________________________________
YEAR_________________________ SEMESTER______________________

Name of Faculty______________________________________________________________________________________
INSTRUCTIONS TO STUDENTS
Before entering the lab the student should carry the following things (MANDATORY)
1. Identity card issued by the college.
2. Class notes
3. Lab observation book
4. Lab Manual
5. Lab Record
 Student must sign in and sign out in the register provided when attending the lab session without fail.
 Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed to
attend the lab.
 Students need to maintain 100% attendance in lab if not a strict action will be taken.
 All students must follow a Dress Code while in the laboratory
 All bags must be left at the indicated place.
 Refer to the lab staff if you need any help in using the lab.
 Respect the laboratory and its other users.
 Workspace must be kept clean and tidy after experiment is completed.
 Read the Manual carefully before coming to the laboratory and be sure about what you are supposed
to do. Do the experiments as per the instructions given in the manual.
 Copy all the programs to observation which are taught in class before attending the lab session.
 Students are not supposed to use floppy disks, pen drives without permission of lab- in charge.
 Lab records need to be submitted on or before the date of submission.
1. To find the sum of any number of integers entered as command line arguments.

//Sum of Integers from Command Line Arguments


public class SumIntegers {
public static void main(String[] args) {
int sum = 0;

// Loop through each argument


for (String arg : args) {
try {
// Convert the argument to an integer
int number = [Link](arg);
sum += number;
} catch (NumberFormatException e) {
// Handle the case where the argument is not a valid integer
[Link]("Invalid input: " + arg + " is not an integer.");
}
}
[Link]("Sum of the integers: " + sum);
}
}

How to Run This Program


1. Save the file as [Link]
2. Compile it:
3. javac [Link]
4. Run it with arguments:
5. java SumIntegers 10 20 30

Output:
Sum of the integers: 60
If a non-integer argument is included:
java SumIntegers 10 abc 5

Output:
Invalid input: abc is not an integer.
Sum of the integers: 15
2. To find the factorial of a given number.

// Factorial of a Given Number (Using Scanner)


import [Link];

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a non-negative integer: ");
int num = [Link]();
if (num < 0) {
[Link]("Factorial is not defined for negative numbers.");
} else {
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
[Link]("Factorial of " + num + " is: " + factorial);
}
[Link]();
}
}
//Factorial Using Command-Line Argument
public class FactorialCLI {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a number as a command-line argument.");
return;
} try {
int num = [Link](args[0]);

if (num < 0) {
[Link]("Factorial is not defined for negative numbers.");
} else {
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
[Link]("Factorial of " + num + " is: " + factorial);
}
} catch (NumberFormatException e) {
[Link]("Invalid input. Please enter a valid integer.");
}
}
}
To Run (Command-Line Version):
javac [Link]
java FactorialCLI 5
Output: Factorial of 5 is: 120
3. To convert a decimal to binary number.

//Decimal to Binary (Using Scanner)


import [Link];
public class DecimalToBinary {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a decimal number: ");
int decimal = [Link]();

String binary = [Link](decimal);


[Link]("Binary representation: " + binary);

[Link]();
}
}
To Run Command-Line Version:
javac [Link]
java DecimalToBinaryCLI 25
Output: Binary representation: 11001
4. Conversion from binary back to decimal

//Convert Between Decimal and Binary (Both Ways) Using Scanner for User Input

import [Link];

public class NumberConverter {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Choose conversion:");
[Link]("1. Decimal to Binary");
[Link]("2. Binary to Decimal");
[Link]("Enter your choice (1 or 2): ");
int choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter a decimal number: ");
int decimal = [Link]();
String binary = [Link](decimal);
[Link]("Binary representation: " + binary);
break;

case 2:
[Link]("Enter a binary number: ");
String binaryInput = [Link]();
try {
int decimalValue = [Link](binaryInput, 2);
[Link]("Decimal value: " + decimalValue);
} catch (NumberFormatException e) {
[Link]("Invalid binary number.");
}
break;

default:
[Link]("Invalid choice.");
}
[Link]();
}
}
Example Runs:
Case 1: Decimal to Binary
Enter your choice (1 or 2): 1
Enter a decimal number: 10
Binary representation: 1010
Case 2: Binary to Decimal
Enter your choice (1 or 2): 2
Enter a binary number: 1010
Decimal value: 10
5. To check if a number is prime or not, by taking the number as input from the keyboard.

//Check if a Number is Prime


import [Link];

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a positive integer: ");
int number = [Link]();

if (number <= 1) {
[Link](number + " is not a prime number.");
} else {
boolean isPrime = true;
// Only need to check up to the square root of the number
for (int i = 2; i <= [Link](number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}
}
[Link]();
}
}
Example Output:
Case 1: Prime
Enter a positive integer: 7
7 is a prime number.
Case 2: Not Prime
Enter a positive integer: 10
10 is not a prime number.
6. To find the sum of any number of integers interactively, i.e., entering every number from the
keyboard, whereas the total number of integers is given as a command line argument.

//Sum of N Integers (Size from Command-Line, Values from Keyboard)


import [Link];

public class InteractiveSum {


public static void main(String[] args) {
// Check if command-line argument is provided
if ([Link] == 0) {
[Link]("Please provide the number of integers as a command-line argument.");
return;
}
int count;
try {
count = [Link](args[0]);
} catch (NumberFormatException e) {
[Link]("Invalid number format. Please enter a valid integer as an argument.");
return;
}
if (count <= 0) {
[Link]("The number of integers should be greater than 0.");
return;
}
Scanner scanner = new Scanner([Link]);
int sum = 0;

for (int i = 1; i <= count; i++) {


[Link]("Enter number " + i + ": ");
try {
int number = [Link]();
sum += number;
} catch (Exception e) {
[Link]("Invalid input. Please enter an integer.");
[Link](); // clear invalid input
i--; // retry current number
}
}
[Link]("Sum of the entered numbers: " + sum);
[Link]();
}
}

Running the Program


Compile:
javac [Link]
Run with 3 numbers:
java InteractiveSum 3
Console Output:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 5
Sum of the entered numbers: 35
7. Write a program that show working of different functions of String and String Buffer classs like
set Char At( ), set Length( ), append( ), insert( ), concat( )and equals( ).
//Demonstrating String and StringBuffer Methods
public class StringFunctionsDemo {
public static void main(String[] args) {
[Link]("=== String Class Methods ===");
String str1 = "Hello";
String str2 = "World";
String str3 = [Link](" ").concat(str2);
[Link]("Concatenated String: " + str3); // Hello World
[Link]("str1 equals str2? " + [Link](str2)); // false
[Link]("str1 equals 'Hello'? " + [Link]("Hello")); // true
[Link]("\n=== StringBuffer Class Methods ===");
StringBuffer sb = new StringBuffer("Java Programming");
[Link](5, '-');
[Link]("After setCharAt(5, '-'): " + sb); // Java -rogramming
[Link](10);
[Link]("After setLength(10): " + sb); // Java -prog
[Link](" Language");
[Link]("After append(\" Language\"): " + sb); // Java -prog Language
[Link](5, "is fun ");
[Link]("After insert(5, \"is fun \"): " + sb); // Java is fun -prog Language
}
}
Sample Output
=== String Class Methods ===
Concatenated String: Hello World
str1 equals str2? false
str1 equals 'Hello'? true
=== StringBuffer Class Methods ===
After setCharAt(5, '-'): Java -rogramming
After setLength(10): Java -prog
After append(" Language"): Java -prog Language
After insert(5, "is fun "): Java is fun -prog Language

Notes:
 String is immutable, so methods like setCharAt() and setLength() are not available.
 StringBuffer is mutable, ideal when you want to modify strings in-place.
 If you're using Java 1.5 or later, consider using StringBuilder for faster single-threaded operations
8. Write a program to create a – “distance” class with methods where distance is computed in
terms of feet and inches, how to create objects of a class and to see the use of this pointer.
//Distance Class with this Keyword
class Distance {
private int feet;
private int inches;

// Method to set distance using this pointer


public void setDistance(int feet, int inches) {
[Link] = feet;
[Link] = inches;
normalize();
}
// Normalize inches > 12 into feet
private void normalize() {
if ([Link] >= 12) {
[Link] += [Link] / 12;
[Link] = [Link] % 12;
}
}
// Method to add two Distance objects and return result
public Distance add(Distance d) {
Distance result = new Distance();
[Link] = [Link] + [Link];
[Link] = [Link] + [Link];
[Link]();
return result;
}
// Method to display the distance
public void display() {
[Link]([Link] + " feet " + [Link] + " inches");
}
}
public class DistanceDemo {
public static void main(String[] args) {
// Create objects of Distance class
Distance d1 = new Distance();
Distance d2 = new Distance();

// Set distances
[Link](5, 8); // 5 feet 8 inches
[Link](3, 11); // 3 feet 11 inches

// Display the original distances


[Link]("Distance 1:");
[Link]();

[Link]("Distance 2:");
[Link]();

// Add two distances


Distance d3 = [Link](d2);
[Link]("Sum of distances:");
[Link]();
}
}
Output
Distance 1:
5 feet 8 inches
Distance 2:
3 feet 11 inches
Sum of distances:
9 feet 7 inches

 [Link] and [Link]: Used to distinguish between instance variables and parameters.
 normalize(): Converts inches ≥ 12 to feet.
 add(Distance d): Adds two Distance objects and returns a new object.
 display(): Prints distance in a user-friendly format.
9. Modify the – “distance” class by creating constructor for assigning values (feet and inches) to the
distance object. Create another object and assign second object as reference variable to another
object reference variable. Further create a third object which is a clone of the first object.

//Distance Class with Constructor, Reference Assignment, and Cloning


class Distance {
private int feet;
private int inches;

// Constructor to initialize feet and inches


public Distance(int feet, int inches) {
[Link] = feet;
[Link] = inches;
normalize();
}
// Normalize inches into feet if inches >= 12
private void normalize() {
if ([Link] >= 12) {
[Link] += [Link] / 12;
[Link] = [Link] % 12;
}
}
// Display method
public void display() {
[Link]([Link] + " feet " + [Link] + " inches");
}
// Clone method (manual deep copy)
public Distance clone() {
return new Distance([Link], [Link]);
}
}
public class DistanceTest {
public static void main(String[] args) {
// 1. Create first object using constructor
Distance d1 = new Distance(5, 14); // Normalizes to 6 feet 2 inches
[Link]("Original d1:");
[Link]();

// 2. Reference assignment: d2 refers to the same object as d1


Distance d2 = d1;
[Link]("Reference copy d2 (same as d1):");
[Link]();

// 3. Cloning: Create a separate object d3 with same values


Distance d3 = [Link]();
[Link]("Cloned object d3 (deep copy of d1):");
[Link]();
}
}
Sample Output
Original d1:
6 feet 2 inches
Reference copy d2 (same as d1):
6 feet 2 inches
Cloned object d3 (deep copy of d1):
6 feet 2 inches

Explained
 Constructor: Distance(int feet, int inches) initializes the object when it's created.
 Reference Assignment: Distance d2 = d1; means both variables point to the same object.
 Cloning: clone() method returns a new object with the same values (deep copy).
 Normalization: Converts values like 5 feet 14 inches → 6 feet 2 inches.
10. Write a program to show that during function overloading, if no matching argument is found,
then Java will apply automatic type conversions (from lower to higher data type).

//Function Overloading and Automatic Type Conversion


class OverloadingExample {

// Overloaded method with int parameter


public void display(int num) {
[Link]("Integer argument: " + num);
}
// Overloaded method with float parameter
public void display(float num) {
[Link]("Float argument: " + num);
}
// Overloaded method with double parameter
public void display(double num) {
[Link]("Double argument: " + num);
}
// Overloaded method with long parameter
public void display(long num) {
[Link]("Long argument: " + num);
}
}
public class OverloadingTest {
public static void main(String[] args) {
OverloadingExample obj = new OverloadingExample();

// Calling method with different argument types


[Link](10); // Matches int (exact match)
[Link](10L); // Matches long (exact match)
[Link](10.5f); // Matches float (exact match)
[Link](10.5); // Matches double (exact match)

// Automatic type conversion examples


[Link](100); // int is converted to long automatically
[Link](3.14f); // float is converted to double automatically
}
}
Sample Output
Integer argument: 10
Long argument: 10
Float argument: 10.5
Double argument: 10.5
Long argument: 100
Double argument: 3.14
Key Concepts:
 Overloaded Methods: Methods with the same name but different parameter types (e.g., int, float, double).
 Automatic Type Conversion (Widening):
o If an argument passed is a smaller data type (e.g., int), Java automatically converts it to a larger data
type (e.g., long, float, double).
o This occurs when there's no exact match, but Java can widen the type automatically to match the
method signature.

Example of Type Conversion:


 [Link](100): The int (100) is automatically converted to long when calling the display(long num)
method.
 [Link](3.14f): The float value is automatically converted to double when calling the display(double
num) method.
11. Write a program to show the difference between public and private access specifiers. The
program should also show that primitive data types are passed by value and objects are passed
by reference and to learn use of final keyword.

In Java, the public and private access specifiers determine the accessibility of class members (variables and
methods). Here's what each one does:
 public: The member is accessible from any other class.
 private: The member is only accessible within the same class; it cannot be accessed from outside the class.
Additionally, Java uses pass-by-value for primitive data types and pass-by-reference for objects. The final keyword
is used to declare constants, prevent method overriding, or prevent inheritance of a class.
Let's create a program that demonstrates all of these concepts:

//public, private, pass-by-value, pass-by-reference, and final keyword


class AccessSpecifierDemo {

// Public member (can be accessed from any other class)


public int publicVar = 10;

// Private member (can only be accessed within the same class)


private int privateVar = 20;

// Final variable (cannot be modified after initialization)


public final int finalVar = 30;

// Public method to access private member


public void setPrivateVar(int value) {
[Link] = value;
}
// Method demonstrating pass-by-value with primitive data type
public void modifyPrimitive(int num) {
num = 100; // This will not affect the original variable outside the method
}
// Method demonstrating pass-by-reference with objects
public void modifyObject(AccessSpecifierDemo obj) {
[Link] = 500; // This will modify the object passed from outside
}
// Method to display values
public void display() {
[Link]("Public Variable: " + publicVar);
[Link]("Private Variable: " + privateVar);
[Link]("Final Variable: " + finalVar);
}
}
public class AccessSpecifierTest {
public static void main(String[] args) {
// Creating an object of AccessSpecifierDemo class
AccessSpecifierDemo obj = new AccessSpecifierDemo();
// Accessing and modifying public variable
[Link] = 50;

// Accessing private variable through a public method


[Link](80);

// Display values
[Link]("Before modifying values:");
[Link]();

// Demonstrating pass-by-value with primitive data type


int num = 10;
[Link]("\nBefore modifying primitive data:");
[Link]("Original primitive value: " + num);
[Link](num); // This will not change the original variable
[Link]("After modifying primitive value: " + num); // Remains the same

// Demonstrating pass-by-reference with object


[Link]("\nBefore modifying object:");
[Link]("Original publicVar value: " + [Link]);
[Link](obj); // This will change the publicVar of the object
[Link]("After modifying object publicVar: " + [Link]); // Value is changed
}
}

Output
Before modifying values:
Public Variable: 50
Private Variable: 80
Final Variable: 30

Before modifying primitive data:


Original primitive value: 10
After modifying primitive value: 10

Before modifying object:


Original publicVar value: 50
After modifying object publicVar: 500
Access Specifiers:
 public: The variable publicVar is accessible from any other class.
 private: The variable privateVar can only be accessed within the same class. We access it through the public
method setPrivateVar().
Pass-by-Value (Primitive Types):
 When you pass a primitive data type (like int) to a method, Java passes a copy of the value (not the original
variable).
 Example: In the modifyPrimitive(int num) method, changing num inside the method does not affect the
original variable num outside the method.
Pass-by-Reference (Objects):
 When you pass an object to a method, Java passes the reference (memory address) of the object, not a
copy of the object. This allows the method to modify the original object.
 Example: In the modifyObject(AccessSpecifierDemo obj) method, modifying [Link] affects the obj
object in the main method.
The final Keyword:
 final variable: The finalVar variable is initialized once and cannot be modified later.
 final method: If a method is marked final, it cannot be overridden by subclasses.
 final class: If a class is declared final, it cannot be inherited.
12. Write a program to show the use of static functions and to pass variable length arguments in a
function.

In Java, static functions (also called static methods) belong to the class rather than to any specific object instance,
meaning they can be invoked without creating an object of the class. Static methods are often used for utility
functions or operations that don't depend on instance variables.
Variable length arguments (varargs) allow a method to accept zero or more arguments of a specified type. This is
done using ... (ellipsis) syntax in the method definition. Below program that demonstrates both static functions and
variable-length arguments.

//Static Functions and Variable Length Arguments


class MathUtility {

// Static method to find the sum of variable-length arguments


public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Static method to find the product of variable-length arguments
public static int product(int... numbers) {
int total = 1;
for (int num : numbers) {
total *= num;
}
return total;
}
// Static method to display the given numbers
public static void displayNumbers(int... numbers) {
[Link]("Numbers: ");
for (int num : numbers) {
[Link](num + " ");
}
[Link]();
}
}
public class StaticAndVarargsDemo {
public static void main(String[] args) {
// Calling static methods without creating an object of MathUtility class
[Link]("Sum of 2, 4, 6, 8: " + [Link](2, 4, 6, 8));
[Link]("Sum of 10, 20: " + [Link](10, 20));
[Link]("Sum of no arguments: " + [Link]());

[Link]("Product of 1, 2, 3, 4: " + [Link](1, 2, 3, 4));


[Link]("Product of 5, 10: " + [Link](5, 10));

// Demonstrating display function with variable-length arguments


[Link](1, 2, 3, 4, 5);
[Link](100, 200);
[Link](); // No arguments
}
}
Sample Output
Sum of 2, 4, 6, 8: 20
Sum of 10, 20: 30
Sum of no arguments: 0
Product of 1, 2, 3, 4: 24
Product of 5, 10: 50
Numbers: 1 2 3 4 5
Numbers: 100 200
Numbers:

Static Functions:
 The methods sum, product, and displayNumbers are static, meaning they are associated with the class
(MathUtility), not an instance of the class.
 Static methods are called using the class name: [Link](), [Link](), and
[Link]().
Variable-Length Arguments (Varargs):
 The method signature public static int sum(int... numbers) means it can accept any number of int arguments
(including zero).
 Similarly, public static void displayNumbers(int... numbers) can handle zero or more int arguments.
 Inside the method, the numbers parameter is treated as an array.
Notes:
 Static Methods: You can call a static method directly using the class name, and it can access only static
members (variables/methods).
 Varargs: You can pass a specific number of arguments or no arguments at all to the method. Java
automatically handles the conversion of the passed arguments into an array.
14. Write a program to demonstrate the concept of boxing and unboxing.

In Java, boxing and unboxing refer to the automatic conversion between primitive types and their corresponding
wrapper classes (objects).
 Boxing: The process of converting a primitive type to its corresponding wrapper class (e.g., int to Integer).
 Unboxing: The process of converting an object of a wrapper class back to its corresponding primitive type
(e.g., Integer to int).
Java provides autoboxing and autounboxing to automatically handle these conversions when you work with
primitive types and wrapper classes.

//Program to Demonstrate Boxing and Unboxing


public class BoxingUnboxingDemo {
public static void main(String[] args) {
// Boxing: Converting primitive int to Integer (autoboxing)
int primitiveInt = 10;
Integer boxedInteger = primitiveInt; // Autoboxing: int -> Integer
[Link]("Boxed Integer: " + boxedInteger);

// Unboxing: Converting Integer to primitive int (autounboxing)


Integer anotherBoxedInteger = new Integer(20);
int unboxedInt = anotherBoxedInteger; // Autounboxing: Integer -> int
[Link]("Unboxed int: " + unboxedInt);

// Boxing with other primitive types


double primitiveDouble = 10.5;
Double boxedDouble = primitiveDouble; // Autoboxing: double -> Double
[Link]("Boxed Double: " + boxedDouble);

// Unboxing with other primitive types


Double anotherBoxedDouble = new Double(25.75);
double unboxedDouble = anotherBoxedDouble; // Autounboxing: Double -> double
[Link]("Unboxed double: " + unboxedDouble);

// Demonstrating auto-unboxing in a collection


Integer[] integerArray = new Integer[]{1, 2, 3, 4};
int sum = 0;
for (Integer number : integerArray) {
sum += number; // Unboxing happens here automatically
}
[Link]("Sum of Integer array: " + sum);
} }
Sample Output
Boxed Integer: 10
Unboxed int: 20
Boxed Double: 10.5
Unboxed double: 25.75
Sum of Integer array: 10
Boxing (Autoboxing):
 Autoboxing occurs when a primitive type (like int, double, etc.) is automatically converted into its
corresponding wrapper class (Integer, Double, etc.).
 In the example, primitiveInt (of type int) is automatically converted to Integer when assigned to
boxedInteger.
Unboxing (Autounboxing):
 Autounboxing occurs when a wrapper class object is automatically converted back to its corresponding
primitive type.
 In the example, anotherBoxedInteger (of type Integer) is automatically converted back to a primitive int
when assigned to unboxedInt.
Using Collections:
 Autoboxing and autounboxing also work with collections like ArrayList, Integer[], etc. In the example, when
we loop through the Integer[] array, the Integer objects are automatically unboxed to int during the
summation.
Notes:
 Wrapper Classes: Each primitive type in Java has a corresponding wrapper class:
o int → Integer
o char → Character
o double → Double
o boolean → Boolean
o And so on...
 Autoboxing and Autounboxing make it easier to work with collections (like ArrayList<Integer>) and other
scenarios where objects are required instead of primitives.
15. Create a multi-file program where in one file a string message is taken as input from the user and
the function to display the message on the screen is given in another file (make use of Scanner
package in this program).

1. One file takes a string message as input from the user using the Scanner class.
2. Another file contains the function that displays the message on the screen.
Steps:
1. Create two Java files:
o [Link]: This will handle user input using the Scanner class.
o [Link]: This will contain a method to display the message.
1. [Link]: Takes input from the user
import [Link];

public class MessageInput {


public static void main(String[] args) {
// Create Scanner object to take input
Scanner scanner = new Scanner([Link]);

// Prompt user for input


[Link]("Enter a message: ");
String message = [Link](); // Read the input message

// Call the displayMessage function from the MessageDisplay class


MessageDisplay display = new MessageDisplay();
[Link](message);
}
}
2. [Link]: Contains the function to display the message
public class MessageDisplay {
// Function to display the message
public void displayMessage(String message) {
[Link]("The message is: " + message);
}
}

Compiling and Running the Program


1. Save these files in the same directory:
o [Link]
o [Link]
2. Compile the Java files:
Open the terminal or command prompt, navigate to the folder where the files are saved, and run:
3. javac [Link] [Link]
4. Run the program:
After compiling, run the MessageInput class:
5. java MessageInput
6. Sample Output:
Enter a message: Hello, this is a multi-file program!
The message is: Hello, this is a multi-file program!
How the program works:
1. [Link]:
o Imports the Scanner class for taking user input.
o Reads the input message from the user.
o Creates an object of the MessageDisplay class and calls the displayMessage method, passing the
input message as an argument.
2. [Link]:
o Contains the displayMessage method that simply prints the received message.

 Scanner class: Used for taking input from the user in [Link].
 Multi-file structure: The program is divided into two classes (MessageInput for input and MessageDisplay
for displaying the message).
 Method calling: The MessageInput class calls the displayMessage method from MessageDisplay to display
the message.
16. Write a program to create a multilevel package and also creates a reusable class to generate
Fibonacci series, where the function to generate Fibonacci series is given in a different file
belonging to the same package.

In Java, packages are used to group related classes, interfaces, and sub-packages. A multilevel package consists of a
hierarchy of packages, where a package can contain sub-packages, which in turn can contain more sub-packages.
To demonstrate this, we'll create:
1. A multilevel package structure.
2. A reusable class for generating the Fibonacci series, with the function to generate the series in a different
file belonging to the same package.

Package Structure:
We'll create the following multilevel package structure:
com
└── fib
└── util
└── [Link]
└── [Link]
Steps:
1. Create the main class [Link] in the [Link] package to call the Fibonacci generation function.
2. Create the reusable class [Link] in the [Link] package, which contains the function
to generate the Fibonacci series.
1. [Link] (located in com/fib/util/)
package [Link];

public class FibonacciGenerator {

// Function to generate Fibonacci series up to 'n' numbers


public void generateFibonacci(int n) {
int a = 0, b = 1, c;

[Link]("Fibonacci Series: ");


if (n >= 1) [Link](a + " ");
if (n >= 2) [Link](b + " ");

for (int i = 3; i <= n; i++) {


c = a + b;
[Link](c + " ");
a = b;
b = c;
}
[Link](); // Move to the next line after printing the series
}
}
2. [Link] (located in com/fib/)
package [Link];

import [Link]; // Importing the FibonacciGenerator class

public class FibonacciApp {

public static void main(String[] args) {


// Create an object of FibonacciGenerator class
FibonacciGenerator generator = new FibonacciGenerator();

// Generate Fibonacci series of first 10 numbers


[Link](10);

// Generate Fibonacci series of first 15 numbers


[Link](15);
}
}
Compiling and Running the Program
1. Create the directory structure:
You need to create the directory structure to match the package hierarchy:
2. mkdir -p com/fib/util
3. Save the files:
o Save [Link] in the com/fib/util/ directory.
o Save [Link] in the com/fib/ directory.
4. Compile the files:
Open the terminal/command prompt and navigate to the parent directory of com/ (where the com folder is
located). Then run:
5. javac com/fib/util/[Link] com/fib/[Link]
6. Run the program:
Once the program is compiled, run it by using the following command:
7. java [Link]
Sample Output
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

How the program works:


1. [Link] (in [Link] package):
o This class contains a method generateFibonacci(int n) that generates the Fibonacci series up to n
numbers.
o It uses a simple loop to generate the Fibonacci numbers, starting with 0 and 1, and then summing
the previous two numbers to generate the next one.
2. [Link] (in [Link] package):
o This is the main class that creates an object of the FibonacciGenerator class and calls the
generateFibonacci method to display the Fibonacci series.
o It imports FibonacciGenerator from the [Link] package using the import statement.

Multilevel Package:
 We created a multilevel package structure with [Link] containing the FibonacciGenerator class, and
[Link] containing the main class FibonacciApp.
Reusable Class:
 The FibonacciGenerator class is designed to be reusable. It contains a method generateFibonacci(int n) that
can be called with any number of terms to generate the Fibonacci series.
Package Import:
 In the [Link] class, we imported the FibonacciGenerator class from the [Link] package
using the import statement.

Notes:
 Package Declaration: Each file starts with a package declaration, which must match the directory structure.
 Class Organization: Organizing code into different packages makes it more modular, and allows reusability.
In this case, the Fibonacci generation logic is separate from the main application logic.
17. Write a program that creates illustrates different levels of protection in classes/subclasses
belonging to same package or different packages

Access modifiers define the level of protection or visibility for classes, methods, variables, and constructors. These
modifiers are:
1. public: Accessible from anywhere.
2. protected: Accessible within the same package and by subclasses (including those in different packages).
3. default (no modifier): Accessible only within the same package.
4. private: Accessible only within the same class.
Objective: The goal of this program is to illustrate how different levels of access protection work in classes and
subclasses both within the same package and across different packages.
Steps:
1. Create multiple classes to demonstrate different levels of protection.
o A base class with different access modifiers.
o A subclass in the same package and a subclass in a different package.
2. Show how public, protected, default, and private modifiers affect access from within the same package and
from subclasses in different packages.

1. Package Structure:
 [Link]:
o [Link] (This will have different access modifiers).
o [Link] (Subclass in the same package).
 [Link]:
o [Link] (Subclass in a different package).

2. [Link] (Located in com/protection/)


package [Link];

public class BaseClass {

// Public: Can be accessed from anywhere


public String publicField = "Public Field";

// Protected: Can be accessed within the same package or by subclasses in any package
protected String protectedField = "Protected Field";

// Default (no modifier): Can be accessed only within the same package
String defaultField = "Default Field";

// Private: Can be accessed only within this class


private String privateField = "Private Field";

public void display() {


[Link]("BaseClass display method");
}

// Getter for private field


public String getPrivateField() {
return privateField;
}
}

3. [Link] (Located in com/protection/)


package [Link];

public class SamePackageSubclass extends BaseClass {

public void accessFields() {


// Can access public field
[Link]("Accessing publicField: " + publicField);

// Can access protected field because it's within the same package
[Link]("Accessing protectedField: " + protectedField);

// Can access default field because it's within the same package
[Link]("Accessing defaultField: " + defaultField);

// Cannot access private field directly (private is for the class itself)
// [Link]("Accessing privateField: " + privateField); // Error

// But can access private field using a getter


[Link]("Accessing privateField via getter: " + getPrivateField());
}
}
4. [Link] (Located in com/protection/sub/)
package [Link];

import [Link];

public class DifferentPackageSubclass extends BaseClass {

public void accessFields() {


// Can access public field
[Link]("Accessing publicField: " + publicField);

// Can access protected field because it's a subclass


[Link]("Accessing protectedField: " + protectedField);

// Cannot access default field because it's in a different package


// [Link]("Accessing defaultField: " + defaultField); // Error

// Cannot access private field directly (private is for the class itself)
// [Link]("Accessing privateField: " + privateField); // Error

// But can access private field using a getter (from BaseClass)


[Link]("Accessing privateField via getter: " + getPrivateField());
}
}
5. [Link] (Main class, located in com/protection/)
package [Link];

import [Link];

public class TestAccessModifiers {

public static void main(String[] args) {


// Create object of SamePackageSubclass
SamePackageSubclass samePackageSubclass = new SamePackageSubclass();
[Link]("In SamePackageSubclass:");
[Link]();

[Link]();

// Create object of DifferentPackageSubclass


DifferentPackageSubclass differentPackageSubclass = new DifferentPackageSubclass();
[Link]("In DifferentPackageSubclass:");
[Link]();
}
}
Compiling and Running the Program
1. Create the directory structure:
2. mkdir -p com/protection
3. mkdir -p com/protection/sub
4. Save the files:
o Save [Link], [Link], and [Link] in the
com/protection/ directory.
o Save [Link] in the com/protection/sub/ directory.
5. Compile the classes:
Navigate to the parent directory of com/ and run:
6. javac com/protection/*.java com/protection/sub/*.java
7. Run the program:
Run the main class:
8. java [Link]
Sample Output
In SamePackageSubclass:
Accessing publicField: Public Field
Accessing protectedField: Protected Field
Accessing defaultField: Default Field
Accessing privateField via getter: Private Field

In DifferentPackageSubclass:
Accessing publicField: Public Field
Accessing protectedField: Protected Field
Accessing privateField via getter: Private Field

How the Program Works:


1. BaseClass:
o This class contains fields with various access levels (public, protected, default, private).
o It also includes a getter method for the privateField to demonstrate how private fields can be
accessed outside their class.
2. SamePackageSubclass:
o This class is in the same package as BaseClass.
o It can access public, protected, and default fields directly.
o It cannot access private fields directly but can access them through a public getter method.
3. DifferentPackageSubclass:
o This class is in a different package than BaseClass.
o It can access public and protected fields.
o It cannot access default fields, as they are package-private.
o It also cannot access private fields, but it can access them via the getter method.
4. TestAccessModifiers: This is the main class that creates objects of both subclasses (SamePackageSubclass
and DifferentPackageSubclass) and calls their methods to access fields.

 public: Accessible everywhere.


 protected: Accessible within the same package and by subclasses (even if they are in different packages).
 default: Accessible only within the same package.
 private: Accessible only within the same class, but can be accessed using public getter methods.
Notes:
 Inheritance and Access: Subclasses can access protected fields and methods, but only the class itself can
access private fields.
 Different Packages: default access is not visible outside the package, while protected is accessible to
subclasses even in different packages.

18. Write a program – “Divide By Zero” that takes two numbers a and b as input, computes a/b, and
invokes Arithmetic Exception to generate a message when the denominator is zero.

In this program, we will:


1. Take two numbers a (numerator) and b (denominator) as input from the user.
2. Compute the division a/b.
3. Handle the scenario where the denominator b is zero by throwing an ArithmeticException, which will
invoke a message that indicates a division by zero error.
Steps:
1. We will use the Scanner class to take input from the user.
2. Use a try-catch block to handle the ArithmeticException when trying to divide by zero.
Program: "Divide By Zero"
import [Link];

public class DivideByZero {

public static void main(String[] args) {


// Create a Scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Taking inputs for the two numbers


[Link]("Enter the numerator (a): ");
int a = [Link]();

[Link]("Enter the denominator (b): ");


int b = [Link]();
try {
// Attempt to divide a by b
int result = a / b;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Catch the ArithmeticException (i.e., division by zero)
[Link]("Error: Division by zero is not allowed.");
} finally {
// This block is executed whether or not an exception occurs
[Link]("Execution finished.");
[Link](); // Close the scanner
}
}
}
Sample Output 1 (When no error occurs):
Enter the numerator (a): 10
Enter the denominator (b): 2
Result: 5
Execution finished.
Sample Output 2 (When division by zero occurs):
Enter the numerator (a): 10
Enter the denominator (b): 0
Error: Division by zero is not allowed.
Execution finished.

Explanation:
1. Scanner for Input:
o We use the Scanner class to take input from the user for both the numerator a and denominator b.
2. try-catch Block:
o The division operation a / b is wrapped inside a try block.
o If b is 0, an ArithmeticException will be thrown, and the code inside the catch block will execute,
printing the error message: Error: Division by zero is not allowed.
3. finally Block:
o The finally block is always executed, regardless of whether an exception was thrown or not. It
ensures the scanner resource is closed, avoiding potential resource leaks.

Compiling and Running the Program


1. Save the file as [Link].
2. Compile the file:
3. javac [Link]
4. Run the program:
5. java DivideByZero

1. Exception Handling: We used try-catch to handle the ArithmeticException when attempting to divide by
zero.
2. finally block: This block is always executed after the try and catch blocks, making it a good place to close
resources like the Scanner.
3. User Input: We used the Scanner class to get input from the user for a and b.
Notes:
 ArithmeticException is a runtime exception, meaning you don’t have to explicitly declare it in the method
signature.
 finally block ensures that necessary cleanup is done (in this case, closing the Scanner) even if an exception
occurs.

19. Write a program to show the use of nested try statements that emphasizes the sequence of
checking for catch handler statements.

In Java, nested try-catch blocks allow you to handle multiple levels of exceptions, where a try block is nested inside
another try block. This can be useful when you want to handle different exceptions at different levels of your code
and have more control over specific error situations.
Objective: We will write a program that demonstrates the use of nested try-catch blocks. The program will simulate
different types of exceptions (such as ArithmeticException and ArrayIndexOutOfBoundsException) and show how
the order of checking catch handlers works.
Steps:
1. The outer try block will handle a potential ArithmeticException.
2. The inner try block will attempt an operation that could throw an ArrayIndexOutOfBoundsException.
3. The catch handlers will show how Java first checks for exceptions in the innermost block before checking
outer blocks.

Program: Nested Try Statements


public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
[Link]("Outer try block starts");

try {
// Inner try block
[Link]("Inner try block starts");

// Simulate an ArithmeticException
int result = 10 / 0; // This will throw ArithmeticException
[Link]("Result: " + result);

// Simulate ArrayIndexOutOfBoundsException (this will not be reached)


int[] array = new int[5];
[Link](array[10]); // This will throw ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {
// This catch handles ArrayIndexOutOfBoundsException in the inner try block
[Link]("Caught ArrayIndexOutOfBoundsException in inner catch: " + [Link]());
}

} catch (ArithmeticException e) {
// This catch handles ArithmeticException in the outer try block
[Link]("Caught ArithmeticException in outer catch: " + [Link]());
} finally {
// This block will execute regardless of whether an exception occurred
[Link]("Finally block executed");
}
}
}
Explanation:
1. Outer Try Block: The outer try block encloses the inner try block and handles exceptions like
ArithmeticException.
2. Inner Try Block: The inner try block attempts to execute two statements:
o The first one causes an ArithmeticException by dividing by zero.
o The second one attempts to access an out-of-bounds index in an array, which would throw an
ArrayIndexOutOfBoundsException.
3. Catch Blocks:
o The ArrayIndexOutOfBoundsException is caught inside the inner catch block.
o The ArithmeticException is caught inside the outer catch block.
4. Finally Block: Regardless of whether an exception occurs, the finally block is executed to indicate that it is
always executed after the try-catch blocks.
How Exceptions Are Handled:
 Java checks the inner try block first for exceptions. If an exception occurs inside the inner block, it first
checks for the appropriate catch block inside the inner try-catch.
 If no exception occurs in the inner block, the outer catch blocks are considered.
 If both try blocks throw exceptions, the first matching catch block (from the innermost try) will handle the
exception.
Compiling and Running the Program:
1. Save the file as [Link].
2. Compile the program:
3. javac [Link]
4. Run the program:
5. java NestedTryExample
Sample Output 1 (When ArithmeticException occurs):
Outer try block starts
Inner try block starts
Caught ArithmeticException in outer catch: / by zero
Finally block executed
Sample Output 2 (When ArrayIndexOutOfBoundsException occurs in the inner try block):
Outer try block starts
Inner try block starts
Caught ArrayIndexOutOfBoundsException in inner catch: Index 10 out of bounds for length 5
Finally block executed
Sample Output 3 (When no exception occurs): If we modify the program slightly to avoid exceptions (for
demonstration purposes):
int result = 10 / 2; // No exception
int[] array = new int[5];
[Link](array[4]); // Valid index, no exception
The output would be:
Outer try block starts
Inner try block starts
Result: 5
Finally block executed

 Nested try-catch: Java allows the use of nested try-catch blocks to handle multiple levels of exceptions.
 Sequence of exception handling: Java first checks the innermost catch block before moving outward. If an
exception occurs inside a nested block, it is handled by the nearest matching catch block.
 Finally block: The finally block is always executed, regardless of whether an exception occurs.

20. Write a program to create your own exception types to handle situation specific to your
application (Hint: Define a subclass of Exception which itself is a subclass of Throwable).
In Java, you can create your own custom exception by subclassing the Exception class (or any other class that is a
subclass of Throwable). This allows you to define exception types that are specific to the needs of your application.
Objective: We will write a program where we define a custom exception to handle a specific scenario. For this
example, we’ll create a custom exception to handle an invalid withdrawal amount in a simple bank account
application. If a user tries to withdraw an amount that exceeds the account balance, we’ll throw a custom exception
called InsufficientFundsException.
Steps:
1. Define a custom exception class InsufficientFundsException that extends Exception.
2. Create a BankAccount class with methods to deposit and withdraw money.
3. Handle the exception in the main method when the withdrawal amount exceeds the available balance.

Program: Custom Exception for Bank Account Withdrawal


1. [Link] (Custom Exception Class)
// Custom exception class that extends the Exception class
public class InsufficientFundsException extends Exception {

// Constructor to initialize the exception with a custom message


public InsufficientFundsException(String message) {
super(message); // Pass the message to the Exception class constructor
}
}
2. [Link] (Bank Account Class)
public class BankAccount {

private double balance;

// Constructor to initialize balance


public BankAccount(double initialBalance) {
[Link] = initialBalance;
}
// Method to deposit money into the account
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount);
} else {
[Link]("Invalid deposit amount.");
}
}
// Method to withdraw money from the account
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
// If withdrawal amount is greater than the balance, throw a custom exception
throw new InsufficientFundsException("Insufficient funds for withdrawal. Current balance: " +
balance);
} else if (amount > 0) {
balance -= amount;
[Link]("Withdrew: " + amount);
} else {
[Link]("Invalid withdrawal amount.");
}
}
// Method to check the balance
public double getBalance() {
return balance;
}
}
3. [Link] (Main Class to Test)
import [Link];

public class TestBankAccount {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Create a BankAccount object with an initial balance of 1000


BankAccount account = new BankAccount(1000);

// Display initial balance


[Link]("Initial balance: " + [Link]());

// Try to deposit some money


[Link]("Enter deposit amount: ");
double depositAmount = [Link]();
[Link](depositAmount);

// Try to withdraw money


try {
[Link]("Enter withdrawal amount: ");
double withdrawalAmount = [Link]();
[Link](withdrawalAmount);
} catch (InsufficientFundsException e) {
// Handle the custom exception (if withdrawal is greater than balance)
[Link]("Error: " + [Link]());
}
// Display final balance
[Link]("Final balance: " + [Link]());

// Close the scanner


[Link]();
}
}
Compiling and Running the Program
1. Save the files:
o Save the custom exception as [Link].
o Save the BankAccount class as [Link].
o Save the TestBankAccount class as [Link].
2. Compile the classes:
3. javac [Link] [Link] [Link]
4. Run the program:
5. java TestBankAccount
Sample Output 1 (Successful Withdrawal):
Initial balance: 1000.0
Enter deposit amount: 500
Deposited: 500.0
Enter withdrawal amount: 300
Withdrew: 300.0
Final balance: 1200.0
Sample Output 2 (Insufficient Funds Exception):
Initial balance: 1000.0
Enter deposit amount: 500
Deposited: 500.0
Enter withdrawal amount: 2000
Error: Insufficient funds for withdrawal. Current balance: 1500.0
Final balance: 1500.0
Explanation:
1. InsufficientFundsException (Custom Exception Class):
o We create a custom exception class called InsufficientFundsException which extends Exception.
o The constructor accepts a message that will be passed to the Exception class’s constructor to
provide a specific error message when the exception is thrown.
2. BankAccount Class:
o The BankAccount class contains methods for:
 deposit(): Adds money to the account balance.
 withdraw(): Attempts to withdraw a specified amount. If the withdrawal amount is greater
than the balance, an InsufficientFundsException is thrown.
 getBalance(): Returns the current balance of the account.
o In the withdraw() method, the custom exception InsufficientFundsException is thrown when the
withdrawal amount exceeds the balance.
3. TestBankAccount Class:
o In the main method, we prompt the user for deposit and withdrawal amounts using the Scanner
class.
o We handle the InsufficientFundsException in a try-catch block to print an appropriate error message
if a withdrawal attempt is made with insufficient funds.
o The program displays the initial and final account balances.

1. Custom Exceptions: We defined a custom exception InsufficientFundsException by extending the Exception


class. This allows us to handle specific application errors with a clear, meaningful message.
2. Exception Handling: The throw keyword is used to throw the custom exception in the withdraw() method,
and it is caught in the main method using a try-catch block.
3. Separation of Concerns: The custom exception helps separate the logic of the program from the error-
handling mechanism, making the code cleaner and easier to maintain.

Notes:
 You can create other custom exceptions by extending either the Exception class for checked exceptions or
the RuntimeException class for unchecked exceptions.
 Custom exceptions are helpful when you need to handle specific errors that are domain-related, rather than
relying on Java’s built-in exceptions.

21. Write a program to demonstrate priorities among multiple threads.


You can assign priorities to threads using the Thread class. Each thread can have a priority, which affects the order
in which threads are scheduled for execution by the thread scheduler. The default priority for threads is Thread.
NORM_PRIORITY (which is 5 on a scale of 1 to 10), and you can adjust it using setPriority().

Objective: We will write a program that demonstrates the use of thread priorities. We will create multiple threads
with different priorities, and observe how threads with higher priorities are given preference by the thread
scheduler.
Steps:
1. We will create several threads with different priorities using the Thread class.
2. Set the priority for each thread using setPriority().
3. Start the threads and observe the order in which they are executed.
Demonstrating Thread Priorities
class MyThread extends Thread {
private String threadName;

public MyThread(String name) {


threadName = name;
}
// Override the run method to define thread's task
@Override
public void run() {
[Link](threadName + " is starting with priority: " + getPriority());
try {
// Simulate some task by sleeping
[Link](1000);
} catch (InterruptedException e) {
[Link](threadName + " was interrupted.");
}
[Link](threadName + " is completed.");
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
// Create threads with different priorities
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
MyThread t3 = new MyThread("Thread 3");
MyThread t4 = new MyThread("Thread 4");

// Set priorities
[Link](Thread.MIN_PRIORITY); // Priority = 1
[Link](Thread.NORM_PRIORITY); // Default priority = 5
[Link](Thread.MAX_PRIORITY); // Priority = 10
[Link](Thread.NORM_PRIORITY); // Default priority = 5

// Start the threads


[Link]();
[Link]();
[Link]();
[Link]();
}
}
Compiling and Running the Program
1. Save the file as [Link].
2. Compile the program:
3. javac [Link]
4. Run the program:
5. java ThreadPriorityDemo
Sample Output: The output order might vary depending on the operating system and how the JVM schedules the
threads, but it should generally show that the thread with the highest priority (Thread 3) gets executed first,
followed by threads with normal priority (Thread 2 and Thread 4), and then the thread with the lowest priority
(Thread 1).

Thread 3 is starting with priority: 10


Thread 3 is completed.
Thread 2 is starting with priority: 5
Thread 2 is completed.
Thread 4 is starting with priority: 5
Thread 4 is completed.
Thread 1 is starting with priority: 1
Thread 1 is completed.
Explanation:
1. Custom Thread Class (MyThread):
o The MyThread class extends Thread and overrides the run() method. The run() method simulates
some task by making the thread sleep for 1 second (using [Link]()).
o The threadName is used to differentiate the threads in the output.
2. Thread Priorities:
o The setPriority(int priority) method is used to set the priority of each thread.
 Thread.MIN_PRIORITY is 1 (the lowest priority).
 Thread.NORM_PRIORITY is 5 (the default priority).
 Thread.MAX_PRIORITY is 10 (the highest priority).
3. Thread Execution:
o All four threads are started using the start() method. They are expected to execute in the order of
their priorities (higher priority threads should be executed first).
4. Output:
o The thread scheduler will prioritize threads with higher priority, but it is important to note that the
actual execution order can also depend on the underlying OS thread scheduling policy. It does not
guarantee that higher-priority threads will always finish first.
5. Simulating Work:
o The [Link](1000) call simulates the work done by each thread, allowing us to observe the
thread execution sequence.

Key Concepts Demonstrated:


1. Thread Priorities: Threads in Java can have priorities from Thread.MIN_PRIORITY (1) to
Thread.MAX_PRIORITY (10). The default priority is Thread.NORM_PRIORITY (5).
2. Thread Scheduling: The operating system's thread scheduler takes thread priority into account, but it is not
guaranteed that threads will execute strictly according to their priority. This depends on the JVM and OS.
3. Thread Execution Order: Higher-priority threads are generally executed first, but the exact order may vary
depending on system resources and load.
Notes:
1. Thread Priority and OS: Thread priority is only a suggestion to the OS thread scheduler. Some operating
systems may give more importance to high-priority threads, while others might ignore thread priority
altogether.
2. [Link](): This is used to simulate work. The sleep time is kept short (1000ms) to allow all threads to
execute and demonstrate priority effects in a visible way.
3. Thread Interruption: In real-world applications, threads can be interrupted, and exception handling can be
added. For simplicity, we haven’t focused on that here.

22. Write a program to demonstrate different mouse handling events like mouse Clicked( ), mouse
Entered ( ), mouse Exited ( ), mouse Pressed( ), mouse Released( ) & mouse Dragged( ).

Mouse events are handled through the MouseListener and MouseMotionListener interfaces. The MouseListener
interface handles events like clicks, entry, and exit, while MouseMotionListener is used to handle mouse movement
and dragging events.

Objective: We will create a simple Java Swing program that demonstrates the following mouse handling events:
 mouseClicked()
 mouseEntered()
 mouseExited()
 mousePressed()
 mouseReleased()
 mouseDragged()
Steps:
1. We will implement the MouseListener and MouseMotionListener interfaces.
2. The program will display a simple frame where the mouse events will be triggered when interacting with
the window.
3. Each event will print a message to the console to demonstrate the event handling.

//Demonstrating Mouse Events


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

public class MouseEventDemo extends JFrame implements MouseListener, MouseMotionListener {

public MouseEventDemo() {
// Set up the JFrame
setTitle("Mouse Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Add mouse listeners


addMouseListener(this);
addMouseMotionListener(this);

// Set the frame visible


setVisible(true);
}
// MouseListener methods
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at: (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered the frame");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited the frame");
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed at: (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at: (" + [Link]() + ", " + [Link]() + ")");
}
// MouseMotionListener methods
@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged at: (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseMoved(MouseEvent e) {
// You can also handle mouse move event if needed
[Link]("Mouse Moved at: (" + [Link]() + ", " + [Link]() + ")");
}
public static void main(String[] args) {
// Create an instance of the MouseEventDemo
new MouseEventDemo();
}
}
Compiling and Running the Program
1. Save the file as [Link].
2. Compile the program:
3. javac [Link]
4. Run the program:
5. java MouseEventDemo
Sample Output: When you interact with the window, different mouse events will trigger and print messages to the
console.
1. Mouse Clicked:
2. Mouse Clicked at: (150, 200)
3. Mouse Entered:
4. Mouse Entered the frame
5. Mouse Exited:
6. Mouse Exited the frame
7. Mouse Pressed:
8. Mouse Pressed at: (180, 220)
9. Mouse Released:
10. Mouse Released at: (180, 220)
11. Mouse Dragged:
12. Mouse Dragged at: (200, 250)
13. Mouse Moved (when you move the mouse over the window):
14. Mouse Moved at: (250, 300)
Explanation:
1. MouseListener Interface: This interface includes methods that are triggered by mouse interactions like
clicks, entering, and exiting:
o mouseClicked(MouseEvent e): Called when the mouse is clicked.
o mouseEntered(MouseEvent e): Called when the mouse enters the component.
o mouseExited(MouseEvent e): Called when the mouse exits the component.
o mousePressed(MouseEvent e): Called when a mouse button is pressed.
o mouseReleased(MouseEvent e): Called when a mouse button is released.
2. MouseMotionListener Interface: This interface includes methods for mouse movement and dragging:
o mouseDragged(MouseEvent e): Called when the mouse is dragged.
o mouseMoved(MouseEvent e): Called when the mouse moves without being dragged.
3. The JFrame:
o We extend JFrame to create a simple graphical window.
o The mouse events are added to the frame using addMouseListener() and
addMouseMotionListener().
4. Event Handling:
o Each mouse event prints a message to the console, showing the event type and the mouse's
coordinates ([Link]() and [Link]()).
5. Visibility: The frame is displayed when the setVisible(true) method is called.

1. MouseListener Interface: It is used to handle mouse events like clicks, entering, and exiting.
2. MouseMotionListener Interface: It is used to handle mouse movements and dragging.
3. Event Handling: We attach listeners to the frame and override methods to handle different mouse events.
4. Event Object (MouseEvent): This provides the details of the event such as the position of the mouse (getX(),
getY()).

Notes:
 Event Propagation: You can handle mouse events at different levels of the GUI hierarchy (such as for
specific components like buttons, panels, or the entire frame). This example demonstrates handling events
for the entire JFrame.
 Other Mouse Listeners: There are more specialized listeners like MouseAdapter, which you can use when
you only need to override a few methods of the MouseListener interface.

23. Write a program to demonstrate different keyboard handling events.


keyboard events are handled using the KeyListener interface. The KeyListener interface provides methods to handle
different types of keyboard events like when a key is pressed, released, or typed.
Objective: We will create a program that demonstrates different keyboard handling events:
 keyPressed(): Triggered when a key is pressed down.
 keyReleased(): Triggered when a key is released.
 keyTyped(): Triggered when a key is typed (a character is produced).
Steps:
1. We will implement the KeyListener interface.
2. The program will display a simple frame, and when you press keys, the program will respond to these
events by displaying corresponding messages.
3. The program will show the key pressed, released, and typed events.

//Demonstrating Keyboard Events


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

public class KeyEventDemo extends JFrame implements KeyListener {

private JTextArea textArea;

public KeyEventDemo() {
// Set up the JFrame
setTitle("Keyboard Event Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Create a JTextArea for user input


textArea = new JTextArea();
[Link](this); // Add the key listener to the text area
[Link](true);

// Add the text area to the JFrame


JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);

// Set the frame visible


setVisible(true);
}
// KeyListener methods
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]() + " (Key Code: " + [Link]() + ")");
}
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]() + " (Key Code: " + [Link]() + ")");
}
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
public static void main(String[] args) {
// Create an instance of the KeyEventDemo class
new KeyEventDemo();
}
}

Compiling and Running the Program


1. Save the file as [Link].
2. Compile the program:
3. javac [Link]
4. Run the program:
5. java KeyEventDemo
Sample Output: When you type in the JTextArea in the window, the following will be printed in the console
depending on the key events triggered:
1. Key Pressed:
2. Key Pressed: A (Key Code: 65)
3. Key Pressed: B (Key Code: 66)
4. Key Released:
5. Key Released: A (Key Code: 65)
6. Key Released: B (Key Code: 66)
7. Key Typed:
8. Key Typed: A
9. Key Typed: B
 When you press the "A" key, you will see the key pressed and key released events in the console, and
keyTyped will print the character "A".
 This behavior will repeat for every key interaction.
Explanation:
1. KeyListener Interface:
o The program implements the KeyListener interface, which includes three key event methods:
o keyPressed(KeyEvent e): Called when a key is pressed.
o keyReleased(KeyEvent e): Called when a key is released.
o keyTyped(KeyEvent e): Called when a key is typed (a character is generated, like pressing a letter
key).
2. JTextArea: A JTextArea is used to allow the user to type text. We attach the KeyListener to the JTextArea so
that the program can handle the key events when the user interacts with the text area.
3. JScrollPane: The JTextArea is placed inside a JScrollPane to provide scrolling functionality in case the user
types a large amount of text.
4. Key Event Handling: When a key is pressed, released, or typed, the respective method is triggered, and the
program prints the key information to the console.
 [Link]() gives the character associated with the key (if applicable).
 [Link]() gives the numeric code of the key (e.g., 65 for 'A', 32 for space).
5. Frame Setup: The frame is set up with a size of 400x400 pixels, and the text area is placed inside a scrollable
pane. The window is set to be visible when the program starts.

Key Concepts Demonstrated:


1. KeyListener Interface: We implement the KeyListener interface, which provides methods for handling
keyboard events.
2. KeyEvent Object: This object provides information about the key event, including the character
(getKeyChar()) and the key code (getKeyCode()).
3. Event Handling: We use addKeyListener(this) to register the current class as the listener for keyboard
events on the JTextArea.
4. Swing Components: The program demonstrates the use of a JTextArea inside a JScrollPane for text input in
a GUI application.
Notes:
 Focus: The component that you want to listen for key events must have focus. In this program, the
JTextArea automatically gains focus when the window is active, so it will listen to the key events.
 KeyCodes vs. KeyChars:
o getKeyChar() returns the character that corresponds to the key pressed (e.g., 'A', '1', etc.).
o getKeyCode() returns the numeric code for the key (e.g., 65 for 'A', 32 for space, etc.).
o The keyPressed() and keyReleased() methods use the key code, while the keyTyped() method uses
the character.

Enhancements:

1. Handling Special Keys: You can handle special keys like Shift, Ctrl, or Enter by checking the key code using
[Link](). For example, KeyEvent.VK_ENTER corresponds to the Enter key.
2. Handling Multiple Key Events: You could also combine the KeyListener with KeyAdapter to simplify your
code if you don’t need to handle all three methods (e.g., if you only care about keyPressed() or keyTyped()).

You might also like