Practical 23 38
Practical 23 38
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
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
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
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
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
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
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