Nothing Special   »   [go: up one dir, main page]

OOPs Lab-E1-CSE-SEM2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 102

Object Oriented Programming through Java

As per Lab Syllabus

Lab No. 1: Basic Programs in Java


Basic programs in Java (Topics: Variables, Datatypes, For loop and while loop)
1. Write a Java program to find the given number is even or not?
Code:
//program to find the given number is even or not?
import java.util.Scanner;
class even
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter a number:");
int n=s.nextInt();
if(n%2==0)
{
System.out.println("the given number is even");
}
else
{
System.out.println("the given number is not even");
}
}
}

2. Write a Java program to find largest among three numbers?


Code:
//program to find largest among three numbers?
import java.util.Scanner;
class largest
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter first number:");
int a=s.nextInt();
System.out.print("enter second number:");
int b=s.nextInt();
System.out.print("enter third number:");
int c=s.nextInt();
if(a>b)
{
if(a>c)
{
System.out.println(a+" is largest number");
}
else
{
System.out.println(c+" is largest number");
}
}
else
{
System.out.println(b+" is largest number");
}
}
}

3. Write a Java program to check whether the give number is a palindrome or not?
Code:
//program to check whether the give number is a palindrome or not?
import java.util.Scanner;
class palindrone
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter a number:");
int n=s.nextInt();
int rev=0,rem,temp=n;
while(n!=0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
if(temp==rev)
{
System.out.println(temp+" is a palindrone number");
}
else
{
System.out.println(temp+ " is not a palindrone number");
}
}
}

4. Write a Java program to check whether the given number is prime number or not?
Code:
//program to check whether the given nuber is prime number or not
import java.util.Scanner;
class prime
{
public static void main(String args[])
{
int i,fact=0;
Scanner s=new Scanner(System.in);
System.out.print("enter a number:");
int n=s.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)
{
fact++;
}
}
if(fact!=0)
{
System.out.println(n+" is not a prime number");
}
else
{
System.out.println(n+" is a prime number");
}
}
}

5. Write a Java program to check whether it is a leap year or not?


Code:
//program to check whwther it is a leap year or not
import java.util.Scanner;
class leapyear
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter a year:");
int n=s.nextInt();
if((n%4==0&&n%100!=0)||(n%400==0))
{
System.out.println(n+" is a leap year");
}
else
{
System.out.println(n+" is not a leap year");
}
}
}

6. Write a Java program to swap two numbers?


Code:
//program to swap two numbers
import java.util.Scanner;
class swap
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.print("enter first number:");
int a=s.nextInt();
System.out.print("enter second number:");
int b=s.nextInt();
System.out.println("before swapping: a="+a+" b="+b);
int temp=a;
a=b;
b=temp;
System.out.println("after swapping: a="+a+" b="+b);
}
}

7. Write a Java program to display the fibanocci series?


Code:
//program to display the fibonacci series
import java.util.Scanner;
class fibonacci
{
public static void main(String argd[])
{
Scanner s=new Scanner(System.in);
System.out.print("Enter the number of terms:");
int n=s.nextInt();
int a=0,b=1,i,c;
System.out.print(a+ " " +b);
for(i=2;i<n;i++)
{
c=a+b;
System.out.print(" " +c);
a=b;
b=c;
}
}
}

8. Write a Java program to print the pyramid triangle shape with stars and numbers range
upto five lines?
import java.util.*;
class pyramid
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
9. Write a Java program to convert temperature in Celsius to Fahrenheit?
Code:
import java.util.Scanner;
class CelsiusToFahrenheit
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter temperature in celcius:");
double celcius=scan.nextDouble();
double fahrenheit=(celcius*9/5)+32;
System.out.print("Temperature in fahrenheit:" +fahrenheit+"°F");
}
}

10. Write a Java program to perform basic Calculator operations(switch case: +,-,*,/,%)
Code:
import java.util.Scanner;
class Calculator
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.println("Basic Calculator:");
System.out.println("Enter two numbers:");
System.out.print("a=");
double a=scan.nextDouble();
System.out.print("b=");
double b=scan.nextDouble();
System.out.println("Choose an operation:");

System.out.println("1.Addition\n2.Substraction\n3.Multiplication\n4.Division
\n5.Modulus\n");
System.out.print("Enter which operation you want to do:");
int choice=scan.nextInt();
double result=0;
switch(choice)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
if(b!=0){
result=a/b;
}
else{
System.out.println("Cannot divisible by zero;");
System.exit(0);
}
break;
case 5:
result=a%b;
break;
default:
System.out.println("Invalid Operation");
System.exit(0);
}
System.out.println("Result="+result);
}
}
11. Write a Java program to find the student grade based on the marks using switch case?
Code:
import java.util.Scanner;
class StudentGrade
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
System.out.print("Enter the marks of the student: ");
int marks=scan.nextInt();
char grade=calculategrade(marks);
System.out.println("Student grade:"+grade);
}
public static char calculategrade(int marks)
{
switch(marks/10)
{
case 10:
case 9:
return 'A';
case 8:
return 'B';
case 7:
return 'C';
case 6:
return 'D';
case 5:
return 'E';
default:
return 'F';
}
}
}

Lab No. 2: Programming Assignments on Arrays and Strings


Programming with arrays and strings (Topics: Arrays and Strings)

1. Write a Java program to find vowels and consonants in a given word?


Code:
import java.util.Scanner;

public class VowelsAndConsonants {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine().toLowerCase();
scanner.close();

int vowelCount = 0;
int consonantCount = 0;

for (int i = 0; i < word.length(); i++) {


char c = word.charAt(i);
if (Character.isLetter(c)) {
if (isVowel(c)) {
vowelCount++;
} else {
consonantCount++;
}
}
}

System.out.println("Number of vowels: " + vowelCount);


System.out.println("Number of consonants: " + consonantCount);
}

private static boolean isVowel(char c) {


c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}

2. Write a Java program to find sum and average of 10 numbers using arrays?
Code:
import java.util.Scanner;

public class SumAndAverage {

public static void main(String[] args) {


final int NUMBERS_COUNT = 10;
int[] numbers = new int[NUMBERS_COUNT];
Scanner scanner = new Scanner(System.in);

// Input numbers
System.out.println("Enter " + NUMBERS_COUNT + " numbers:");
for (int i = 0; i < NUMBERS_COUNT; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();

// Calculate sum
int sum = 0;
for (int number : numbers) {
sum += number;
}

// Calculate average
double average = (double) sum / NUMBERS_COUNT;

System.out.println("Sum of the numbers: " + sum);


System.out.println("Average of the numbers: " + average);
}
}

3. Write a Java program to find largest and smallest element of an array?


Code:
import java.util.Scanner;

public class LargestAndSmallestElement {

public static void main(String[] args) {


final int ARRAY_SIZE = 5; // You can change this size as per your
requirements
int[] array = new int[ARRAY_SIZE];
Scanner scanner = new Scanner(System.in);

// Input array elements


System.out.println("Enter " + ARRAY_SIZE + " integers:");
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = scanner.nextInt();
}
scanner.close();

// Find the largest and smallest elements


int largest = array[0];
int smallest = array[0];
for (int i = 1; i < ARRAY_SIZE; i++) {
if (array[i] > largest) {
largest = array[i];
}
if (array[i] < smallest) {
smallest = array[i];
}
}

System.out.println("Largest element: " + largest);


System.out.println("Smallest element: " + smallest);
}
}

4. Write a Java program for addition of two matrices?


Code:
import java.util.Scanner;

public class MatrixAddition {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows: ");


int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int columns = scanner.nextInt();

// Input matrices
System.out.println("Enter elements of the first matrix:");
int[][] matrix1 = inputMatrix(rows, columns, scanner);

System.out.println("Enter elements of the second matrix:");


int[][] matrix2 = inputMatrix(rows, columns, scanner);
scanner.close();
// Perform matrix addition
int[][] resultMatrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Display the result


System.out.println("Result of matrix addition:");
displayMatrix(resultMatrix);
}

// Helper method to input a matrix


private static int[][] inputMatrix(int rows, int columns, Scanner
scanner) {
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}

// Helper method to display a matrix


private static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

5. Write a Java program for multiplication of two matrices?


Code:
import java.util.Scanner;

