### 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";
System.out.println("Integer: " + a);
System.out.println("Double: " + b);
System.out.println("Char: " + c);
System.out.println("Boolean: " + d);
System.out.println("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) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
// Loop statement
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
### 3. Exercise Programs on I/O Streams
#### i. Reading Data Through Keyboard
*Example Program:*
java
import java.util.Scanner;
public class KeyboardInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}
#### ii. Reading and Writing Primitive Data Types Using DataInputStream and DataOutputStream
*Example Program:*
java
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
// Writing data
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeInt(123);
dos.writeDouble(45.67);
dos.close();
// Reading data
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
int number = dis.readInt();
double decimal = dis.readDouble();
dis.close();
System.out.println("Read Int: " + number);
System.out.println("Read Double: " + decimal);
#### iii. Perform Reading and Writing Operations on Files Using FileStreams
*Example Program:*
java
import java.io.*;
public class FileStreamExample {
public static void main(String[] args) throws IOException {
// Writing data
FileOutputStream fos = new FileOutputStream("file.txt");
fos.write("Hello, World!".getBytes());
fos.close();
// Reading data
FileInputStream fis = new FileInputStream("file.txt");
int i;
while ((i = fis.read()) != -1) {
System.out.print((char) i);
fis.close();
### 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();
System.out.println("Original String: " + str);
System.out.println("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() {
System.out.println("Name: " + name + ", Age: " + age);
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "Alice";
person.age = 25;
person.displayInfo();
### 6. Exercise Programs Using Constructors and Constructor Overloading
*Example Program:*
java
class Person {
String name;
int age;
// Default constructor
Person() {
this.name = "Unknown";
this.age = 0;
// Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
public class Main {
public static void main(String[] args) {
Person person1 = new Person();
person1.displayInfo();
Person person2 = new Person("Bob", 30);
person2.displayInfo();
### 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 (args.length > 0) {
int sum = 0;
for (String arg : args) {
sum += Integer.parseInt(arg);
System.out.println("Sum: " + sum);
} else {
System.out.println("No command line arguments provided.");
#### ii. Input as Command Line Arguments and Update Manipulated Data in Files
*Example Program:*
java
import java.io.*;
public class CommandLineFileExample {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
FileWriter writer = new FileWriter("output.txt");
for (String arg : args) {
writer.write(arg + "\n");
writer.close();
} else {
System.out.println("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();
System.out.println("Sum of integers: " + math.add(5, 10));
System.out.println("Sum of doubles: " + math.add(5.5, 10.5));
}
### 9. Exercise Programs on Inheritance
*Example Program:*
java
class Animal {
void eat() {
System.out.println("This animal eats food.");
class Dog extends Animal {
void bark() {
System.out.println("This dog barks.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
### 10. Write a Program Using the Concept of Method Overriding
*Example Program:*
java
class Animal {
void sound() {
System.out.println("This animal makes a sound.");
class Dog extends Animal {
@Override
void sound() {
System.out.println("The dog barks.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
### 11. Exercise on Packages
#### i. Creation of Packages
*Example Program:*
java
// Save this as Animal.java in the package mypack
package mypack;
public class Animal {
public void display() {
System.out.println("This is an animal.");
// Save this as Main.java in the default package
import mypack.Animal;
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.display();
#### ii. Design Module to Import Packages from Other Packages
*Example Program:*
java
// Save this as Dog.java in the package mypack
package mypack;
public class Dog {
public void bark() {
System.out.println("The dog barks.");
// Save this as Main.java in the default package
import mypack.Dog;
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark();
### 12. Exercise Programs on Interfaces
*Example Program:*
java
interface Animal {
void eat();
class Dog implements Animal {
public void eat() {
System.out.println("The dog eats.");
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
### 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 java.util.ArrayList;
class Student {
int pin;
double percentage;
Student(int pin, double percentage) {
this.pin = pin;
this.percentage = percentage;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(101, 85.5));
students.add(new Student(102, 90.2));
students.add(new Student(103, 78.9));
int searchPin = 102;
for (Student student : students) {
if (student.pin == searchPin) {
System.out.println("Percentage: " + student.per
ii) Write a java program to create linked list to perform delete, Insert, and update data in linked list with
any application.
import java.util.LinkedListy
public class MainClass
public static void mainiString))(
LinkedList officers sew LinkedList
//insection
officers.add("Begum");
officers.add("yasmin");
officers.add("bb");
officers.add("Naazil");
officers.add("Rabbani");
System.out.println(officers);
//updation
officers,set (2, "Sultana");
System.out.println(officers);
//deletion
officers.remove(3):
officers.removeFirst();
//print the altered list
System.out.println("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>();
ht.put("1", "First");
ht.put("2", "Second");
ht.put("3", "Third"):
ht.put("4", "Forth"):
ht.put("5", "Fifth");
System.out.println("Hashtable elements with key: ");
System.out.println(ht):
System.out.println("=================");
if (ht.containsKey("1") &&ht.containsValue ("First"))
System.out.println("key 1 and value first are available.");
else
System.out.println("Hashtable doesn't contain first key and value");
if (ht.containsKey("second") && ht.containsValue("2"))
System.out.println("key second and value 1 are available.");
System.out.println("Hashtable doesn't contain key second and value 2");
System.out.println("==============");
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 java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main{
public static void main(String[] args) {
// Create and populate the HashMap
HashMap<String, String> map = new HashMap<>();
map.put("2", "BUNNY");
map.put("8", "AJAY");
map.put("4", "DIMPU");
map.put("7", "FAROOQ");
map.put("6", "Rams");
// Create a list to store the values from the HashMap
ArrayList<String> list = new ArrayList<>(map.values());
// Sort the list of values
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String str1, String str2) {
return str1.compareTo(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 (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
sortedMap.put(entry.getKey(), entry.getValue());
break; // Break the inner loop once the entry is added
// Print the sorted map
System.out.println(sortedMap);
OUTPUT
{2=BUNNY,8=AJAY,4=DIMPU, 7= FAROOQ,
6=Rams}
14.Exercise 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 java.util.Scanner;
public class ExceptionHandling
public static void main(String[] args)
Scanner scanner = new Scanner(System.in);
int result = 0;
try {
System.out.print("Enter a number to divide 100 by: ");
String input = scanner.nextLine();
// Convert input to integer
int number = Integer.parseInt(input);
// Attempt to divide by the input number
result = 100 / number;
System.out.println("100 divided by " + number + " is " + result);
} catch (NumberFormatException e) {
// Handle case where input is not a valid integer
System.out.println("Error: Please enter a valid integer.");
} catch (ArithmeticException e) {
// Handle division by zero
System.out.println("Error: Division by zero is not allowed.");
} finally {
// This block always executes
System.out.println("Finally block: Closing the scanner.");
scanner.close();
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 = Integer.parseInt(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
System.out.println("Error: Array index out of bounds.");
} catch (NumberFormatException e) {
// Handle case where string is not a valid integer
System.out.println("Error: Number format exception.");
} catch (ArithmeticException e) {
// Handle case where division by zero occurs
System.out.println("Error: Division by zero.");
} finally {
// This block always executes
System.out.println("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 {
System.out.println("Outer try block started.");
try {
System.out.println("Inner try block started.");
int[] numbers = {1, 2, 3};
// This will throw ArrayIndexOutOfBoundsException
int result = numbers[5];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Inner catch block: Array index is out of bounds.");
// This block will execute if no exceptions were thrown in the inner try block
System.out.println("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) {
System.out.println("Outer catch block: Division by zero is not allowed.");
} finally {
// This block always executes
System.out.println("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.
15.Exercise 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++) {
System.out.println("Task running: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
};
// Create and start a single thread
Thread thread = new Thread(task);
thread.start();
// Wait for the thread to complete
try {
thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("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"));
thread1.start();
thread2.start();
thread3.start();
// Wait for all threads to complete
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
System.out.println("All threads execution complete.");
class Task implements Runnable {
private final String threadName;
public Task(String threadName) {
this.threadName = threadName;
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(threadName + " is running: " + i);
try {
Thread.sleep(500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
System.out.println(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
highPriorityThread.setPriority(Thread.MAX_PRIORITY); // Highest priority
mediumPriorityThread.setPriority(Thread.NORM_PRIORITY); // Normal priority
lowPriorityThread.setPriority(Thread.MIN_PRIORITY); // Lowest priority
highPriorityThread.start();
mediumPriorityThread.start();
lowPriorityThread.start();
// Wait for all threads to complete
try {
highPriorityThread.join();
mediumPriorityThread.join();
lowPriorityThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
System.out.println("All threads execution complete.");
class Task implements Runnable {
private final String threadName;
public Task(String threadName) {
this.threadName = threadName;
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(threadName + " is running: " + i);
try {
Thread.sleep(500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
System.out.println(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)
e.printStackTrace();
System.out.print in (msg):
flag= true;
notify();
public synchronized vold AnswertString mag) |
if (!flag)
{
try{
Wait();
I catch (InterruptedException e.printStackTrace();
System.out.println(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 (
this.smi
new Thread(this, "Question").start()
public void runti
for (int 101s1.length; 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; 12.length; i++) .Answer (s2[1])