### 1.
Exercise Programs Using Java Built-in Data Types
*Example Program:*
java
public class DataTypesExample {
public static void main(String[] args) {
int a = 10;
double b = 20.5;
char c = 'A';
boolean d = true;
String e = "Hello";
[Link]("Integer: " + a);
[Link]("Double: " + b);
[Link]("Char: " + c);
[Link]("Boolean: " + d);
[Link]("String: " + e);
### 2. Exercise Programs on Conditional Statements and Loop Statements
*Example Program:*
java
public class ConditionalLoopExample {
public static void main(String[] args) {
int num = 5;
// Conditional statement
if (num % 2 == 0) {
[Link](num + " is even");
} else {
[Link](num + " is odd");
// Loop statement
for (int i = 1; i <= 5; i++) {
[Link]("Number: " + i);
### 3. Exercise Programs on I/O Streams
#### i. Reading Data Through Keyboard
*Example Program:*
java
import [Link];
public class KeyboardInput {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Hello, " + name);
}
#### ii. Reading and Writing Primitive Data Types Using DataInputStream and DataOutputStream
*Example Program:*
java
import [Link].*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
// Writing data
DataOutputStream dos = new DataOutputStream(new FileOutputStream("[Link]"));
[Link](123);
[Link](45.67);
[Link]();
// Reading data
DataInputStream dis = new DataInputStream(new FileInputStream("[Link]"));
int number = [Link]();
double decimal = [Link]();
[Link]();
[Link]("Read Int: " + number);
[Link]("Read Double: " + decimal);
#### iii. Perform Reading and Writing Operations on Files Using FileStreams
*Example Program:*
java
import [Link].*;
public class FileStreamExample {
public static void main(String[] args) throws IOException {
// Writing data
FileOutputStream fos = new FileOutputStream("[Link]");
[Link]("Hello, World!".getBytes());
[Link]();
// Reading data
FileInputStream fis = new FileInputStream("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link]((char) i);
[Link]();
### 4. Exercise Programs on Strings
*Example Program:*
java
public class StringExample {
public static void main(String[] args) {
String str = "Hello, World!";
String reversedStr = new StringBuilder(str).reverse().toString();
[Link]("Original String: " + str);
[Link]("Reversed String: " + reversedStr);
}
### 5. Exercise Program to Create Class and Objects and Adding Methods
*Example Program:*
java
class Person {
String name;
int age;
void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
public class Main {
public static void main(String[] args) {
Person person = new Person();
[Link] = "Alice";
[Link] = 25;
[Link]();
### 6. Exercise Programs Using Constructors and Constructor Overloading
*Example Program:*
java
class Person {
String name;
int age;
// Default constructor
Person() {
[Link] = "Unknown";
[Link] = 0;
// Parameterized constructor
Person(String name, int age) {
[Link] = name;
[Link] = age;
void displayInfo() {
[Link]("Name: " + name + ", Age: " + age);
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
[Link]();
Person person2 = new Person("Bob", 30);
[Link]();
### 7. Exercise Programs on Command Line Arguments
#### i. Input as Command Line Arguments and Perform Operation on That Data
*Example Program:*
java
public class CommandLineExample {
public static void main(String[] args) {
if ([Link] > 0) {
int sum = 0;
for (String arg : args) {
sum += [Link](arg);
[Link]("Sum: " + sum);
} else {
[Link]("No command line arguments provided.");
#### ii. Input as Command Line Arguments and Update Manipulated Data in Files
*Example Program:*
java
import [Link].*;
public class CommandLineFileExample {
public static void main(String[] args) throws IOException {
if ([Link] > 0) {
FileWriter writer = new FileWriter("[Link]");
for (String arg : args) {
[Link](arg + "\n");
[Link]();
} else {
[Link]("No command line arguments provided.");
### 8. Exercise Programs Using Concept of Overloading Methods
*Example Program:*
java
class MathOperations {
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
[Link]("Sum of integers: " + [Link](5, 10));
[Link]("Sum of doubles: " + [Link](5.5, 10.5));
}
### 9. Exercise Programs on Inheritance
*Example Program:*
java
class Animal {
void eat() {
[Link]("This animal eats food.");
class Dog extends Animal {
void bark() {
[Link]("This dog barks.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
[Link]();
### 10. Write a Program Using the Concept of Method Overriding
*Example Program:*
java
class Animal {
void sound() {
[Link]("This animal makes a sound.");
class Dog extends Animal {
@Override
void sound() {
[Link]("The dog barks.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
### 11. Exercise on Packages
#### i. Creation of Packages
*Example Program:*
java
// Save this as [Link] in the package mypack
package mypack;
public class Animal {
public void display() {
[Link]("This is an animal.");
// Save this as [Link] in the default package
import [Link];
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
[Link]();
#### ii. Design Module to Import Packages from Other Packages
*Example Program:*
java
// Save this as [Link] in the package mypack
package mypack;
public class Dog {
public void bark() {
[Link]("The dog barks.");
// Save this as [Link] in the default package
import [Link];
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
### 12. Exercise Programs on Interfaces
*Example Program:*
java
interface Animal {
void eat();
class Dog implements Animal {
public void eat() {
[Link]("The dog eats.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
}
### 13. Exercise Programs on Collections
#### i. Write a Java Program to Search a Student Mark Percentage Based on Pin Number Using
ArrayList
*Example Program:*
```java
import [Link];
class Student {
int pin;
double percentage;
Student(int pin, double percentage) {
[Link] = pin;
[Link] = percentage;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
[Link](new Student(101, 85.5));
[Link](new Student(102, 90.2));
[Link](new Student(103, 78.9));
int searchPin = 102;
for (Student student : students) {
if ([Link] == searchPin) {
[Link]("Percentage: " + [Link]
ii) Write a java program to create linked list to perform delete, Insert, and update data in linked list with
any application.
import [Link]
public class MainClass
public static void mainiString))(
LinkedList officers sew LinkedList
//insection
[Link]("Begum");
[Link]("yasmin");
[Link]("bb");
[Link]("Naazil");
[Link]("Rabbani");
[Link](officers);
//updation
officers,set (2, "Sultana");
[Link](officers);
//deletion
[Link](3):
[Link]();
//print the altered list
[Link]("Linked list after delecions officers
Output:
[Begum,Yasmin,bb,Naazil,Rabbani]
[Begum, Yasmin, Sultana, bb,Naazil, Rabbani]
Linked list after deletion: [Yasmin, Sultana, Rabbani]
ill) Write a java program to search an element from hash table.
import java util. Enumeration;
import java util Hashtable:
clase SearchValunkeys
public static void main(String []args)
Hashtable<String, String> ht = new Hashtable<String, String>();
[Link]("1", "First");
[Link]("2", "Second");
[Link]("3", "Third"):
[Link]("4", "Forth"):
[Link]("5", "Fifth");
[Link]("Hashtable elements with key: ");
[Link](ht):
[Link]("=================");
if ([Link]("1") &&[Link] ("First"))
[Link]("key 1 and value first are available.");
else
[Link]("Hashtable doesn't contain first key and value");
if ([Link]("second") && [Link]("2"))
[Link]("key second and value 1 are available.");
[Link]("Hashtable doesn't contain key second and value 2");
[Link]("==============");
Output:
Hashtable elements with key:
(5=Fifth, 4=Forth, 3=Third, 2=Second, 1=First)
========================
key 1 and value first are available.
Hashtable doesn't contain key second and value 2
=====================
iv) Write a Java program to sorting employee detalls using hash map.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Main{
public static void main(String[] args) {
// Create and populate the HashMap
HashMap<String, String> map = new HashMap<>();
[Link]("2", "BUNNY");
[Link]("8", "AJAY");
[Link]("4", "DIMPU");
[Link]("7", "FAROOQ");
[Link]("6", "Rams");
// Create a list to store the values from the HashMap
ArrayList<String> list = new ArrayList<>([Link]());
// Sort the list of values
[Link](list, new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
return [Link](str2);
});
// Create a LinkedHashMap to store the sorted entries
LinkedHashMap<String, String> sortedMap = new LinkedHashMap<>();
// Add the sorted entries to the LinkedHashMap
for (String value : list) {
for ([Link]<String, String> entry : [Link]()) {
if ([Link]().equals(value)) {
[Link]([Link](), [Link]());
break; // Break the inner loop once the entry is added
// Print the sorted map
[Link](sortedMap);
OUTPUT
{2=BUNNY,8=AJAY,4=DIMPU, 7= FAROOQ,
6=Rams}
[Link] on exception handling
i) program on try,catch and finally
try Block:
The try block contains code that might throw an exception. It is used to wrap the code where you
anticipate potential errors.
catch Block:
The catch block is used to handle exceptions thrown by the try block. It defines how to respond to
specific types of exceptions.
finally Block:
The finally block contains code that is always executed, whether an exception is thrown or not. It is
typically used for cleanup activities, like closing files or releasing resources.
Program:
import [Link];
public class ExceptionHandling
public static void main(String[] args)
Scanner scanner = new Scanner([Link]);
int result = 0;
try {
[Link]("Enter a number to divide 100 by: ");
String input = [Link]();
// Convert input to integer
int number = [Link](input);
// Attempt to divide by the input number
result = 100 / number;
[Link]("100 divided by " + number + " is " + result);
} catch (NumberFormatException e) {
// Handle case where input is not a valid integer
[Link]("Error: Please enter a valid integer.");
} catch (ArithmeticException e) {
// Handle division by zero
[Link]("Error: Division by zero is not allowed.");
} finally {
// This block always executes
[Link]("Finally block: Closing the scanner.");
[Link]();
Output
Enter a number to divide 100 by: 5
100 divided by 5 is 20
Finally block: Closing the scanner.
ii) Program on multiple catch statement
public class MultipleCatch
public static void main(String[] args) {
try {
// Code that might throw multiple exceptions
String[] numbers = {"10", "20", "abc"};
int index = 3;
int number = [Link](numbers[index]); // This will throw
ArrayIndexOutOfBoundsException
int result = 100 / number; // This line will not be reached due to the previous exception
} catch (ArrayIndexOutOfBoundsException e) {
// Handle case where array index is out of bounds
[Link]("Error: Array index out of bounds.");
} catch (NumberFormatException e) {
// Handle case where string is not a valid integer
[Link]("Error: Number format exception.");
} catch (ArithmeticException e) {
// Handle case where division by zero occurs
[Link]("Error: Division by zero.");
} finally {
// This block always executes
[Link]("Finally block: Execution completed.");
}
Output
Error: Array index out of bounds.
Finally block: Execution completed.
iii)Program on nested try statement
public class NestedTry
public static void main(String[] args) {
try {
[Link]("Outer try block started.");
try {
[Link]("Inner try block started.");
int[] numbers = {1, 2, 3};
// This will throw ArrayIndexOutOfBoundsException
int result = numbers[5];
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner catch block: Array index is out of bounds.");
// This block will execute if no exceptions were thrown in the inner try block
[Link]("Inner try block completed.");
// Additional code that might throw exceptions
int a = 10;
int b = 0;
int division = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Outer catch block: Division by zero is not allowed.");
} finally {
// This block always executes
[Link]("Outer finally block: Cleanup completed.");
Output
Outer try block started.
Inner try block started.
Inner catch block: Array index is out of bounds.
Inner try block completed.
Outer catch block: Division by zero is not allowed.
Outer finally block: Cleanup completed.
[Link] on multithreading
i)program on creation of single and multithread
Single Thread Program
public class SingleThread {
public static void main(String[] args) {
// Create a single thread using a Runnable
Runnable task = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task running: " + i);
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
};
// Create and start a single thread
Thread thread = new Thread(task);
[Link]();
// Wait for the thread to complete
try {
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Single thread execution complete.");
Output
Task running: 1
Task running: 2
Task running: 3
Task running: 4
Task running: 5
Single thread execution complete.
Multiple Threads Program:
public class MultiThread
public static void main(String[] args) {
// Create and start multiple threads
Thread thread1 = new Thread(new Task("Thread 1"));
Thread thread2 = new Thread(new Task("Thread 2"));
Thread thread3 = new Thread(new Task("Thread 3"));
[Link]();
[Link]();
[Link]();
// Wait for all threads to complete
try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
[Link]("All threads execution complete.");
class Task implements Runnable {
private final String threadName;
public Task(String threadName) {
[Link] = threadName;
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](threadName + " is running: " + i);
try {
[Link](500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
Output
Thread 1 is running: 1
Thread 2 is running: 1
Thread 3 is running: 1
Thread 1 is running: 2
Thread 2 is running: 2
Thread 3 is running: 2
Thread 1 is running: 3
Thread 2 is running: 3
Thread 3 is running: 3
All threads execution complete.
ii)Program and adding priorities to multiple thread.
public class ThreadPriorityExample {
public static void main(String[] args) {
// Create and start threads with different priorities
Thread highPriorityThread = new Thread(new Task("High Priority Thread"));
Thread mediumPriorityThread = new Thread(new Task("Medium Priority Thread"));
Thread lowPriorityThread = new Thread(new Task("Low Priority Thread"));
// Set thread priorities
[Link](Thread.MAX_PRIORITY); // Highest priority
[Link](Thread.NORM_PRIORITY); // Normal priority
[Link](Thread.MIN_PRIORITY); // Lowest priority
[Link]();
[Link]();
[Link]();
// Wait for all threads to complete
try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
[Link]("All threads execution complete.");
class Task implements Runnable {
private final String threadName;
public Task(String threadName) {
[Link] = threadName;
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](threadName + " is running: " + i);
try {
[Link](500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
Output
High Priority Thread is running: 1
Medium Priority Thread is running: 1
Low Priority Thread is running: 1
High Priority Thread is running: 2
Medium Priority Thread is running: 2
Low Priority Thread is running: 2
High Priority Thread is running: 3
Medium Priority Thread is running: 3
Low Priority Thread is running: 3
All threads execution complete.
iii) program on inter thread communication
class Chat
boolean flag =false
public synchronized void Question (String msg)
if (flag)
try{
Wait();
catch (InterruptedException e)
[Link]();
[Link] in (msg):
flag= true;
notify();
public synchronized vold AnswertString mag) |
if (!flag)
{
try{
Wait();
I catch (InterruptedException [Link]();
[Link](msg)
flag falaer
notify)
class i implements Runnable |
Chat B
Stringi) si "Hi", "How are you ?", "I am also doing final
public 71 (Chat mis (
[Link]
new Thread(this, "Question").start()
public void runti
for (int [Link]; i++)(
miQuestiontal [1]):
cians 12 implements Punnable
Chat mi
String() s21 "Hi", "I am good, what about you?", "Orestis
public 12 (Chat #2) (
this.n21
new Thread(this, "Answer").start():
public void run() ( for (int 10; [Link]; i++) .Answer (s2[1])