public class MatrixMultiplication {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows for the first matrix: ");


int rowsMatrix1 = scanner.nextInt();
System.out.print("Enter the number of columns for the first matrix:
");
int columnsMatrix1 = scanner.nextInt();

System.out.print("Enter the number of rows for the second matrix:


");
int rowsMatrix2 = scanner.nextInt();
System.out.print("Enter the number of columns for the second matrix:
");
int columnsMatrix2 = scanner.nextInt();

// Check if matrix multiplication is possible


if (columnsMatrix1 != rowsMatrix2) {
System.out.println("Matrix multiplication is not possible
because the number of columns in the first matrix is not equal to the number
of rows in the second matrix.");
return;
}

// Input matrices
System.out.println("Enter elements of the first matrix:");
int[][] matrix1 = inputMatrix(rowsMatrix1, columnsMatrix1, scanner);

System.out.println("Enter elements of the second matrix:");


int[][] matrix2 = inputMatrix(rowsMatrix2, columnsMatrix2, scanner);
scanner.close();
// Perform matrix multiplication
int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);

// Display the result


System.out.println("Result of matrix multiplication:");
displayMatrix(resultMatrix);
}

// Helper method to input a matrix


private static int[][] inputMatrix(int rows, int columns, Scanner
scanner) {
int[][] matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}

// Helper method to multiply two matrices


private static int[][] multiplyMatrices(int[][] matrix1, int[][]
matrix2) {
int rowsMatrix1 = matrix1.length;
int columnsMatrix1 = matrix1[0].length;
int rowsMatrix2 = matrix2.length;
int columnsMatrix2 = matrix2[0].length;

int[][] resultMatrix = new int[rowsMatrix1][columnsMatrix2];

for (int i = 0; i < rowsMatrix1; i++) {


for (int j = 0; j < columnsMatrix2; j++) {
int sum = 0;
for (int k = 0; k < columnsMatrix1; k++) {
sum += matrix1[i][k] * matrix2[k][j];
}
resultMatrix[i][j] = sum;
}
}

return resultMatrix;
}

// Helper method to display a matrix


private static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

Sorting:

1. Write a Java Program to sort the elements using bubble sort?


Code:
import java.util.Arrays;

public class BubbleSort {

public static void main(String[] args) {


int[] arr = {64, 34, 25, 12, 22, 11, 90};

System.out.println("Original array: " + Arrays.toString(arr));


bubbleSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}

public static void bubbleSort(int[] arr) {


int n = arr.length;
boolean swapped;

for (int i = 0; i < n - 1; i++) {


swapped = false;

for (int j = 0; j < n - i - 1; j++) {


if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

// If no two elements were swapped in the inner loop, the array


is already sorted
if (!swapped) {
break;
}
}
}
}

2. Write a Java Program to sort the elements using insertion sort?


Code:
import java.util.Arrays;

public class InsertionSort {

public static void main(String[] args) {


int[] arr = {64, 34, 25, 12, 22, 11, 90};

System.out.println("Original array: " + Arrays.toString(arr));


insertionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}

public static void insertionSort(int[] arr) {


int n = arr.length;

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


int key = arr[i];
int j = i - 1;

// Move elements that are greater than the key to one position
ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}

3. Write a Java Program to sort the elements using selection sort?


Code:
import java.util.Arrays;

public class SelectionSort {

public static void main(String[] args) {


int[] arr = {64, 34, 25, 12, 22, 11, 90};

System.out.println("Original array: " + Arrays.toString(arr));


selectionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
public static void selectionSort(int[] arr) {
int n = arr.length;

for (int i = 0; i < n - 1; i++) {


int minIndex = i;

// Find the minimum element in the unsorted portion of the array


for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element of the
unsorted portion
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}

Searching:
1. Write a Java Program to search an element using linear search technique?
Code:
import java.util.Scanner;

public class LinearSearch {

public static void main(String[] args) {


int[] arr = {64, 34, 25, 12, 22, 11, 90};

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the element to search: ");
int searchElement = scanner.nextInt();
scanner.close();

int index = linearSearch(arr, searchElement);

if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
}

public static int linearSearch(int[] arr, int key) {


for (int i = 0; i < arr.length; i++) {
if (arr[i] == key) {
return i; // Element found, return its index
}
}
return -1; // Element not found in the array
}
}

2. Write a Java Program to search an element using binary search technique?


Code:
import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {

public static void main(String[] args) {


int[] arr = {11, 12, 22, 25, 34, 64, 90};

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the element to search: ");
int searchElement = scanner.nextInt();
scanner.close();
int index = binarySearch(arr, searchElement);

if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
}

public static int binarySearch(int[] arr, int key) {


int left = 0;
int right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == key) {
return mid; // Element found, return its index
} else if (arr[mid] < key) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}

return -1; // Element not found in the array


}
}

Topic: Strings

1. Write a Java program to find frequency of characters of strings?


Code:
import java.util.HashMap;
import java.util.Map;
public class CharacterFrequency {

public static void main(String[] args) {


String inputString = "Hello, World!";
Map<Character, Integer> charFrequencyMap =
getCharacterFrequency(inputString);

System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry :
charFrequencyMap.entrySet()) {
char c = entry.getKey();
int frequency = entry.getValue();
System.out.println("'" + c + "': " + frequency);
}
}

public static Map<Character, Integer> getCharacterFrequency(String


input) {
Map<Character, Integer> charFrequencyMap = new HashMap<>();

for (char c : input.toCharArray()) {


if (Character.isLetter(c)) {
c = Character.toLowerCase(c); // Consider both lowercase and
uppercase characters
charFrequencyMap.put(c, charFrequencyMap.getOrDefault(c, 0)
+ 1);
}
}

return charFrequencyMap;
}
}

2. Write a Java program to find number of vowels, consonants, digits and spaces in a given
sentence?
Code:
import java.util.Scanner;

public class SentenceAnalyzer {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = scanner.nextLine().toLowerCase();
scanner.close();

int vowelCount = 0;
int consonantCount = 0;
int digitCount = 0;
int spaceCount = 0;

for (int i = 0; i < sentence.length(); i++) {


char c = sentence.charAt(i);

if (Character.isLetter(c)) {
if (isVowel(c)) {
vowelCount++;
} else {
consonantCount++;
}
} else if (Character.isDigit(c)) {
digitCount++;
} else if (Character.isWhitespace(c)) {
spaceCount++;
}
}

System.out.println("Number of vowels: " + vowelCount);


System.out.println("Number of consonants: " + consonantCount);
System.out.println("Number of digits: " + digitCount);
System.out.println("Number of spaces: " + spaceCount);
}

private static boolean isVowel(char c) {


c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
}

3. Write a Java program to remove all the characters except alphabets yin a given sentence
(Ex: IDNO)?
Code:
import java.util.Scanner;

public class AlphabetRemover {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = scanner.nextLine();
scanner.close();

String result = removeNonAlphabets(sentence);

System.out.println("Sentence after removing non-alphabets: " +


result);
}

public static String removeNonAlphabets(String input) {


StringBuilder sb = new StringBuilder();

for (int i = 0; i < input.length(); i++) {


char c = input.charAt(i);
if (Character.isLetter(c)) {
sb.append(c);
}
}

return sb.toString();
}
}

4. Write a Java Program to implement all String Class Methods


Code:
public class StringMethods {

public static void main(String[] args) {


String str = "Hello, World!";

// length() method
int length = str.length();
System.out.println("Length of the string: " + length);

// charAt() method
char firstChar = str.charAt(0);
System.out.println("First character of the string: " + firstChar);

// indexOf() method
int index = str.indexOf("World");
System.out.println("Index of 'World': " + index);

// substring() method
String substring = str.substring(7);
System.out.println("Substring from index 7: " + substring);

// toLowerCase() and toUpperCase() methods


String lowercase = str.toLowerCase();
String uppercase = str.toUpperCase();
System.out.println("Lowercase: " + lowercase);
System.out.println("Uppercase: " + uppercase);

// replace() method
String replacedStr = str.replace('o', 'X');
System.out.println("String after replacing 'o' with 'X': " +
replacedStr);

// split() method
String[] splitArray = str.split(",");
System.out.println("Splitting the string with ',' as delimiter:");
for (String s : splitArray) {
System.out.println(s.trim());
}

// trim() method
String stringWithSpaces = " Hello, World! ";
String trimmedString = stringWithSpaces.trim();
System.out.println("Trimmed string: '" + trimmedString + "'");
}
}

5. Write a Java Program to implement all String Buffer Class and String Builder Class
Methods
Code:
public class StringBufferAndStringBuilder {

public static void main(String[] args) {


// StringBuffer examples
StringBuffer stringBuffer = new StringBuffer();

// append() method
stringBuffer.append("Hello, ");
stringBuffer.append("World!");
System.out.println("StringBuffer after appending: " + stringBuffer);
// insert() method
stringBuffer.insert(7, "Java ");
System.out.println("StringBuffer after insertion: " + stringBuffer);

// delete() method
stringBuffer.delete(0, 7);
System.out.println("StringBuffer after deletion: " + stringBuffer);

// replace() method
stringBuffer.replace(0, 5, "Hi");
System.out.println("StringBuffer after replacement: " +
stringBuffer);

// reverse() method
stringBuffer.reverse();
System.out.println("Reversed StringBuffer: " + stringBuffer);

// length() method
int length = stringBuffer.length();
System.out.println("Length of StringBuffer: " + length);

// substring() method
String substring = stringBuffer.substring(0, 4);
System.out.println("Substring of StringBuffer: " + substring);

// StringBuilder examples
StringBuilder stringBuilder = new StringBuilder();

// append() method
stringBuilder.append("Hello, ");
stringBuilder.append("World!");
System.out.println("StringBuilder after appending: " +
stringBuilder);

// insert() method
stringBuilder.insert(7, "Java ");
System.out.println("StringBuilder after insertion: " +
stringBuilder);

// delete() method
stringBuilder.delete(0, 7);
System.out.println("StringBuilder after deletion: " +
stringBuilder);

// replace() method
stringBuilder.replace(0, 2, "Hi");
System.out.println("StringBuilder after replacement: " +
stringBuilder);

// reverse() method
stringBuilder.reverse();
System.out.println("Reversed StringBuilder: " + stringBuilder);

// length() method
length = stringBuilder.length();
System.out.println("Length of StringBuilder: " + length);

// substring() method
substring = stringBuilder.substring(0, 4);
System.out.println("Substring of StringBuilder: " + substring);
}
}

6. Write a Java Program to print only alphabets in email id and count the characters in your
rgukt email id
Code:
import java.util.Scanner;

public class EmailIDAnalyzer {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter your RGUKT email ID: ");


String emailID = scanner.nextLine();
scanner.close();

String alphabetsOnly = getAlphabetsOnly(emailID);


int charCount = emailID.length();

System.out.println("Alphabets Only: " + alphabetsOnly);


System.out.println("Character Count in RGUKT email ID: " +
charCount);
}

public static String getAlphabetsOnly(String input) {


StringBuilder alphabetsOnly = new StringBuilder();

for (int i = 0; i < input.length(); i++) {


char c = input.charAt(i);
if (Character.isLetter(c)) {
alphabetsOnly.append(c);
}
}

return alphabetsOnly.toString();
}
}

7. Write a Java Program to print special characters in email id (rgukt)


Write a Java Program to print the characters in reverse order in the given string
Code:
import java.util.Scanner;

public class EmailAndReverseString {


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

System.out.print("Enter your RGUKT email ID: ");


String emailID = scanner.nextLine();
scanner.close();

System.out.println("Special characters in RGUKT email ID:");


printSpecialCharacters(emailID);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

String reversedString = reverseString(inputString);


System.out.println("Reversed string: " + reversedString);
}

public static void printSpecialCharacters(String input) {


for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '@' && c != '.') {
System.out.print(c + " ");
}
}
System.out.println();
}

public static String reverseString(String input) {


StringBuilder reversed = new StringBuilder(input);
return reversed.reverse().toString();
}
}

