0% found this document useful (0 votes)
1 views

Practical 23 38

The document contains practical programming exercises by Yash Srivastava, a B.Tech CSE-AI student, covering various Java concepts such as exception handling, file operations, inheritance, multi-dimensional arrays, string manipulation, and multithreading. Each practical includes a code solution and expected output demonstrating the respective concept. The exercises illustrate fundamental programming skills and Java features in a structured manner.

Uploaded by

samii000786
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)
1 views

Practical 23 38

The document contains practical programming exercises by Yash Srivastava, a B.Tech CSE-AI student, covering various Java concepts such as exception handling, file operations, inheritance, multi-dimensional arrays, string manipulation, and multithreading. Each practical includes a code solution and expected output demonstrating the respective concept. The exercises illustrate fundamental programming skills and Java features in a structured manner.

Uploaded by

samii000786
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
You are on page 1/ 26

2201921520198 YASH SRIVASTAVA B.

Tech CSE-AI

Practical No. – 23
Write a program that describes exception handling mechanism (use try-catch, finally).
Solution :
class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of code...");
}
}
Output

Practical No. – 24
Write a program to demonstrate how to create a new file, write to a file and perform some
other operations using file handling.
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Solution :
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileHandlingDemo {
public static void main(String[] args) {
String fileName = "example.txt";
createNewFile(fileName);
writeFile(fileName, "Hello, this is a sample text written to the file.\n");
writeFile(fileName, "This text is appended to the file.\n");
readFile(fileName);
deleteFile(fileName);
}
public static void createNewFile(String fileName) {
File file = new File(fileName);
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
public static void writeFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName, true)) {
writer.write(content);
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

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


e.printStackTrace();
}
}
public static void readFile(String fileName) {
try (FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Output
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Practical No. – 25
Write a program to implement user-defined exception in java.
Solution :
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class UserDefinedException{
public static void validate(int age) throws MyException {
if (age < 18) {
throw new MyException("Age must be 18 or above for registration.");
} else {
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

System.out.println("Registration successful!");
}
}
public static void main(String[] args) {
try {
validate(2);
} catch (MyException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}
Output

Practical No. – 26
Write program(s) on use of inheritance, preventing inheritance using final, abstract classes.
Solution :
// Demonstrating inheritance
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Demonstrating preventing inheritance using final
final class Vehicle {
void drive() {
System.out.println("This vehicle can be driven.");
}
}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

// Demonstrating abstract class


abstract class Shape {
abstract void draw(); // Abstract method
void display() {
System.out.println("This is a shape.");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle.");
}
}
// Demonstrating inheritance with a subclass
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class CombinedDemo {
public static void main(String[] args) {
// Inheritance demo
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Own method
// Preventing inheritance using final
Vehicle vehicle = new Vehicle();
vehicle.drive();
// Abstract class demo
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Shape circle = new Circle();


circle.draw(); // Implementation of abstract method
circle.display(); // Concrete method in abstract class
Shape rectangle = new Rectangle();
rectangle.draw(); // Implementation of abstract method
rectangle.display(); // Concrete method in abstract class
}
}
Output

Practical No. – 27
Write a program that prints a multi-dimensional array of integers.
Solution :
public class MultiDimensionalArrayDemo {
public static void main(String[] args) {
// Initializing a 2D array
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("2D Array:");
print2DArray(array);
// Initializing a 3D array
int[][][] array3D = {
{
{1, 2, 3},
{4, 5, 6}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

},
{
{7, 8, 9},
{10, 11, 12}
}
};
System.out.println("\n3D Array:");
print3DArray(array3D);
}
public static void print2DArray(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
public static void print3DArray(int[][][] array) {
for (int i = 0; i < array.length; i++) {
System.out.println("Layer " + (i + 1) + ":");
for (int j = 0; j < array[i].length; j++) {
for (int k = 0; k < array[i][j].length; k++) {
System.out.print(array[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Output

Practical No. – 28
Write a Program to demonstrate String Buffer Class and String Builder Class.
Solution :
public class StringBufferBuilderDemo {
public static void main(String[] args) {
// StringBuffer demonstration
System.out.println("StringBuffer Demonstration:");
StringBuffer stringBuffer = new StringBuffer("Hello");
// Append
stringBuffer.append(" World");
System.out.println("After append: " + stringBuffer);
// Insert
stringBuffer.insert(5, ",");
System.out.println("After insert: " + stringBuffer);
// Replace
stringBuffer.replace(5, 6, "!");
System.out.println("After replace: " + stringBuffer);
// Delete
stringBuffer.delete(5, 6);
System.out.println("After delete: " + stringBuffer);
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

// Reverse
stringBuffer.reverse();
System.out.println("After reverse: " + stringBuffer);
// Capacity
System.out.println("Capacity of stringBuffer: " + stringBuffer.capacity());
// StringBuilder demonstration
System.out.println("\nStringBuilder Demonstration:");
StringBuilder stringBuilder = new StringBuilder("Hello");
// Append
stringBuilder.append(" World");
System.out.println("After append: " + stringBuilder);
// Insert
stringBuilder.insert(5, ",");
System.out.println("After insert: " + stringBuilder);
// Replace
stringBuilder.replace(5, 6, "!");
System.out.println("After replace: " + stringBuilder);
// Delete
stringBuilder.delete(5, 6);
System.out.println("After delete: " + stringBuilder);
// Reverse
stringBuilder.reverse();
System.out.println("After reverse: " + stringBuilder);
// Capacity
System.out.println("Capacity of stringBuilder: " + stringBuilder.capacity());
}
}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Output

Practical No. – 29
Write a program to illustrate Multiple catch blocks.
Solution :
public class MultipleCatchBlocksDemo {
public static void main(String[] args) {
try {
// This array will cause ArrayIndexOutOfBoundsException
int[] array = {1, 2, 3};
System.out.println("Accessing element at index 3: " + array[3]);
// This will cause NullPointerException
String str = null;
System.out.println("Length of the string: " + str.length());
// This will cause ArithmeticException
int result = 10 / 0;
System.out.println("Result of division: " + result);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}
catch (Exception e) {
System.out.println("General Exception caught: " + e.getMessage());
}
System.out.println("\nProgram continues after the try-catch blocks.");
}
}
Output
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Practical No. – 30
Write a program for creation of illustrating throw.
Solution :
class ThrowExcep {
static void fun()
{
try {
throw new NullPointerException("demo");
}
catch (NullPointerException e) {
System.out.println("Caught inside fun().");
throw e;
}
}
public static void main(String args[])
{
try {
fun();
}
catch (NullPointerException e) {
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

System.out.println("Caught in main.");
}
}
}
Output

Practical No. – 31
Write a program to demonstrate creation of multiple child threads.
Solution :
public class MyThread extends Thread
{
String task;
MyThread(String task){
this.task = task;
}
public void run(){
for(int i = 1; i <= 5; i++){
System.out.println(task+ " : " +i);
try{
Thread.sleep(1000);
}
catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

} // end of for loop.


} // end of run() method.
public static void main(String[] args) {
MyThread th1 = new MyThread("Cut the ticket");
MyThread th2 = new MyThread("Show your seat number");
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);
t1.start();
t2.start();
}
}

Output
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Practical No. – 32
Write a program for multi-thread implementation using Thread Class and Runnable Interface.
Solution :
class Run implements Runnable{
public void run() {
System.out.println("Runnable Interface...");
}
}
class start extends Thread{
public void run() {
System.out.println("Thread Class...");
}
}
public class ExampleClass {
public static void main(String[] args) {
Run ex = new Run();
Thread t1= new Thread(ex);
t1.start();
start object = new start();
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

object.start();
}
}
Output

Practical No. – 33
Write a program creating 2 threads using Runnable interface. Print your name in run()
method of first class and "Hello Java" in run () method of second thread.
Solution :
class PrintName implements Runnable {
@Override
public void run() {
System.out.println("Yash Srivastava");
}
}
class PrintMessage implements Runnable {
@Override
public void run() {
System.out.println("Hello Java");
}
}
public class Main {
public static void main(String[] args) {
Runnable printName = new PrintName();
Runnable printMessage = new PrintMessage();
Thread thread1 = new Thread(printName);
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Thread thread2 = new Thread(printMessage);


thread1.start();
thread2.start();
}
}

Output

Practical No. – 34
Write a Program to synchronize the threads by using Synchronize statements and synchronize
block.
Solution :
class Table{
synchronized void printTable(int n){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
} catch(Exception e){
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

Practical No. – 35
Write a Program to demonstrate the following String Handling.
i. String Length& Concatenation.
ii. Character Extraction.
iii. String Comparison.
iv. Searching and modifying String.
Solution :
public class StringHandlingDemo {
public static void main(String[] args) {
// Part i: String Length & Concatenation
String str1 = "Hello";
String str2 = "World";
// Length
int length1 = str1.length();
int length2 = str2.length();
System.out.println("Length of str1: " + length1);
System.out.println("Length of str2: " + length2);
// Concatenation
String concatenatedString = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenatedString);
// Part ii: Character Extraction
char charAtIndex2 = str1.charAt(2);
System.out.println("Character at index 2 in str1: " + charAtIndex2);
// Part iii: String Comparison
String str3 = "Hello";
boolean isEqual = str1.equals(str3);
System.out.println("str1 is equal to str3: " + isEqual);
int comparisonResult = str1.compareTo(str2);
System.out.println("Comparison of str1 with str2: " + comparisonResult);
// Part iv: Searching and Modifying String
String sentence = "The quick brown fox jumps over the lazy dog";
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

// Searching
int indexOfFox = sentence.indexOf("fox");
System.out.println("Index of 'fox' in the sentence: " + indexOfFox);
// Modifying
String modifiedSentence = sentence.replace("fox", "cat");
System.out.println("Modified Sentence: " + modifiedSentence);
}
}
Output

Practical No. – 36
Write a program to implement the following operations of Collection Classes:
a) Creating an ArrayList.
b) Adding elements to the ArrayList.
c) Displaying elements using both for-each loop and iterator.
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

d) Adding an element at a specific index.


e) Removing an element at a specific index.
f) Checking if an element is present in the ArrayList.
g) Getting the size of the ArrayList.
Solution :
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo {
public static void main(String[] args) {
// a) Creating an ArrayList
ArrayList<String> list = new ArrayList<>();
// b) Adding elements to the ArrayList
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// c) Displaying elements using both for-each loop and iterator
System.out.println("Displaying elements using for-each loop:");
for (String fruit : list) {
System.out.println(fruit);
}
System.out.println("\nDisplaying elements using iterator:");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// d) Adding an element at a specific index
list.add(1, "Orange");
System.out.println("\nAfter adding Orange at index 1:");
for (String fruit : list) {
System.out.println(fruit);
}
// e) Removing an element at a specific index
list.remove(2);
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

System.out.println("\nAfter removing element at index 2:");


for (String fruit : list) {
System.out.println(fruit);
}
// f) Checking if an element is present in the ArrayList
String elementToCheck = "Banana";
boolean isPresent = list.contains(elementToCheck);
System.out.println("\nIs " + elementToCheck + " present in the list? " + isPresent);
// g) Getting the size of the ArrayList
int size = list.size();
System.out.println("\nSize of the ArrayList: " + size);
}
}
Output

Practical No. – 37
Write a java program to create a treeSet , add some colors(Strings) and perform some
operations:
a) Print out the treeSet
b) To iterate through all elements in a treeSet
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

c) To add all the elements of a specified treeSet to another treeSet


d) To create a reverse order view of the elements contained in a given treeSet.
e) To get the first and last elements in a treeSet.
f) To clone a treeSet list to another treeSet.
g) To get the number of elements in a treeSet.
Solution :
import java.util.Iterator;
import java.util.TreeSet;
import java.util.NavigableSet;
public class TreeSetExample {
public static void main(String[] args) {
// a) Create a TreeSet and add some colors (Strings)
TreeSet<String> colors = new TreeSet<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.add("Yellow");
colors.add("White");
// a) Print out the TreeSet
System.out.println("TreeSet: " + colors);
// b) Iterate through all elements in the TreeSet
System.out.println("Iterating through the TreeSet:");
Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// c) Add all elements of the current TreeSet to another TreeSet
TreeSet<String> otherColors = new TreeSet<>();
otherColors.addAll(colors);
System.out.println("New TreeSet after adding elements : " + otherColors);
// d) Create a reverse order view of the elements contained in the given TreeSet
NavigableSet<String> reverseColors = colors.descendingSet();
System.out.println("Reverse order view of the TreeSet: " + reverseColors);
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

// e) Get the first and last elements in the TreeSet


String firstElement = colors.first();
String lastElement = colors.last();
System.out.println("First element: " + firstElement);
System.out.println("Last element: " + lastElement);
// f) Clone the TreeSet to another TreeSet
TreeSet<String> clonedColors = (TreeSet<String>) colors.clone();
System.out.println("Cloned TreeSet: " + clonedColors);
// g) Get the number of elements in the TreeSet
int size = colors.size();
System.out.println("Number of elements in the TreeSet: " + size);
}
}
Output

Practical No. – 38
Write a Program to demonstrate the concept of type annotations in java.

import java.util.ArrayList;
import java.util.List;
class car {
2201921520198 YASH SRIVASTAVA B.Tech CSE-AI

void model() {
System.out.println("Volvo S60");
}
}
class audi extends car {
@Override
void model() {
System.out.println("Audi A8");
}
}
public class AnnotationsDemo {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Example 1: Using @Override annotation
car c = new audi();
c.model();
// Example 2: Using @SuppressWarnings annotation
List<String> list = new ArrayList<>();
@SuppressWarnings("unchecked")
List<String> uncheckedList = (List) list;
uncheckedList.add("Yash Srivastava");
System.out.println("Unchecked List: " + uncheckedList);
}
}
Output

You might also like