Lab No. 3: Programming Assignments on Classes and


Encapsulation
Problem Set: (Classes, Objects, Constructors and Encapsulation)
1. Create a class named 'Student' with a string variable 'name' and an string variable id_no'.
Assign the value of id_no as 'student id' and that of name as "Student name" by creating an
object of the class Student.
Code:
public class Student {
private String name;
private String id_no;

// Constructor to initialize the 'name' and 'id_no' variables


public Student(String name, String id_no) {
this.name = name;
this.id_no = id_no;
}

// Getter methods to access the 'name' and 'id_no' variables


public String getName() {
return name;
}

public String getId_no() {


return id_no;
}

// Main method to demonstrate creating an object of the 'Student' class


public static void main(String[] args) {
// Creating an object of the 'Student' class
Student student = new Student("Student name", "student id");

// Accessing and printing the values of 'name' and 'id_no' variables


System.out.println("Student Name: " + student.getName());
System.out.println("Student ID: " + student.getId_no());
}
}
2. Assign and print the roll number, phone number and address of two students having names
"Sam" and "John" respectively by creating two objects of the class 'Student'.
Code:
public class Student1 {
private String name;
private int rollNumber;
private String phoneNumber;
private String address;

// Constructor to initialize the attributes


public Student1(String name, int rollNumber, String phoneNumber, String
address) {
this.name = name;
this.rollNumber = rollNumber;
this.phoneNumber = phoneNumber;
this.address = address;
}

// Getter methods to access the attributes


public String getName() {
return name;
}

public int getRollNumber() {


return rollNumber;
}

public String getPhoneNumber() {


return phoneNumber;
}

public String getAddress() {


return address;
}

// Main method to demonstrate creating objects and assigning values


public static void main(String[] args) {
// Creating two objects of the 'Student' class and assigning values
Student1 sam = new Student1("Sam", 101, "1234567890", "123 Main St");
Student1 john = new Student1("John", 102, "9876543210", "456 Elm St");

// Printing the details of the students


System.out.println("Student Name: " + sam.getName());
System.out.println("Roll Number: " + sam.getRollNumber());
System.out.println("Phone Number: " + sam.getPhoneNumber());
System.out.println("Address: " + sam.getAddress());

System.out.println(); // Adding a blank line for readability

System.out.println("Student Name: " + john.getName());


System.out.println("Roll Number: " + john.getRollNumber());
System.out.println("Phone Number: " + john.getPhoneNumber());
System.out.println("Address: " + john.getAddress());
}
}

3. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units
by creating a class named 'Triangle' with a function to print the area and perimeter.
Code:
public class Triangle {
private double side1;
private double side2;
private double side3;

// Constructor to initialize the sides of the triangle


public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

// Function to calculate the area of the triangle using Heron's formula


public double calculateArea() {
double s = (side1 + side2 + side3) / 2.0;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

// Function to calculate the perimeter of the triangle


public double calculatePerimeter() {
return side1 + side2 + side3;
}

// Main method to demonstrate calculating and printing the area and


perimeter
public static void main(String[] args) {
// Creating a Triangle object with sides 3, 4, and 5 units
Triangle triangle = new Triangle(3, 4, 5);

// Calculating and printing the area and perimeter of the triangle


double area = triangle.calculateArea();
double perimeter = triangle.calculatePerimeter();

System.out.println("Area of the triangle: " + area);


System.out.println("Perimeter of the triangle: " + perimeter);
}
}

4. Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5
units by creating a class named 'Triangle' with the constructor having the three sides as its
parameters.
code:
public class Triangle1 {
private double side1;
private double side2;
private double side3;

// Constructor to initialize the sides of the triangle


public Triangle1(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

// Function to calculate the area of the triangle using Heron's formula


public double calculateArea() {
double s = (side1 + side2 + side3) / 2.0;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

// Function to calculate the perimeter of the triangle


public double calculatePerimeter() {
return side1 + side2 + side3;
}

// Main method to demonstrate calculating and printing the area and


perimeter
public static void main(String[] args) {
// Creating a Triangle1 object with sides 3, 4, and 5 units
Triangle1 triangle = new Triangle1(3, 4, 5);

// Calculating and printing the area and perimeter of the triangle


double area = triangle.calculateArea();
double perimeter = triangle.calculatePerimeter();

System.out.println("Area of the triangle: " + area);


System.out.println("Perimeter of the triangle: " + perimeter);
}
}

5. Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively
by creating a class named 'Rectangle' with a function named 'Area' which returns the area.
Length and breadth are passed as parameters to its constructor.
Code:
public class Rectangle {
private double length;
private double breadth;

// Constructor to initialize the length and breadth of the rectangle


public Rectangle(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}

// Function to calculate the area of the rectangle


public double calculateArea() {
return length * breadth;
}

// Main method to demonstrate calculating and printing the area of


rectangles
public static void main(String[] args) {
// Creating two Rectangle objects with sides (4, 5) and (5, 8)
respectively
Rectangle rectangle1 = new Rectangle(4, 5);
Rectangle rectangle2 = new Rectangle(5, 8);

// Calculating the area of the rectangles


double area1 = rectangle1.calculateArea();
double area2 = rectangle2.calculateArea();

// Printing the area of the rectangles


System.out.println("Area of Rectangle 1: " + area1);
System.out.println("Area of Rectangle 2: " + area2);
}
}

6. Print the average of three numbers entered by the user by creating a class named 'Average'
having a function to calculate and print the average without creating any object of the
Average class.
Code:
import java.util.Scanner;
public class Average {
// Function to calculate and print the average of three numbers
public static void calculateAndPrintAverage(double num1, double num2,
double num3) {
double average = (num1 + num2 + num3) / 3.0;
System.out.println("The average of the three numbers is: " + average);
}

// Main method to take user input and call the static function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


double num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");


double num2 = scanner.nextDouble();

System.out.print("Enter the third number: ");


double num3 = scanner.nextDouble();

scanner.close();

// Calling the static function to calculate and print the average


calculateAndPrintAverage(num1, num2, num3);
}
}

7. Write a program that would print the information (name, year of joining, salary, address)
of three employees by creating a class named 'Employee'. The output should be as follows:
Name Year of joining Address Robert 1994 64C- WallsStreat Sam 2000 68D- WallsStreat
John 1999 26B- WallsStreat
Code:
public class Employee {
private String name;
private int yearOfJoining;
private double salary;
private String address;

// Constructor to initialize the employee information


public Employee(String name, int yearOfJoining, double salary, String
address) {
this.name = name;
this.yearOfJoining = yearOfJoining;
this.salary = salary;
this.address = address;
}

// Method to print the employee information


public void printEmployeeInfo() {
System.out.println(name + "\t" + yearOfJoining + "\t" + salary + "\t"
+ address);
}

// Main method to demonstrate printing the employee information


public static void main(String[] args) {
// Creating three Employee objects
Employee emp1 = new Employee("Robert", 1994, 50000.0, "64C-
WallsStreat");
Employee emp2 = new Employee("Sam", 2000, 60000.0, "68D-
WallsStreat");
Employee emp3 = new Employee("John", 1999, 55000.0, "26B-
WallsStreat");

// Printing the information of the three employees


System.out.println("Name\tYear of Joining\tSalary\t\tAddress");
emp1.printEmployeeInfo();
emp2.printEmployeeInfo();
emp3.printEmployeeInfo();
}
}
(Object and Classes)
1. Write a program to implement single inheritance with example ( Parent Class-
Animal ,Child Class-Dog). [ Variables – 2 Legs, tail, Methods -2 Bark(), Eat()]
Code:
class Animal {
int legs;
boolean tail;

public void eat() {


System.out.println("Animal is eating.");
}

public void move() {


System.out.println("Animal is moving.");
}
}

class Dog extends Animal {


public void bark() {
System.out.println("Dog is barking.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.legs = 4;
dog.tail = true;

System.out.println("Dog has " + dog.legs + " legs.");


System.out.println("Dog has a tail: " + dog.tail);

dog.eat();
dog.move();
dog.bark();
}
}

2. Write a program to implement Multiple Inheritance with example( Base Class-1-


Subject1(NT), Base Class-2 Subject2(OOPs), Derived Class Student(Name)-1) and
Display the Subject marks ( MID and END SEM Marks along with student details
Id,Name,Branch
Code:
// Interface for Subject1 (NT)
interface Subject1 {
int getNTMidMarks();
int getNTEndSemMarks();
}

// Interface for Subject2 (OOPs)


interface Subject2 {
int getOOPsMidMarks();
int getOOPsEndSemMarks();
}

// Derived Class Student implementing Subject1 and Subject2


class Student implements Subject1, Subject2 {
private int id;
private String name;
private String branch;
private int ntMidMarks;
private int ntEndSemMarks;
private int oopsMidMarks;
private int oopsEndSemMarks;

public Student(int id, String name, String branch, int ntMidMarks, int
ntEndSemMarks, int oopsMidMarks, int oopsEndSemMarks) {
this.id = id;
this.name = name;
this.branch = branch;
this.ntMidMarks = ntMidMarks;
this.ntEndSemMarks = ntEndSemMarks;
this.oopsMidMarks = oopsMidMarks;
this.oopsEndSemMarks = oopsEndSemMarks;
}
@Override
public int getNTMidMarks() {
return ntMidMarks;
}

@Override
public int getNTEndSemMarks() {
return ntEndSemMarks;
}

@Override
public int getOOPsMidMarks() {
return oopsMidMarks;
}

@Override
public int getOOPsEndSemMarks() {
return oopsEndSemMarks;
}

public void displayStudentDetails() {


System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name);
System.out.println("Student Branch: " + branch);
System.out.println("Subject1 (NT) Mid Marks: " + getNTMidMarks());
System.out.println("Subject1 (NT) End Sem Marks: " +
getNTEndSemMarks());
System.out.println("Subject2 (OOPs) Mid Marks: " +
getOOPsMidMarks());
System.out.println("Subject2 (OOPs) End Sem Marks: " +
getOOPsEndSemMarks());
}
}

public class question2 {


public static void main(String[] args) {
Student student = new Student(101, "John Doe", "Computer Science",
80, 90, 85, 95);
student.displayStudentDetails();
}
}

3. Write a program to implement Multilevel Inheritance with example( Base class- Animal,
Derived Class – Dog , Derived Class- Babydog) and display the details of (Animal, Dog,
Babydog)
Code:
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks.");
}
}

class BabyDog extends Dog {


void sound() {
System.out.println("BabyDog makes a cute sound.");
}
}

public class question3 {


public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
BabyDog babyDog = new BabyDog();

System.out.println("Animal Details:");
animal.sound();

System.out.println("\nDog Details:");
dog.sound();

System.out.println("\nBabyDog Details:");
babyDog.sound();
}
}

4. Write a program to implement Hierarchical Inheritance with example( Base Class-


Student, Derived Class – student1, Derived Class-Student2) and display the student1,and
student2 details as id,name,class,branch, college
Code:
class Student {
int id;
String name;
String className;
String branch;
String college;

public Student(int id, String name, String className, String branch,


String college) {
this.id = id;
this.name = name;
this.className = className;
this.branch = branch;
this.college = college;
}

void displayDetails() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Branch: " + branch);
System.out.println("College: " + college);
}
}

class Student1 extends Student {


public Student1(int id, String name, String className, String branch,
String college) {
super(id, name, className, branch, college);
}
}
class Student2 extends Student {
public Student2(int id, String name, String className, String branch,
String college) {
super(id, name, className, branch, college);
}
}

public class question4 {


public static void main(String[] args) {
Student1 student1 = new Student1(101, "John Doe", "10th", "Science",
"ABC School");
Student2 student2 = new Student2(102, "Jane Smith", "12th",
"Commerce", "XYZ College");

System.out.println("Student1 Details:");
student1.displayDetails();

System.out.println("\nStudent2 Details:");
student2.displayDetails();
}
}

5. Write a program to implement function overloading with change in the number of


arguments for display the student details display(Id, Name), display(Id,Name, Branch)
Code:
public class StudentDetails {
// Function Overloading: Display student details with two arguments (Id
and Name)
public void display(int id, String name) {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
}

// Function Overloading: Display student details with three arguments


(Id, Name, and Branch)
public void display(int id, String name, String branch) {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Branch: " + branch);
}

public static void main(String[] args) {


StudentDetails studentDetails = new StudentDetails();

// Display student details with two arguments (Id and Name)


studentDetails.display(101, "John Doe");

System.out.println(); // Adding a blank line for readability

// Display student details with three arguments (Id, Name, and


Branch)
studentDetails.display(102, "Jane Smith", "Computer Science");
}
}

6. Write a program to implement function overloading with change in the typde of


arguments for display the student details display(Id, Name,Branch,Total Marks),
display(Id,Name, Branch,Percentage)
Code:
public class StudentDetails1 {
// Function Overloading: Display student details with four arguments
(Id, Name, Branch, and Total Marks)
public void display(int id, String name, String branch, int totalMarks)
{
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Branch: " + branch);
System.out.println("Total Marks: " + totalMarks);
}

// Function Overloading: Display student details with three arguments


(Id, Name, Branch) and calculate the percentage
public void display(int id, String name, String branch, double
percentage) {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Branch: " + branch);
System.out.println("Percentage: " + percentage);
}

public static void main(String[] args) {


StudentDetails1 studentDetails = new StudentDetails1();

// Display student details with four arguments (Id, Name, Branch,


and Total Marks)
studentDetails.display(101, "John Doe", "Computer Science", 450);

System.out.println(); // Adding a blank line for readability

// Display student details with three arguments (Id, Name, Branch)


and calculate the percentage
int marksObtained = 360;
int totalMarks = 500;
double percentage = (marksObtained * 100.0) / totalMarks;
studentDetails.display(102, "Jane Smith", "Electrical Engineering",
percentage);
}
}

7. Write a program to implement Overriding with example Base Class(Animal) and Derived
Class(Dog) variables and methods should be same display the details
Code:
class Animal {
String name;
int age;

public Animal(String name, int age) {


this.name = name;
this.age = age;
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

class Dog extends Animal {


String breed;

public Dog(String name, int age, String breed) {


super(name, age);
this.breed = breed;
}

// Method overriding: Overriding the displayDetails() method of the base


class
@Override
void displayDetails() {
super.displayDetails(); // Call the base class method using super
System.out.println("Breed: " + breed);
}
}

public class question7 {


public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Labrador");

System.out.println("Dog Details:");
dog.displayDetails();
}
}

Concepts: Object & Class


1. Write a program to create a class for student to get and print details of a student (idno,
name, class, branch).
Code:
class Student {
private int idNo;
private String name;
private String className;
private String branch;

// Constructor to initialize the student details


public Student(int idNo, String name, String className, String branch) {
this.idNo = idNo;
this.name = name;
this.className = className;
this.branch = branch;
}

// Getter methods to retrieve student details


public int getIdNo() {
return idNo;
}

public String getName() {


return name;
}

public String getClassName() {


return className;
}

public String getBranch() {


return branch;
}

// Method to print student details


public void printDetails() {
System.out.println("ID Number: " + idNo);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Branch: " + branch);
}
}

public class question1 {


public static void main(String[] args) {
// Create a student object and provide the details
Student student = new Student(101, "John Doe", "10th", "Science");

// Print the student details


student.printDetails();
}
}

2. Write a program to create a class for employee and display Employee details(empid,
empname, salary etc)
Code:
class Employee {
private int empId;
private String empName;
private double salary;
// Add more attributes as needed

// Constructor to initialize the employee details


public Employee(int empId, String empName, double salary) {
this.empId = empId;
this.empName = empName;
this.salary = salary;
}

// Getter methods to retrieve employee details


public int getEmpId() {
return empId;
}

public String getEmpName() {


return empName;
}
public double getSalary() {
return salary;
}

// Method to print employee details


public void printDetails() {
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Salary: " + salary);
// Print more attributes here if needed
}
}

public class question2 {


public static void main(String[] args) {
// Create an employee object and provide the details
Employee emp = new Employee(101, "John Doe", 50000.0);

// Print the employee details


emp.printDetails();
}
}

3. Write a program to create a class for student and display student details (id, name,
class,branch) through method (insert, display)
Code:
class Student {
private int id;
private String name;
private String className;
private String branch;

// Method to insert student details


public void insert(int id, String name, String className, String branch)
{
this.id = id;
this.name = name;
this.className = className;
this.branch = branch;
}

// Method to display student details


public void display() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Class: " + className);
System.out.println("Branch: " + branch);
}
}

public class question3 {


public static void main(String[] args) {
// Create a student object
Student student = new Student();

// Insert student details


student.insert(101, "John Doe", "10th", "Science");

// Display student details


student.display();
}
}

4. Write a program to create a class for an employee and display employee


details(empid,empname,salary) through method (insert, display)
Code:
class Employee {
private int empId;
private String empName;
private double salary;

// Method to insert employee details


public void insert(int empId, String empName, double salary) {
this.empId = empId;
this.empName = empName;
this.salary = salary;
}
// Method to display employee details
public void display() {
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Salary: " + salary);
}
}

public class question4 {


public static void main(String[] args) {
// Create an employee object
Employee emp = new Employee();

// Insert employee details


emp.insert(101, "John Doe", 50000.0);

// Display employee details


emp.display();
}
}

5. Write a program to print addition of two numbers using default constructor and
parameterized constructor?
Code:
class Addition {
private int num1;
private int num2;

// Default Constructor
public Addition() {
num1 = 0;
num2 = 0;
}

// Parameterized Constructor
public Addition(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}

// Method to perform addition and print the result


public void performAddition() {
int sum = num1 + num2;
System.out.println("Addition Result: " + sum);
}
}

public class question5 {


public static void main(String[] args) {
// Using Default Constructor
Addition defaultAddition = new Addition();
defaultAddition.performAddition();

// Using Parameterized Constructor


Addition paramAddition = new Addition(5, 10);
paramAddition.performAddition();
}
}

6. Write a program to print area of triangle using default and parameterized constructor?
import java.util.Scanner;

class Triangle {
private double base;
private double height;
private double area;

// Default Constructor
public Triangle() {
base = 0.0;
height = 0.0;
}

// Parameterized Constructor
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

// Method to calculate the area of the triangle


public void calculateArea() {
area = 0.5 * base * height;
}

// Method to print the area of the triangle


public void displayArea() {
System.out.println("Area of Triangle: " + area);
}
}

public class question6 {


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

// Using Default Constructor


Triangle defaultTriangle = new Triangle();
defaultTriangle.calculateArea();
defaultTriangle.displayArea();

// Using Parameterized Constructor


System.out.print("Enter the base of the triangle: ");
double base = scanner.nextDouble();

System.out.print("Enter the height of the triangle: ");


double height = scanner.nextDouble();

Triangle paramTriangle = new Triangle(base, height);


paramTriangle.calculateArea();
paramTriangle.displayArea();
scanner.close();
}
}

7. Write a program to differentiate the public and private access specifiers considering data
members x ,y as private and a , b as public and display the output?
Code:
class AccessSpecifiersDemo {
private int x;
private int y;
public int a;
public int b;

// Method to display the values of data members


public void display() {
System.out.println("Private Data Members (x, y): " + x + ", " + y);
System.out.println("Public Data Members (a, b): " + a + ", " + b);
}
}

public class question7 {


public static void main(String[] args) {
AccessSpecifiersDemo obj = new AccessSpecifiersDemo();

// Private data members cannot be accessed outside the class


// obj.x = 10; // Error: x has private access in
AccessSpecifiersDemo
// obj.y = 20; // Error: y has private access in
AccessSpecifiersDemo

// Public data members can be accessed outside the class


obj.a = 30;
obj.b = 40;

// Displaying the values of data members using the display() method


obj.display();
}
}

8. Write a program to implement the concept of Encapsulation by considering data


members (a,b) as private and access through public methods as set and get ?
Code:
class EncapsulationDemo {
private int a;
private int b;

// Setter method for data member 'a'


public void setA(int value) {
a = value;
}

// Getter method for data member 'a'


public int getA() {
return a;
}

// Setter method for data member 'b'


public void setB(int value) {
b = value;
}

// Getter method for data member 'b'


public int getB() {
return b;
}
}

public class question8 {


public static void main(String[] args) {
EncapsulationDemo obj = new EncapsulationDemo();
// Using setter methods to set values for data members 'a' and 'b'
obj.setA(10);
obj.setB(20);

// Using getter methods to retrieve values of data members 'a' and


'b'
int aValue = obj.getA();
int bValue = obj.getB();

// Displaying the values of data members


System.out.println("Value of a: " + aValue);
System.out.println("Value of b: " + bValue);
}
}

Lab No. 4: Implementing the concepts of Inheritance and


Array Objects
1. Write a program to implement Single Inheritance using class names as student,
mystudent and display student details.(id,name,batch,branch,college name etc) (Hint:
Base Class-1, Derived Class-1)
Code:
// Base class Student
class Student {
private int id;
private String name;
private String batch;
private String branch;
private String collegeName;

public Student(int id, String name, String batch, String branch, String collegeName) {
this.id = id;
this.name = name;
this.batch = batch;
this.branch = branch;
this.collegeName = collegeName;
}

public void displayDetails() {


System.out.println("Student ID: " + id);
System.out.println("Name: " + name);
System.out.println("Batch: " + batch);
System.out.println("Branch: " + branch);
System.out.println("College Name: " + collegeName);
}
}

// Derived class MyStudent inheriting from Student


class MyStudent extends Student {
public MyStudent(int id, String name, String batch, String branch, String
collegeName) {
super(id, name, batch, branch, collegeName);
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
MyStudent student1 = new MyStudent(101, "John Doe", "2022", "Computer
Science", "ABC College");
MyStudent student2 = new MyStudent(102, "Jane Smith", "2023", "Electrical
Engineering", "XYZ College");

System.out.println("Details of Student 1:");


student1.displayDetails();

System.out.println("\nDetails of Student 2:");


student2.displayDetails();
}
}
2. Write a program to implement Multilevel Inheritance using class names as
Grandparent, Parent and Child; Display the details of the family members? (Hint: Base
Class -1, Derived / Base Class-1, Derived Class-1)
Code:
// Grandparent class
class Grandparent {
private String grandparentName;
private int grandparentAge;

public Grandparent(String name, int age) {


grandparentName = name;
grandparentAge = age;
}

public void displayGrandparentDetails() {


System.out.println("Grandparent Name: " + grandparentName);
System.out.println("Grandparent Age: " + grandparentAge);
}
}

// Parent class inheriting from Grandparent


class Parent extends Grandparent {
private String parentName;
private int parentAge;

public Parent(String grandparentName, int grandparentAge, String name, int age) {


super(grandparentName, grandparentAge);
parentName = name;
parentAge = age;
}

public void displayParentDetails() {


displayGrandparentDetails();
System.out.println("Parent Name: " + parentName);
System.out.println("Parent Age: " + parentAge);
}
}

// Child class inheriting from Parent


class Child extends Parent {
private String childName;
private int childAge;

public Child(String grandparentName, int grandparentAge, String parentName, int


parentAge, String name, int age) {
super(grandparentName, grandparentAge, parentName, parentAge);
childName = name;
childAge = age;
}

public void displayChildDetails() {


displayParentDetails();
System.out.println("Child Name: " + childName);
System.out.println("Child Age: " + childAge);
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
Child child1 = new Child("Grandpa", 70, "Dad", 45, "Alice", 20);
Child child2 = new Child("Grandma", 65, "Mom", 42, "Bob", 18);

System.out.println("Details of Child 1:");


child1.displayChildDetails();

System.out.println("\nDetails of Child 2:");


child2.displayChildDetails();
}
}

3. Write a program to implement Multiple Inheritance using class names as Father,


Mother and Child; Display the details of family members?
(Hint: Base Class -1, Base Class-2, Derived Class-1)
Code:
// Interface Father
interface Father {
void displayFatherDetails();
}

// Interface Mother
interface Mother {
void displayMotherDetails();
}

// Class Child implementing multiple interfaces - Father and Mother


class Child implements Father, Mother {
private String childName;
private int childAge;

public Child(String name, int age) {


childName = name;
childAge = age;
}

@Override
public void displayFatherDetails() {
System.out.println("Father: John Doe");
}

@Override
public void displayMotherDetails() {
System.out.println("Mother: Jane Smith");
}
public void displayChildDetails() {
System.out.println("Child Name: " + childName);
System.out.println("Child Age: " + childAge);
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Child child = new Child("Alice", 10);

System.out.println("Details of Family Members:");


child.displayFatherDetails();
child.displayMotherDetails();
child.displayChildDetails();
}
}

4. Write a program to implement Hierarchical Inheritance using class name Student,


student1(name), student2(name), and display the student1 and student2
respectively(id,name,batch,branch,collegename) (Hint: Base Class-1, Derived Class-1,
Derived Class-2)
Code:
// Base class Student
class Student {
protected int id;
protected String name;
protected String batch;
protected String branch;
protected String collegeName;

public Student(int id, String name, String batch, String branch, String collegeName) {
this.id = id;
this.name = name;
this.batch = batch;
this.branch = branch;
this.collegeName = collegeName;
}

public void displayDetails() {


System.out.println("Student ID: " + id);
System.out.println("Name: " + name);
System.out.println("Batch: " + batch);
System.out.println("Branch: " + branch);
System.out.println("College Name: " + collegeName);
}
}

// Derived class Student1 inheriting from Student


class Student1 extends Student {
public Student1(int id, String name, String batch, String branch, String collegeName) {
super(id, name, batch, branch, collegeName);
}
}

// Derived class Student2 inheriting from Student


class Student2 extends Student {
public Student2(int id, String name, String batch, String branch, String collegeName) {
super(id, name, batch, branch, collegeName);
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
Student1 student1 = new Student1(101, "John Doe", "2022", "Computer Science",
"ABC College");
Student2 student2 = new Student2(102, "Jane Smith", "2023", "Electrical
Engineering", "XYZ College");

System.out.println("Details of Student 1:");


student1.displayDetails();

System.out.println("\nDetails of Student 2:");


student2.displayDetails();
}
}
5. Write a Program to take subjects (NT,OOPS,EDS) as Class names , attributes as MID-
I , MID-II and ENDSEM marks of each subject, use the method name as totalmarks().
Display the student marks subject wise with (id,name, branch, and marks of each
subject)
(Hint: Base Class-1, Base Class-2, Base Class-3, Derived Class-1)

Code:

// Base class for subjects

class Subject {

protected int mid1;


protected int mid2;

protected int endSem;

public Subject(int mid1, int mid2, int endSem) {

this.mid1 = mid1;

this.mid2 = mid2;

this.endSem = endSem;

public void totalMarks() {

System.out.println("MID-I Marks: " + mid1);

System.out.println("MID-II Marks: " + mid2);

System.out.println("ENDSEM Marks: " + endSem);

// Derived class NT inheriting from Subject

class NT extends Subject {

public NT(int mid1, int mid2, int endSem) {

super(mid1, mid2, endSem);

}
// Derived class OOPS inheriting from Subject

class OOPS extends Subject {

public OOPS(int mid1, int mid2, int endSem) {

super(mid1, mid2, endSem);

// Derived class EDS inheriting from Subject

class EDS extends Subject {

public EDS(int mid1, int mid2, int endSem) {

super(mid1, mid2, endSem);

public class SubjectMarksExample {

public static void main(String[] args) {

int studentID = 101;

String studentName = "John Doe";

String branch = "Computer Science";

System.out.println("Student ID: " + studentID);

System.out.println("Name: " + studentName);

System.out.println("Branch: " + branch);


System.out.println("\nMarks for NT subject:");

NT ntSubject = new NT(80, 75, 90);

ntSubject.totalMarks();

System.out.println("\nMarks for OOPS subject:");

OOPS oopsSubject = new OOPS(85, 78, 92);

oopsSubject.totalMarks();

System.out.println("\nMarks for EDS subject:");

EDS edsSubject = new EDS(75, 70, 88);

edsSubject.totalMarks();

Array of Objects

Lab No. 5: Implementing the OOPs Concepts of Abstract,


Interfaces and Polymorphism

Interfaces:
1. Write a Program to implement Drawable interface with example like Circle and
Rectangle class
Code:
// Drawable interface
interface Drawable {
void draw();
}
// Circle class implementing Drawable interface
class Circle implements Drawable {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
}

// Rectangle class implementing Drawable interface


class Rectangle implements Drawable {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with length " + length + " and width " + width);
}
}

public class DrawableExample {


public static void main(String[] args) {
Drawable circle = new Circle(5.0);
Drawable rectangle = new Rectangle(10.0, 7.0);

System.out.println("Drawing the circle:");


circle.draw();

System.out.println("Drawing the rectangle:");


rectangle.draw();
}
}
2. Write a program of java interface which provides the implementation of Bank interface.
(Interface: Bank, class: SBI,PNB,ICICI etc)
Code:
// Bank interface
interface Bank {
void withdraw(double amount);

void deposit(double amount);


}

// SBI class implementing Bank interface


class SBI implements Bank {
private double balance;

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}

// PNB class implementing Bank interface


class PNB implements Bank {
private double balance;

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}

// ICICI class implementing Bank interface


class ICICI implements Bank {
private double balance;

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal successful. Balance: " + balance);
} else {
System.out.println("Insufficient balance for withdrawal.");
}
}

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. Balance: " + balance);
} else {
System.out.println("Invalid amount for deposit.");
}
}
}

public class BankImplementationExample {


public static void main(String[] args) {
Bank sbi = new SBI();
Bank pnb = new PNB();
Bank icici = new ICICI();

// Example usage:
sbi.deposit(5000);
sbi.withdraw(2000);

pnb.deposit(10000);
pnb.withdraw(3000);

icici.deposit(8000);
icici.withdraw(5000);
}
}
3. Write a program to implement multiple inheritance in java by interface

Code:

// First Interface

interface Shape {

double getArea();

double getPerimeter();

}
// Second Interface

interface Color {

String getColor();

// Concrete class implementing both interfaces

class Circle implements Shape, Color {

private double radius;

private String color;

public Circle(double radius, String color) {

this.radius = radius;

this.color = color;

@Override

public double getArea() {

return Math.PI * radius * radius;

@Override

public double getPerimeter() {


return 2 * Math.PI * radius;

@Override

public String getColor() {

return color;

public class Main {

public static void main(String[] args) {

Circle circle = new Circle(5.0, "Red");

System.out.println("Circle Area: " + circle.getArea());

System.out.println("Circle Perimeter: " + circle.getPerimeter());

System.out.println("Circle Color: " + circle.getColor());

4. Write a Java program to create an interface Shape with the getArea() method.
Create three classes Rectangle, Circle, and Triangle that implement the Shape
interface. Implement the getArea() method for each of the three classes.

Code:

// Shape interface
interface Shape {

double getArea();

// Rectangle class implementing Shape interface

class Rectangle implements Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double getArea() {

return length * width;

// Circle class implementing Shape interface

class Circle implements Shape {

private double radius;


public Circle(double radius) {

this.radius = radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

// Triangle class implementing Shape interface

class Triangle implements Shape {

private double base;

private double height;

public Triangle(double base, double height) {

this.base = base;

this.height = height;

@Override

public double getArea() {


return 0.5 * base * height;

public class ShapeExample {

public static void main(String[] args) {

Shape rectangle = new Rectangle(4, 5);

Shape circle = new Circle(3);

Shape triangle = new Triangle(6, 8);

System.out.println("Area of Rectangle: " + rectangle.getArea());

System.out.println("Area of Circle: " + circle.getArea());

System.out.println("Area of Triangle: " + triangle.getArea());

Abstract:
1. Write a Java Program to create an Abstract class with example of Shape , Rectangle
and Circle

Code:

// Abstract class Shape

abstract class Shape {

abstract double getArea();

}
// Rectangle class extending Shape

class Rectangle extends Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

double getArea() {

return length * width;

// Circle class extending Shape

class Circle extends Shape {

private double radius;

public Circle(double radius) {


this.radius = radius;

@Override

double getArea() {

return Math.PI * radius * radius;

public class AbstractClassExample {

public static void main(String[] args) {

Shape rectangle = new Rectangle(4, 5);

Shape circle = new Circle(3);

System.out.println("Area of Rectangle: " + rectangle.getArea());

System.out.println("Area of Circle: " + circle.getArea());

2. Write a Java Program to implement Abstract Class (Bank) by extending class SBI,
PNB to implement Abstract class

Code:

// Abstract class Bank

abstract class Bank {


// Abstract method to calculate interest rate

public abstract double calculateInterest(double principalAmount);

// SBI class extending Bank

class SBI extends Bank {

@Override

public double calculateInterest(double principalAmount) {

// SBI specific interest rate calculation

return principalAmount * 0.065; // Assuming 6.5% interest rate

// PNB class extending Bank

class PNB extends Bank {

@Override

public double calculateInterest(double principalAmount) {

// PNB specific interest rate calculation

return principalAmount * 0.06; // Assuming 6% interest rate

public class Main {


public static void main(String[] args) {

double principalAmount = 10000.0;

// Create SBI object and calculate interest

Bank sbi = new SBI();

double sbiInterest = sbi.calculateInterest(principalAmount);

System.out.println("Interest by SBI: " + sbiInterest);

// Create PNB object and calculate interest

Bank pnb = new PNB();

double pnbInterest = pnb.calculateInterest(principalAmount);

System.out.println("Interest by PNB: " + pnbInterest);

3. Write a Java Program to implement Abstract class with Constructor(Bike)

Code:

// Abstract class Bike

abstract class Bike {

private String brand;

// Constructor for Bike class

public Bike(String brand) {

this.brand = brand;
}

// Abstract method

abstract void start();

// Concrete method

void displayBrand() {

System.out.println("Brand: " + brand);

// Concrete subclass Honda extending Bike

class Honda extends Bike {

public Honda(String brand) {

super(brand);

@Override

void start() {

System.out.println("Honda bike started.");

}
// Concrete subclass Yamaha extending Bike

class Yamaha extends Bike {

public Yamaha(String brand) {

super(brand);

@Override

void start() {

System.out.println("Yamaha bike started.");

public class AbstractClassWithConstructorExample {

public static void main(String[] args) {

Bike hondaBike = new Honda("Honda");

Bike yamahaBike = new Yamaha("Yamaha");

hondaBike.displayBrand();

hondaBike.start();

yamahaBike.displayBrand();
yamahaBike.start();

Polymorphism:
1. Explain about Compile Time Polymorphism(Method Overloading) and
Runtime Polymorphism(Method Overriding)
Code:
class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double values


public double add(double a, double b) {
return a + b;
}
}

public class MethodOverloadingExample {


public static void main(String[] args) {
MathOperations math = new MathOperations();

int result1 = math.add(10, 20);


int result2 = math.add(5, 10, 15);
double result3 = math.add(2.5, 3.5);

System.out.println("Result 1: " + result1);


System.out.println("Result 2: " + result2);
System.out.println("Result 3: " + result3);
}
}
Run time

class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.sound(); // Outputs: "Dog barks"


animal2.sound(); // Outputs: "Cat meows"
}
}
2. Explain about Dynamic Method Dispatch with suitable example
Code:
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle extends Shape {


@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}

public class DynamicMethodDispatchExample {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();

shape1.draw(); // Output: "Drawing a circle"


shape2.draw(); // Output: "Drawing a rectangle"
}
}
Lab No. 6: Programming Assignments on File Handling
1. Write a Java Program to explain the concept of File Reader, File Writer, File Buffer
Reader, Buffer Writer with suitable examples.
Code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileIOExample {


public static void main(String[] args) {
String sourceFile = "input.txt";
String destinationFile = "output.txt";

try {
// Reading data from the source file using FileReader and BufferedReader
FileReader fileReader = new FileReader(sourceFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);

// Writing data to the destination file using FileWriter and BufferedWriter


FileWriter fileWriter = new FileWriter(destinationFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String line;
while ((line = bufferedReader.readLine()) != null) {
// Process the data (e.g., convert to uppercase) before writing to the destination file
String processedLine = line.toUpperCase();
bufferedWriter.write(processedLine);
bufferedWriter.newLine(); // Add a new line after each processed line
}

// Close the readers and writers to release resources


bufferedReader.close();
bufferedWriter.close();

System.out.println("Data processed and written to the destination file successfully.");


} catch (IOException e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
}
2. Write a Java Program to Create a Newfile in the specified path(Desktop or Documents or
Downloads)
Code:
import java.io.File;
import java.io.IOException;

public class CreateNewFileExample {


public static void main(String[] args) {
String filePath = "C:/example/newfile.txt"; // Specify the desired file path here

try {
File file = new File(filePath);

if (file.createNewFile()) {
System.out.println("New file created successfully at: " + filePath);
} else {
System.out.println("File already exists at: " + filePath);
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file: " + e.getMessage());
}
}
}
3. Write a Java Program to Get File Information from the exiting file or create a new file
Code:
import java.io.File;

public class FileInfoExample {


public static void main(String[] args) {
String filePath = "C:/example/sample.txt"; // Specify the path of the existing file here

File file = new File(filePath);

if (file.exists()) {
System.out.println("File Name: " + file.getName());
System.out.println("Absolute Path: " + file.getAbsolutePath());
System.out.println("File Size (bytes): " + file.length());
System.out.println("Is Directory: " + file.isDirectory());
System.out.println("Is File: " + file.isFile());
System.out.println("Can Read: " + file.canRead());
System.out.println("Can Write: " + file.canWrite());
System.out.println("Can Execute: " + file.canExecute());
} else {
System.out.println("File does not exist.");
}
}
}
4. Write a Java Program to write into file using File Writer
Code:
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {


public static void main(String[] args) {
String filePath = "output.txt"; // Specify the desired file path here

try {
// Create a FileWriter object with the specified file path
FileWriter fileWriter = new FileWriter(filePath);

// Write data to the file using the write() method


fileWriter.write("Hello, this is a test content.\n");
fileWriter.write("Writing data to a file using FileWriter.\n");

// Close the FileWriter to release resources and flush the data to the file
fileWriter.close();

System.out.println("Data written to the file successfully.");


} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}
}
5. Write a Java Program to read file from existing file
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFileExample {


public static void main(String[] args) {
String filePath = "C:/example/sample.txt"; // Specify the path of the existing file here

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
}
}
6. Write a Java Program to delete a File from existing File
Code:
import java.io.File;

public class DeleteFileExample {


public static void main(String[] args) {
String filePath = "C:/example/sample.txt"; // Specify the path of the file to be deleted here

File file = new File(filePath);

if (file.exists()) {
if (file.delete()) {
System.out.println("File deleted successfully: " + filePath);
} else {
System.out.println("Failed to delete the file: " + filePath);
}
} else {
System.out.println("File does not exist: " + filePath);
}
}
}

Lab No. 7: Programming Exercises on Packages and


Exception Handling

Packages:
1. Write a Java Program to create a Package
Code:
import com.example.mypackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
// Use the methods of MyClass here
}
}
2. Write a Java Program to create a class with reference to package of another class
Code:
package com.example.mypackage;

public class MyClass {


public void displayMessage() {
System.out.println("Hello from MyClass!");
}
}
public class Main {
public static void main(String[] args) {
com.example.mypackage.MyClass obj = new com.example.mypackage.MyClass();
obj.displayMessage();
}
}
3. Write a Java Program to access a Package from another package with example
Code:
package com.example.package1;

public class ClassInPackage1 {


public void methodInPackage1() {
System.out.println("Method in Package 1");
}
}

package com.example.package2;

import com.example.package1.ClassInPackage1;

public class ClassInPackage2 {


public static void main(String[] args) {
ClassInPackage1 obj = new ClassInPackage1();
obj.methodInPackage1();
}
}

Managing Errors and Exceptions: (Exception Handling)


1. Explain types of Exceptions with examples
Code:
public class TypesOfExceptions {
public static void main(String[] args) {
try {
// Arithmetic Exception
int result = divideNumbers(10, 0);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
}

try {
// Array Index Out of Bounds Exception
int[] arr = {1, 2, 3};
int element = getElementAtIndex(arr, 5);
System.out.println("Element at index: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
}

try {
// Null Pointer Exception
String str = null;
int length = str.length();
System.out.println("Length of the string: " + length);
} catch (NullPointerException e) {
System.out.println("Null Pointer Exception: " + e.getMessage());
}

try {
// Number Format Exception
String numStr = "abc";
int number = Integer.parseInt(numStr);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
}
}

// Method to divide two numbers and throw ArithmeticException if the divisor is zero.
private static int divideNumbers(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return dividend / divisor;
}

// Method to get an element at a specific index in an array and throw


ArrayIndexOutOfBoundsException.
private static int getElementAtIndex(int[] arr, int index) {
return arr[index];
}
}
2. Write a Program using finally statement in exception
Code:
public class FinallyStatementExample {
public static void main(String[] args) {
try {
int result = divideNumbers(10, 0);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}

try {
int[] arr = {1, 2, 3};
int element = getElementAtIndex(arr, 5);
System.out.println("Element at index: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}

private static int divideNumbers(int dividend, int divisor) {


if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return dividend / divisor;
}

private static int getElementAtIndex(int[] arr, int index) {


return arr[index];
}
}
3. Write a program to implement multiple catch statements
Code:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int result = divideNumbers(10, 0);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Null Pointer Exception: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}

private static int divideNumbers(int dividend, int divisor) {


if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
return dividend / divisor;
}
}
4. Write a Program to explain throwing our own exceptions

Code:

class MyCustomException extends Exception {

public MyCustomException(String message) {

super(message);

public class CustomExceptionExample {

public static void main(String[] args) {

try {

int result = divideNumbers(10, 0);

System.out.println("Result of division: " + result);

} catch (MyCustomException e) {
System.out.println("Custom Exception: " + e.getMessage());

private static int divideNumbers(int dividend, int divisor) throws MyCustomException {

if (divisor == 0) {

throw new MyCustomException("Cannot divide by zero!");

return dividend / divisor;

Lab No. 9: Implementing the concepts of Multi-Threading

Multithreading
1. Implementation of Thread using Inheritance
Code:
// Define a custom thread class by extending Thread
class MyThread extends Thread {
@Override
public void run() {
// Define the task you want the thread to perform
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
// Create an instance of your custom thread
MyThread myThread = new MyThread();

// Start the thread


myThread.start();

// You can do other tasks in the main thread while the custom thread is running
for (int i = 1; i <= 3; i++) {
System.out.println("Main thread is running: " + i);
try {
Thread.sleep(2000); // Pause the main thread for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. Implementation of Thread using Runnable Interface
Code:
// Define a class that implements the Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
// Define the task you want the thread to perform
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Pause the thread for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class Main {


public static void main(String[] args) {
// Create an instance of the class that implements Runnable
MyRunnable myRunnable = new MyRunnable();

// Create a Thread object and pass the MyRunnable instance to it


Thread thread = new Thread(myRunnable);

// Start the thread


thread.start();

// You can do other tasks in the main thread while the custom thread is running
for (int i = 1; i <= 3; i++) {
System.out.println("Main thread is running: " + i);
try {
Thread.sleep(2000); // Pause the main thread for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. Life Cycle of a Thread (Program to implement thread class)
Code:
public class ThreadLifeCycleDemo {
public static void main(String[] args) {
// Create a custom Runnable implementation
Runnable myRunnable = () -> {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " is in 'Runnable' state.");

// Simulate some work


try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(thread.getName() + " is in 'Running' state.");


};

// Create a thread using the Runnable


Thread thread = new Thread(myRunnable, "MyThread");

// Start the thread


thread.start();

// Main thread message


System.out.println(Thread.currentThread().getName() + " is in 'Runnable' state.");

try {
// Wait for the custom thread to complete its work
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Thread terminated message


System.out.println(Thread.currentThread().getName() + " is in 'Terminated' state.");
}
}
4. Thread Synchronization implementation with example
Code:
class Counter {
private int count = 0;

// Synchronized method to increment the counter


public synchronized void increment() {
count++;
}

// Synchronized method to get the counter value


public synchronized int getCount() {
return count;
}
}

public class ThreadSynchronizationDemo {


public static void main(String[] args) {
Counter counter = new Counter();

// Create multiple threads that increment the counter


Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread thread2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

// Start the threads


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

try {
// Wait for both threads to complete
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Get the final counter value


int finalCount = counter.getCount();
System.out.println("Final counter value: " + finalCount);
}
}
5. Example synchronized method by using anonymous class
Code:
public class SynchronizedMethodWithAnonymousClass {
private int count = 0;

public static void main(String[] args) {


SynchronizedMethodWithAnonymousClass obj = new
SynchronizedMethodWithAnonymousClass();

// Create multiple threads that increment the counter using an anonymous class
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
obj.increment();
}
});

Thread thread2 = new Thread(new Runnable() {


@Override
public void run() {
obj.increment();
}
});

// Start the threads


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

try {
// Wait for both threads to complete
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Get the final counter value


int finalCount = obj.getCount();
System.out.println("Final counter value: " + finalCount);
}

// Synchronized method to increment the counter


public synchronized void increment() {
for (int i = 0; i < 1000; i++) {
count++;
}
}

// Synchronized method to get the counter value


public synchronized int getCount() {
return count;
}
}
6. Implementing thread methods with example

Code:

public class ThreadMethodsExample {

public static void main(String[] args) {

// Example of creating a thread using the Thread class

Thread thread1 = new Thread(() -> {

System.out.println("Thread 1 is running.");

});

// Example of setting thread priority

thread1.setPriority(Thread.MIN_PRIORITY);

// Example of setting a thread name

thread1.setName("Thread 1");

// Start the thread


thread1.start();

// Example of creating a thread using the Runnable interface

Runnable myRunnable = () -> {

System.out.println("Thread 2 is running.");

};

Thread thread2 = new Thread(myRunnable);

thread2.start();

// Example of sleeping a thread

try {

Thread.sleep(1000); // Pause the main thread for 1 second

} catch (InterruptedException e) {

e.printStackTrace();

// Example of checking if a thread is alive

System.out.println("Is Thread 1 alive? " + thread1.isAlive());

System.out.println("Is Thread 2 alive? " + thread2.isAlive());

// Example of joining a thread


try {

thread1.join();

thread2.join();

} catch (InterruptedException e) {

e.printStackTrace();

// Example of getting the thread state

System.out.println("Thread 1 state: " + thread1.getState());

System.out.println("Thread 2 state: " + thread2.getState());

// Example of interrupting a thread

Thread thread3 = new Thread(() -> {

try {

while (!Thread.currentThread().isInterrupted()) {

System.out.println("Thread 3 is running.");

Thread.sleep(500); // Pause the thread for 0.5 seconds

} catch (InterruptedException e) {

System.out.println("Thread 3 is interrupted.");

}
});

thread3.start();

// Example of interrupting the thread after 2 seconds

try {

Thread.sleep(2000);

thread3.interrupt();

} catch (InterruptedException e) {

e.printStackTrace();

// Example of getting the current thread

Thread currentThread = Thread.currentThread();

System.out.println("Current thread name: " + currentThread.getName());

System.out.println("Current thread priority: " + currentThread.getPriority());

Lab No. 10: Programming Exercises on Event Handling


1. Explain about AWT components and Event Handling (Action Listerner)
Answer:-
AWT (Abstract Window Toolkit) is a part of the Java Foundation Classes (JFC) that
provides a set of GUI (Graphical User Interface) components for creating graphical user
interfaces in Java applications. AWT components are platform-independent and can be
used to build interactive and user-friendly graphical interfaces.

Some commonly used AWT components include:


1. `Button`: A simple button that can be clicked by the user to trigger an action.
2. `Label`: A component used to display text or an image.
3. `TextField`: A single-line text input field where the user can enter text.
4. `TextArea`: A multi-line text input field.
5. `Checkbox`: A component that allows the user to select one or more options from a
list.
6. `RadioButton`: A component that allows the user to select a single option from a list.
7. `ComboBox`: A dropdown menu that allows the user to select an item from a list of
choices.
8. `List`: A list of items from which the user can select one or more items.

Event Handling in AWT:


Event handling is a mechanism in Java that allows the program to respond to user
interactions with GUI components. When a user interacts with a GUI component (e.g.,
clicks a button or selects an item from a list), an event is generated. The program can
register listeners for specific types of events and then perform actions in response to
those events.

The `ActionListener` interface is a part of the `java.awt.event` package and is used for
handling action events, such as button clicks. It contains a single method
`actionPerformed(ActionEvent e)` that needs to be implemented.

Example of using ActionListener:


Let's create a simple Java program that uses a button and an `ActionListener` to handle
the button click event:

import java.awt.*;
import java.awt.event.*;

public class ActionListenerExample extends Frame implements ActionListener {


private Button button;

public ActionListenerExample() {
button = new Button("Click Me");
button.setBounds(100, 100, 80, 30);
add(button);

// Register the ActionListener for the button


button.addActionListener(this);

setSize(300, 200);
setTitle("ActionListener Example");
setLayout(null);
setVisible(true);
}

// Implementing actionPerformed method from ActionListener interface


public void actionPerformed(ActionEvent e) {
// Code to be executed when the button is clicked
System.out.println("Button Clicked!");
}

public static void main(String[] args) {


new ActionListenerExample();
}
}
```

In this example, we create a window using `Frame` and add a button to it. We register an
instance of `ActionListenerExample` (which implements `ActionListener`) as the listener
for the button. When the button is clicked, the `actionPerformed()` method will be called,
and it will print "Button Clicked!" to the console.

You might also like