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

Jaimin_Labmanual_Java

Uploaded by

vadhelsarthak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Jaimin_Labmanual_Java

Uploaded by

vadhelsarthak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Government of Gujarat

L. D. College of Engineering

LABORATORY MANUAL
MCA

Semester I

Object Oriented Programming using JAVA

Year 2024-25

Jaimin D Chandarana
(245160694005)

L. D. College of Engineering
Ahmedabad -380015
Practical 1
AIM: Install the JDK (Download the JDK and install it.)
 Set path of the jdk/bin directory.
 Create the java program
 Compile and run the java program
Write a simple “Hello World” java program, compilation, debugging, executing using java
compiler and interpreter.

Program
 Code:

public class Main {


public static void main(String[] args) {

System.out.println("Hello world!");
}
}

 Output:
Practical 2
AIM: Write a program to pass Starting and Ending limit and print all prime numbers
and Fibonacci numbers between this ranges.
Program
 Code:
import java.util.Scanner;
public class PrimeAndFibonacci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the starting limit: ");


int start = scanner.nextInt();

System.out.print("Enter the ending limit: ");


int end = scanner.nextInt();

System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println("\nFibonacci numbers between " + start + " and " + end + ":");
int a = 0, b = 1;
while (a <= end) {
if (a >= start) {
System.out.print(a + " ");
}
int next = a + b;
a = b;
b = next;
}
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
 Output:
Practical 3
AIM: Write a java program to check whether number is palindrome or not. Input: 528 Output: It is
not palindrome number Input: 545 Output: It is not palindrome number
Program
 Code:
import java.util.Scanner;

public class PalindromeCheck {


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

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


int number = scanner.nextInt();

if (isPalindrome(number)) {
System.out.println(number + " is a palindrome number.");
} else {
System.out.println(number + " is not a palindrome number.");
}
}

public static boolean isPalindrome(int num) {


int original = num;
int reversed = 0;

while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

return original == reversed;


}
}

 Output:
Practical 4
AIM: Write a java program to print value of x^n. Input: x=5 Input: n=3 Output: 125
Program
 Code:
import java.util.Scanner;

public class PowerCalculation {


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

System.out.print("Enter the base (x): ");


int x = scanner.nextInt();

System.out.print("Enter the exponent (n): ");


int n = scanner.nextInt();

int result = power(x, n);


System.out.println(x + "^" + n + " = " + result);
}

public static int power(int base, int exponent) {


int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
}

 Output:
Practical 5
AIM: Write a java program to check Armstrong number. Input: 153 Output: Armstrong number
Input: 22 Output: not Armstrong number
Program
 Code:
import java.util.Scanner;

public class ArmstrongCheck {


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

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


int number = scanner.nextInt();

if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}

public static boolean isArmstrong(int num) {


int original = num;
int sum = 0;
int digits = String.valueOf(num).length();

while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}

return sum == original;


}
}

 Output:
Practical 6
AIM: Write a program in Java to find minimum of three numbers using conditional operator.
Program
 Code:
import java.util.Scanner;

public class MinimumOfThree {


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

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


int num1 = scanner.nextInt();

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


int num2 = scanner.nextInt();

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


int num3 = scanner.nextInt();

int min = (num1 < num2) ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);

System.out.println("The minimum of the three numbers is: " + min);


}
}

 Output:
Practical 7
AIM: Write a java program which should display maximum number of given 4 numbers..
Program
 Code:
import java.util.Scanner;

public class MaximumOfFour {


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

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


int num1 = scanner.nextInt();

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


int num2 = scanner.nextInt();

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


int num3 = scanner.nextInt();

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


int num4 = scanner.nextInt();

int max = num1;

if (num2 > max) {


max = num2;
}
if (num3 > max) {
max = num3;
}
if (num4 > max) {
max = num4;
}

System.out.println("The maximum of the four numbers is: " + max);


}
}

 Output:
Practical 8
AIM: Write a program in Java to multiply two matrix. Declare a class Matrix where 2D array
is declared as instance variable and array should be initialized, within class.
Program
 Code:
import java.util.Scanner;

class Matrix {
int[][] matrix;
int rows, cols;

public Matrix(int rows, int cols) {


this.rows = rows;
this.cols = cols;
matrix = new int[rows][cols];
}

public void inputMatrix(Scanner scanner) {


System.out.println("Enter elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}
public void displayMatrix() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

public static Matrix multiply(Matrix m1, Matrix m2) {


if (m1.cols != m2.rows) {
throw new IllegalArgumentException("Matrix multiplication not possible");
}

Matrix result = new Matrix(m1.rows, m2.cols);


for (int i = 0; i < m1.rows; i++) {
for (int j = 0; j < m2.cols; j++) {
for (int k = 0; k < m1.cols; k++) {
result.matrix[i][j] += m1.matrix[i][k] * m2.matrix[k][j];
}
}
}
return result;
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows and columns for the first matrix: ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();

Matrix m1 = new Matrix(rows1, cols1);


m1.inputMatrix(scanner);

System.out.print("Enter the number of rows and columns for the second matrix: ");
int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

if (cols1 != rows2) {
System.out.println("Matrix multiplication not possible with the given dimensions.");
return;
}

Matrix m2 = new Matrix(rows2, cols2);


m2.inputMatrix(scanner);

Matrix result = Matrix.multiply(m1, m2);

System.out.println("Resultant matrix after multiplication:");


result.displayMatrix();
}
}
 Output:
Practical 9
AIM: Write a java program to create a class “Matrix” that would contain integer values having
varied Numbers of columns for each row. Print row-wise sum of the integer values for each row.
Program
 Code:
import java.util.Scanner;

class Matrix {
int[][] matrix;
int rows;

public Matrix(int rows) {


this.rows = rows;
matrix = new int[rows][];
}
public void inputMatrix(Scanner scanner) {
for (int i = 0; i < rows; i++) {
System.out.print("Enter the number of columns for row " + (i + 1) + ": ");
int cols = scanner.nextInt();
matrix[i] = new int[cols];
System.out.println("Enter elements for row " + (i + 1) + ":");
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}
public void printRowWiseSum() {
for (int i = 0; i < rows; i++) {
int sum = 0;
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
System.out.println("Sum of row " + (i + 1) + ": " + sum);
}
}
}

public class MatrixSum {


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

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


int rows = scanner.nextInt();

Matrix matrix = new Matrix(rows);


matrix.inputMatrix(scanner);
matrix.printRowWiseSum();
}
}
 Output:
Practical 10
AIM: Write a Java application which takes several command line arguments, which are supposed to be
names of students and prints output as given below: (Suppose we enter 3 names then output should be
as follows)..
Number of arguments = 3 1. First Student Name is = Arun 2. Second Student Name is = Hiren
3. Third Student Name is = Hitesh
Program
 Code:
public class StudentNames {
public static void main(String[] args) {
int numberOfArguments = args.length;
System.out.println("Number of arguments = " + numberOfArguments);

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


System.out.println((i + 1) + ". " + getOrdinal(i + 1) + " Student Name is = " + args[i]);
}
}

private static String getOrdinal(int number) {


switch (number) {
case 1:
return "First";
case 2:
return "Second";
case 3:
return "Third";
default:
return number + "th";
}
}
}

 Output:
Practical 11
AIM: Write a Java application to count and display frequency of letters and digits from the String
given by user as command-line argument.
Program
 Code:
public class FrequencyCounter {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide a string as a command-line argument.");
return;
}

String input = args[0];


int[] letterCount = new int[26];
int[] digitCount = new int[10];

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


if (Character.isLetter(ch)) {
letterCount[Character.toLowerCase(ch) - 'a']++;
} else if (Character.isDigit(ch)) {
digitCount[ch - '0']++;
}
}

System.out.println("Frequency of letters:");
for (int i = 0; i < letterCount.length; i++) {
if (letterCount[i] > 0) {
System.out.println((char) (i + 'a') + ": " + letterCount[i]);
}
}

System.out.println("Frequency of digits:");
for (int i = 0; i < digitCount.length; i++) {
if (digitCount[i] > 0) {
System.out.println(i + ": " + digitCount[i]);
}
}
}
}
 Output:
Practical 12
AIM: Create a class “Student” that would contain enrollment No, name, and gender and marks as
instance variables and count as static variable which stores the count of the objects; constructors
and display(). Implement constructors to initialize instance variables. Also demonstrate constructor
chaining. Create objects of class “Student” and displays all values of objects.
Program
 Code:
class Student {
private int enrollmentNo;
private String name;
private String gender;
private int marks;
private static int count = 0;

public Student() {
this(0, "Unknown", "Unknown", 0);
}

public Student(int enrollmentNo, String name) {


this(enrollmentNo, name, "Unknown", 0);
}

public Student(int enrollmentNo, String name, String gender, int marks) {


this.enrollmentNo = enrollmentNo;
this.name = name;
this.gender = gender;
this.marks = marks;
count++;
}

public void display() {


System.out.println("Enrollment No: " + enrollmentNo);
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Marks: " + marks);
}

public static int getCount() {


return count;
}

public static void main(String[] args) {


Student s1 = new Student(201, "Arjun", "Male", 88);
Student s2 = new Student(202, "Priya", "Female", 92);
Student s3 = new Student(203, "Ravi", "Male", 75);

System.out.println("Student 1:");
s1.display();
System.out.println();
System.out.println("Student 2:");
s2.display();
System.out.println();

System.out.println("Student 3:");
s3.display();
System.out.println();

System.out.println("Total number of Student objects created: " + Student.getCount());


}
}

 Output:
Practical 13
AIM: Write a program in Java to demonstrate use of this keyword. Check whether this can
access the Static variables of the class or not. [Refer class student in Q12 to perform the task]
Program
 Code:
public class Student {
private String enrollmentNo;
private String name;
private String gender;
private int marks;
private static int count = 0; // Static variable to count objects

public Student(String enrollmentNo, String name, String gender, int marks) {


this.enrollmentNo = enrollmentNo;
this.name = name;
this.gender = gender;
this.marks = marks;
count++; // Increment object count
}

public Student(String enrollmentNo, String name, String gender) {


this(enrollmentNo, name, gender, 0); // Call the primary constructor
}

public Student() {
this("Unknown", "Unknown", "Unknown", 0); // Call the primary constructor
}

public void display() {


System.out.println("Enrollment No: " + this.enrollmentNo);
System.out.println("Name: " + this.name);
System.out.println("Gender: " + this.gender);
System.out.println("Marks: " + this.marks);
}

public static int getCount() {


return count;
}

public void demonstrateThisKeyword() {


System.out.println("Using 'this' keyword:");
System.out.println("Enrollment No (this.enrollmentNo): " + this.enrollmentNo);
System.out.println("Name (this.name): " + this.name);
System.out.println("Marks (this.marks): " + this.marks);
// Cannot use 'this' to access static variable directly, must use class name
System.out.println("Count (Student.count): " + Student.count);
}

public static void main(String[] args) {


Student s1 = new Student("E001", "Alice", "Female", 85);
Student s2 = new Student("E002", "Bob", "Male");

System.out.println("Demonstrating 'this' with Student 1:");


s1.demonstrateThisKeyword();

System.out.println("\nDemonstrating 'this' with Student 2:");


s2.demonstrateThisKeyword();
System.out.println("\nTotal Students: " + Student.getCount());
}
}
 Output:
Practical 14
AIM: Create a class “Rectangle” that would contain length and width as an instance variable
Count as a static variable. and count
 Code:
class Rectangle { Program
private double length;
private double width;
private static int count = 0;

static {
System.out.println("Static initializer block executed.");
count = 0;
}

{
System.out.println("Initializer block executed.");
length = 0;
width = 0;
}

public Rectangle() {
this(1.0, 1.0);
}

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
count++;
}

public Rectangle(Rectangle other) {


this(other.length, other.width);
}

public double getArea() {


return length * width;
}

public void display() {


System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + getArea());
}

public static int getCount() {


return count;
}
public static void main(String[] args) {
System.out.println("Creating first rectangle:");
Rectangle r1 = new Rectangle();
r1.display();
System.out.println();

System.out.println("Creating second rectangle:");


Rectangle r2 = new Rectangle(5.0, 3.0);
r2.display();
System.out.println();

System.out.println("Creating third rectangle (copy of second):");


Rectangle r3 = new Rectangle(r2);
r3.display();
System.out.println();

System.out.println("Total number of Rectangle objects created: " + Rectangle.getCount());


}
}

 Output:
Practical 15
AIM: Write a java program static block which will be executed before main ( ) method in a Class.
Program
 Code:
public class StaticBlockDemo {
static {
System.out.println("Static block executed.");
}

public static void main(String[] args) {


System.out.println("Main method executed.");
}
}

 Output:
Practical 16
AIM:. Write programs in Java to use Wrapper class of each primitive data types.
Program
 Code:
public class WrapperClassesDemo {
public static void main(String[] args) {
Byte byteWrapper = Byte.valueOf((byte) 10);
byte bytePrimitive = byteWrapper.byteValue();
System.out.println("Byte Wrapper: " + byteWrapper);
System.out.println("Byte Primitive: " + bytePrimitive);

Short shortWrapper = Short.valueOf((short) 100);


short shortPrimitive = shortWrapper.shortValue();
System.out.println("Short Wrapper: " + shortWrapper);
System.out.println("Short Primitive: " + shortPrimitive);
Integer intWrapper = Integer.valueOf(1000);
int intPrimitive = intWrapper.intValue();
System.out.println("Integer Wrapper: " + intWrapper);
System.out.println("Integer Primitive: " + intPrimitive);

Long longWrapper = Long.valueOf(10000L);


long longPrimitive = longWrapper.longValue();
System.out.println("Long Wrapper: " + longWrapper);
System.out.println("Long Primitive: " + longPrimitive);

Float floatWrapper = Float.valueOf(10.5f);


float floatPrimitive = floatWrapper.floatValue();
System.out.println("Float Wrapper: " + floatWrapper);
System.out.println("Float Primitive: " + floatPrimitive);

Double doubleWrapper = Double.valueOf(20.5);


double doublePrimitive = doubleWrapper.doubleValue();
System.out.println("Double Wrapper: " + doubleWrapper);
System.out.println("Double Primitive: " + doublePrimitive);

Character charWrapper = Character.valueOf('A');


char charPrimitive = charWrapper.charValue();
System.out.println("Character Wrapper: " + charWrapper);
System.out.println("Character Primitive: " + charPrimitive);
Boolean booleanWrapper = Boolean.valueOf(true);
boolean booleanPrimitive = booleanWrapper.booleanValue();
System.out.println("Boolean Wrapper: " + booleanWrapper);
System.out.println("Boolean Primitive: " + booleanPrimitive);
}
}
 Output:
Practical 17
AIM: Write a class “circle” with radius as data member and count the number of instances created
using default constructor only. [Constructor Chaining]
Program
 Code:
class Circle {
private double radius;
private static int count = 0;

static {
System.out.println("Static initializer block executed.");
}

{
System.out.println("Initializer block executed.");
}

public Circle() {
this(1.0); // Calls the parameterized constructor
count++;
}

public Circle(double radius) {


this.radius = radius;
}

public Circle(Circle other) {


this(other.radius);
}

public void display() {


System.out.println("Radius: " + this.radius);
}

public static int getCount() {


return count;
}

public static void main(String[] args) {


System.out.println("Creating first circle:");
Circle c1 = new Circle();
c1.display();
System.out.println();

System.out.println("Creating second circle:");


Circle c2 = new Circle(5.0);
c2.display();
System.out.println();
System.out.println("Creating third circle (copy of second):");
Circle c3 = new Circle(c2);
c3.display();
System.out.println();

System.out.println("Total number of Circle objects created using the default constructor: " +
Circle.getCount());
}
}

 Output:
Practical 18
AIM: Create a class “Vehicle” with instance variable vehicle_type. Inherit the class in a class
called “Car” with instance model_type, company name etc. display the information of the vehicle
by defining the display() in both super and sub class [Method Overriding]
Program
 Code:
class Vehicle {
protected String vehicleType;

public Vehicle(String vehicleType) {


this.vehicleType = vehicleType;
}

public void display() {


System.out.println("Vehicle Type: " + vehicleType);
}
}

class Car extends Vehicle {


private String modelType;
private String companyName;

public Car(String vehicleType, String modelType, String companyName) {


super(vehicleType); // Call the constructor of the superclass (Vehicle)
this.modelType = modelType;
this.companyName = companyName;
}

@Override
public void display() {
super.display(); // Call the display method of the superclass (Vehicle)
System.out.println("Model Type: " + modelType);
System.out.println("Company Name: " + companyName);
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car("Sedan", "Model S", "Tesla");
car.display();
}
}

 Output:
Practical 19
AIM: Create a class “Account” containing accountNo, and balance as an instance variable. Derive
the Account class into two classes named “Savings” and “Current”. The “Savings” class should
contain instance variable named interestRate, and the “Current” class should contain instance
variable called overdraftLimit. Define appropriate methods for all the classes to enable
functionalities to check balance, deposit, and withdraw amount in Savings and Current account.
[Ensure that the Account class cannot be instantiated.]
Program
 Code:
abstract class Account {
protected int accountNo;
protected double balance;

public Account(int accountNo, double balance) {


this.accountNo = accountNo;
this.balance = balance;
}

public double checkBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}

public abstract void withdraw(double amount);


}

class Savings extends Account {


private double interestRate;

public Savings(int accountNo, double balance, double interestRate) {


super(accountNo, balance);
this.interestRate = interestRate;
}

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

public void display() {


System.out.println("Savings Account No: " + accountNo);
System.out.println("Balance: " + balance);
System.out.println("Interest Rate: " + interestRate);
}
}

class Current extends Account {


private double overdraftLimit;

public Current(int accountNo, double balance, double overdraftLimit) {


super(accountNo, balance);
this.overdraftLimit = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}

public void display() {


System.out.println("Current Account No: " + accountNo);
System.out.println("Balance: " + balance);
System.out.println("Overdraft Limit: " + overdraftLimit);
}
}

public class Main {


public static void main(String[] args) {
Savings savingsAccount = new Savings(101, 5000.0, 0.05);
Current currentAccount = new Current(102, 3000.0, 1000.0);

savingsAccount.deposit(1000);
savingsAccount.withdraw(2000);
savingsAccount.display();

System.out.println();

currentAccount.deposit(2000);
currentAccount.withdraw(4000);
currentAccount.display();
}
}
 Output:
Practical 20
AIM: Write a program in Java in which a subclass constructor invokes the constructor of the
super class and instantiate the values. [ refer class Account and sub classes savingAccount and
CurrentAccount in Q 19 for this task]
Program
 Code:
abstract class Account {
protected int accountNo;
protected double balance;

public Account(int accountNo, double balance) {


this.accountNo = accountNo;
this.balance = balance;
}

public double checkBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}

public abstract void withdraw(double amount);


}

class Savings extends Account {


private double interestRate;

public Savings(int accountNo, double balance, double interestRate) {


super(accountNo, balance); // Invoke the constructor of the superclass
this.interestRate = interestRate;
}

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

public void display() {


System.out.println("Savings Account No: " + accountNo);
System.out.println("Balance: " + balance);
System.out.println("Interest Rate: " + interestRate);
}
}
class Current extends Account {
private double overdraftLimit;

public Current(int accountNo, double balance, double overdraftLimit) {


super(accountNo, balance); // Invoke the constructor of the superclass
this.overdraftLimit = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}

public void display() {


System.out.println("Current Account No: " + accountNo);
System.out.println("Balance: " + balance);
System.out.println("Overdraft Limit: " + overdraftLimit);
}
}

public class Main {


public static void main(String[] args) {
Savings savingsAccount = new Savings(101, 5000.0, 0.05);
Current currentAccount = new Current(102, 3000.0, 1000.0);

savingsAccount.deposit(1000);
savingsAccount.withdraw(2000);
savingsAccount.display();

System.out.println();

currentAccount.deposit(2000);
currentAccount.withdraw(4000);
currentAccount.display();
}
}
 Output:
Practical 21
AIM: Write a program in Java to demonstrate the use of 'final' keyword in the field
declaration. How it is accessed using the objects.
Program
 Code:
public class FinalKeywordDemo {

private final int id;


private final String name;

public FinalKeywordDemo(int id, String name) {


this.id = id;
this.name = name;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public static void main(String[] args) {


// Create objects of FinalKeywordDemo
FinalKeywordDemo obj1 = new FinalKeywordDemo(1, "Alice");
FinalKeywordDemo obj2 = new FinalKeywordDemo(2, "Bob");

// Access final fields using getter methods


System.out.println("Object 1 - ID: " + obj1.getId() + ", Name: " + obj1.getName());
System.out.println("Object 2 - ID: " + obj2.getId() + ", Name: " + obj2.getName());

// Uncommenting the following lines will cause a compile-time error


// because final fields cannot be reassigned.
// obj1.id = 10;
// obj1.name = "Charlie";
}
}

 Output:
Practical 22
AIM: Write a java program to illustrate how to access a hidden variable. Class A declares a static
variable x. The class B extends A and declares an instance variable x. display ( ) method in B
displays both of these variables.
Program
 Code:
class A {
static int x = 10;
}

class B extends A {
int x = 20;

public void display() {


System.out.println("Static variable x in superclass A: " + A.x);
// Accessing the instance variable from subclass
System.out.println("Instance variable x in subclass B: " + this.x);
}

public static void main(String[] args) {


B obj = new B();
obj.display();
}
}

 Output:
Practical 23
AIM: Describe abstract class called Shape which has three subclasses say Triangle, Rectangle, and
Circle. Define one method area () in the abstract class and override this area () in these three
subclasses to calculate for specific object i.e. area () of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle
Program
 Code:
abstract class Shape {
// Abstract method to calculate area
public abstract double area();
}

class Triangle extends Shape {


private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

@Override
public double area() {
return 0.5 * base * height;
}
}

class Rectangle extends Shape {


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

@Override
public double area() {
return length * width;
}
}

class Circle extends Shape {


private double radius;
public Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

public class Main {


public static void main(String[] args) {
Shape triangle = new Triangle(5, 10);
Shape rectangle = new Rectangle(4, 6);
Shape circle = new Circle(3);

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


System.out.println("Area of Rectangle: " + rectangle.area());
System.out.println("Area of Circle: " + circle.area());
}
}

 Output:
Practical 24
AIM: Write a java program to implement an interface called Exam with a method Pass (int mark)
that returns a boolean. Write another interface called Classify with a method Division (int average)
which returns a String. Write a class called Result which implements both Exam and Classify. The
Pass method should return true if the mark is greater than or equal to 50 else false. The Division
method must return “First” when the parameter average is 60 or more, “Second” when average is
50 or more but below 60, “No division” when average is less than 50.
Program
 Code:
interface Exam {
boolean Pass(int mark);
}

interface Classify {
String Division(int average);
}

class Result implements Exam, Classify {


@Override
public boolean Pass(int mark) {
return mark >= 50;
}

@Override
public String Division(int average) {
if (average >= 60) {
return "First";
} else if (average >= 50) {
return "Second";
} else {
return "No division";
}
}

public static void main(String[] args) {


Result result = new Result();

int mark = 55;


System.out.println("Mark: " + mark + " - Pass: " + result.Pass(mark));

mark = 45;
System.out.println("Mark: " + mark + " - Pass: " + result.Pass(mark));

int average = 65;


System.out.println("Average: " + average + " - Division: " + result.Division(average));

average = 55;
System.out.println("Average: " + average + " - Division: " + result.Division(average));

average = 45;
System.out.println("Average: " + average + " - Division: " + result.Division(average));
}
}
 Output:
Practical 25
AIM: Assume that there are two packages, student and exam. A student package contains Student
class and the exam package contains Result class. Write a program that generates mark sheet for
students.
Program
 Code:

package student;

public class Student {


private String name;
private String rollNumber;

public Student(String name, String rollNumber) {


this.name = name;
this.rollNumber = rollNumber;
}

public String getName() {


return name;
}

public String getRollNumber() {


return rollNumber;
}
}

package exam;

import student.Student;

public class Result {


private Student student;
private int[] marks;
private int total;
private double percentage;

public Result(Student student, int[] marks) {


this.student = student;
this.marks = marks;
calculateTotalAndPercentage();
}

private void calculateTotalAndPercentage() {


total = 0;
for (int mark : marks) {
total += mark;
}
percentage = (double) total / (marks.length * 100) * 100;
}

public void displayResult() {


System.out.println("Mark Sheet");
System.out.println(" --------- ");
System.out.println("Name: " + student.getName());
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Subjects and Marks:");
for (int i = 0; i < marks.length; i++) {
System.out.println("Subject " + (i + 1) + ": " + marks[i]);
}
System.out.println("Total: " + total);
System.out.println("Percentage: " + String.format("%.2f", percentage) + "%");
}
}

import student.Student;
import exam.Result;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter student's name: ");
String name = scanner.nextLine();
System.out.print("Enter roll number: ");
String rollNumber = scanner.nextLine();

String[] subjects = {"Math", "Science", "English", "History", "Geography"};


int[] marks = new int[subjects.length];
for (int i = 0; i < subjects.length; i++) {
System.out.print("Enter marks for " + subjects[i] + ": ");
marks[i] = scanner.nextInt();
}

Student student = new Student(name, rollNumber);


Result result = new Result(student, marks);

result.displayResult();

scanner.close();
}
}

 Output:
Directory structure:
Final Output:
Practical 26
AIM: Define a class A in package apack. In class A, three variables are defined of access modifiers
protected, private and public. Define class B in package bpack which extends A and write display
method which accesses variables of class A. Define class C in package cpack which has one method
display() in that create one object of class A and display its variables. Define class ProtectedDemo
in package dpack in which write main () method. Create objects of class B and C and class display
method for both these objects.
Program
 Code:
package apack;

public class A {
public int publicVar = 10;
protected int protectedVar = 20;
private int privateVar = 30;

public int getPrivateVar() {


return privateVar;
}
}

package bpack;

import apack.A;

public class B extends A {


public void display() {
System.out.println("Public Variable: " + publicVar);
System.out.println("Protected Variable: " + protectedVar);
// System.out.println("Private Variable: " + privateVar); // Cannot access private variable
directly
System.out.println("Private Variable (via getter): " + getPrivateVar());
}
}

package cpack;

import apack.A;

public class C {
public void display() {
A a = new A();
System.out.println("Public Variable: " + a.publicVar);
System.out.println("Private Variable (via getter): " + a.getPrivateVar());
}
}
package dpack;

import bpack.B;
import cpack.C;

public class ProtectedDemo {


public static void main(String[] args) {
B b = new B();
C c = new C();

System.out.println("Displaying from class B:");


b.display();

System.out.println("\nDisplaying from class C:");


c.display();
}
}

Directory structure:

 Output:
Practical 27
AIM: Write a java program to implement Generic class Number_1 for both data type int and float in
java.
Program
 Code:
public class Number_1<T extends Number> {
private T number;

public Number_1(T number) {


this.number = number;
}

public T getNumber() {
return number;
}

public void setNumber(T number) {


this.number = number;
}

public double doubleValue() {


return number.doubleValue();
}

public static void main(String[] args) {


Number_1<Integer> intNumber = new Number_1<>(10);
System.out.println("Integer value: " + intNumber.getNumber());
System.out.println("Double value: " + intNumber.doubleValue());

Number_1<Float> floatNumber = new Number_1<>(10.5f);


System.out.println("Float value: " + floatNumber.getNumber());
System.out.println("Double value: " + floatNumber.doubleValue());
}
}

 Output:
Practical 28
AIM: Write a java program to accept string to check whether it is in Upper or Lower case. After
checking, case will be reversed.
Program
 Code:
import java.util.Scanner;

public class CaseChecker {


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

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


String input = scanner.nextLine();

if (input.equals(input.toUpperCase())) {
System.out.println("The string is in uppercase.");
} else if (input.equals(input.toLowerCase())) {
System.out.println("The string is in lowercase.");
} else {
System.out.println("The string contains both uppercase and lowercase characters.");
}

String reversedCaseString = reverseCase(input);


System.out.println("Reversed case string: " + reversedCaseString);

scanner.close();
}

public static String reverseCase(String str) {


StringBuilder reversedCase = new StringBuilder(str.length());

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


if (Character.isUpperCase(c)) {
reversedCase.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
reversedCase.append(Character.toUpperCase(c));
} else {
reversedCase.append(c);
}
}

return reversedCase.toString();
}
}
 Output:
Practical 29
AIM: Write a java program to use important methods of String class.
Program
 Code:
public class StringMethodsDemo {
public static void main(String[] args) {
String str = "Hello, World!";

int length = str.length();


System.out.println("Length: " + length);

char charAt = str.charAt(7);


System.out.println("Character at index 7: " + charAt);
String substring = str.substring(7, 12);
System.out.println("Substring (7, 12): " + substring);
int indexOf = str.indexOf('W');
System.out.println("Index of 'W': " + indexOf);

String replaced = str.replace('l', 'p');


System.out.println("Replaced 'l' with 'p': " + replaced);

String upperCase = str.toUpperCase();


System.out.println("Uppercase: " + upperCase);

String lowerCase = str.toLowerCase();


System.out.println("Lowercase: " + lowerCase);

String strWithSpaces = " Hello, World! ";


String trimmed = strWithSpaces.trim();
System.out.println("Trimmed: '" + trimmed + "'");

String[] split = str.split(", ");


System.out.println("Split by ', ':");
for (String s : split) {
System.out.println(s);
}

boolean contains = str.contains("World");


System.out.println("Contains 'World': " + contains);

boolean startsWith = str.startsWith("Hello");


System.out.println("Starts with 'Hello': " + startsWith);
boolean endsWith = str.endsWith("!");
System.out.println("Ends with '!': " + endsWith);
}
}

 Output:
Practical 30

AIM: Write a program in Java to demonstrate use of final class, final variable and final
method
Program
 Code:
public final class FinalClass {
public final int finalVariable = 100;

public final void display() {


System.out.println("This is a final method.");
}

public void showFinalVariable() {


System.out.println("Final variable value: " + finalVariable);
}
}

public class Main {


public static void main(String[] args) {
FinalClass finalClass = new FinalClass();
finalClass.showFinalVariable();

finalClass.display();
}
}

 Output:
Practical 31

AIM: Write a program in Java to develop user defined exception for 'Divide by
Zero' error
Program
 Code:
public class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}

public class Division {


public static double divide(double numerator, double denominator) throws
DivideByZeroException {
if (denominator == 0) {
throw new DivideByZeroException("Cannot divide by zero.");
}
return numerator / denominator;
}
}

import java.util.Scanner;

public class Main {


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

System.out.print("Enter numerator: ");


double numerator = scanner.nextDouble();

System.out.print("Enter denominator: ");


double denominator = scanner.nextDouble();

try {
double result = Division.divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (DivideByZeroException e) {
System.out.println("Error: " + e.getMessage());
}

scanner.close();
}
}
 Output:
Practical 32

AIM: Write a program in Java to demonstrate throw, throws, finally, multiple try block and
exception.
multiple catch
Program
 Code:

import java.util.Scanner;

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class ExceptionDemo {


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

try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();

checkNumber(number);

try {
int result = 10 / number;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Division by zero is not allowed.");
}

try {
int[] arr = new int[5];
arr[10] = 50; // This will cause ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: Index out of bounds.");
}

} catch (CustomException e) {
System.out.println("CustomException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
scanner.close();
}
}

public static void checkNumber(int number) throws CustomException {


if (number < 0) {
throw new CustomException("Negative numbers are not allowed.");
}
}
}

 Output:
Practical 33
AIM: Write a small application in Java to develop Banking Application in which user deposits the
amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs 300.00 and it throws exception
"Not Sufficient Fund" when user withdraws Rs. 500 thereafter.
Program
 Code:
public class NotSufficientFundException extends Exception {
public NotSufficientFundException(String message) {
super(message);
}
}

public class BankAccount {


private double balance;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: Rs " + amount);
System.out.println("Current Balance: Rs " + balance);
}

public void withdraw(double amount) throws NotSufficientFundException {


if (amount > balance) {
throw new NotSufficientFundException("Not Sufficient Fund");
}
balance -= amount;
System.out.println("Withdrawn: Rs " + amount);
System.out.println("Current Balance: Rs " + balance);
}

public double getBalance() {


return balance;
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000.00);

try {
account.deposit(1000.00);
account.withdraw(400.00);
account.withdraw(300.00);
account.withdraw(500.00); // This should throw NotSufficientFundException
} catch (NotSufficientFundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

 Output:
Practical 34
AIM: Write a program to write at least 10 objects of the Circle class in a File and to perform basic
operations: adding, retrieving, updating, removing elements.
Program
 Code:
import java.io.Serializable;

public class Circle implements Serializable {


private static final long serialVersionUID = 1L;
private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getRadius() {


return radius;
}

public void setRadius(double radius) {


this.radius = radius;
}

@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
}

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class CircleManager {


private static final String FILE_NAME = "circles.dat";

public void addCircle(Circle circle) throws IOException {


List<Circle> circles = readCircles();
circles.add(circle);
writeCircles(circles);
}

public List<Circle> readCircles() throws IOException {


File file = new File(FILE_NAME);
if (!file.exists()) {
return new ArrayList<>();
}

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {


return (List<Circle>) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public void updateCircle(int index, Circle newCircle) throws IOException {
List<Circle> circles = readCircles();
if (index >= 0 && index < circles.size()) {
circles.set(index, newCircle);
writeCircles(circles);
} else {
System.out.println("Index out of bounds.");
}
}

public void removeCircle(int index) throws IOException {


List<Circle> circles = readCircles();
if (index >= 0 && index < circles.size()) {
circles.remove(index);
writeCircles(circles);
} else {
System.out.println("Index out of bounds.");
}
}

public void clearFile() throws IOException {


try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(FILE_NAME))) {
oos.writeObject(new ArrayList<Circle>());
}
}

private void writeCircles(List<Circle> circles) throws IOException {


try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream(FILE_NAME))) {
oos.writeObject(circles);
}
}
}
import java.io.IOException;
import java.util.List;

public class Main {


public static void main(String[] args) {
CircleManager manager = new CircleManager();

try {
// Clear the file before adding new circles
manager.clearFile();

// Add 10 circles
for (int i = 1; i <= 10; i++) {
manager.addCircle(new Circle(i * 1.0));
}

// Retrieve and display all circles


List<Circle> circles = manager.readCircles();
System.out.println("Circles:");
for (Circle circle : circles) {
System.out.println(circle);
}

manager.updateCircle(5, new Circle(15.0));


System.out.println("\nAfter updating circle at index 5:");
circles = manager.readCircles();
for (Circle circle : circles) {
System.out.println(circle);
}

manager.removeCircle(3);
System.out.println("\nAfter removing circle at index 3:");
circles = manager.readCircles();
for (Circle circle : circles) {
System.out.println(circle);
}

} catch (IOException e) {
e.printStackTrace();
}
}
}

 Output:
Practical 35

AIM: Write a program for Java Generics class for Sorting operations:
1. Sorting a list according to natural ordering of elements
2. Reversing sort order
3. Sorting a list whose elements of a custom type
4. Sorting a list using a Comparator. [desirable]
Program
 Code:
import java.util.*;

public class Sorter<T extends Comparable<T>> {


public void sortList(List<T> list) {
Collections.sort(list);
}

public void reverseSortList(List<T> list) {


Collections.sort(list, Collections.reverseOrder());
}

public void sortListWithComparator(List<T> list, Comparator<T> comparator) {


Collections.sort(list, comparator);
}
}

class Person implements Comparable<Person> {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}

@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
public class Main {
public static void main(String[] args) {
Sorter<Integer> intSorter = new Sorter<>();
List<Integer> intList = Arrays.asList(5, 3, 8, 1, 9);

System.out.println("Original Integer List: " + intList);


intSorter.sortList(intList);
System.out.println("Sorted Integer List: " + intList);
intSorter.reverseSortList(intList);
System.out.println("Reverse Sorted Integer List: " + intList);

Sorter<Person> personSorter = new Sorter<>();


List<Person> personList = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);

System.out.println("\nOriginal Person List: " + personList);


personSorter.sortList(personList);
System.out.println("Sorted Person List by Name: " + personList);

// Sorting by age using a Comparator


personSorter.sortListWithComparator(personList,
Comparator.comparingInt(Person::getAge));
System.out.println("Sorted Person List by Age: " + personList);
}
}

 Output:
Practical 36

AIM: Write a program in Java to create, write, modify, read operations on a Text file.
Program
 Code:
import java.io.*;
import java.util.Scanner;

public class FileOperations {


private static final String FILE_NAME = "example.txt";

public void createAndWriteFile(String content) throws IOException {


try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME))) {
writer.write(content);
}
}

public String readFile() throws IOException {


StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}

public void modifyFile(String content) throws IOException {


try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME, true))) {
writer.write(content);
}
}

public void deleteFile() {


File file = new File(FILE_NAME);
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}

public static void main(String[] args) {


FileOperations fileOps = new FileOperations();
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter content to write to the file: ");
String content = scanner.nextLine();
fileOps.createAndWriteFile(content);
System.out.println("File created and written successfully.");

System.out.println("\nReading from the file:");


String fileContent = fileOps.readFile();
System.out.println(fileContent);

System.out.print("Enter content to append to the file: ");


String appendContent = scanner.nextLine();
fileOps.modifyFile(appendContent);
System.out.println("File modified successfully.");

System.out.println("\nReading from the file after modification:");


fileContent = fileOps.readFile();
System.out.println(fileContent);

System.out.print("Do you want to delete the file? (yes/no): ");


String deleteResponse = scanner.nextLine();
if (deleteResponse.equalsIgnoreCase("yes")) {
fileOps.deleteFile();
}

} catch (IOException e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
}

 Output:
Practical 37
AIM: Write a java program to illustrate use of standard input stream to read the user input.
Program
 Code:

import java.util.Scanner;

public class Userinput {


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

System.out.print("Enter your name: ");


String name = scanner.nextLine();

System.out.print("Enter your age: ");


int age = scanner.nextInt();

System.out.print("Enter your favorite number: ");


double favoriteNumber = scanner.nextDouble();

System.out.println("\nUser Input:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Favorite Number: " + favoriteNumber);

scanner.close();
}
}

 Output:
Practical 38
AIM: Write a java program to checks the existence of a specified file.
Program
 Code:

import java.io.File;
import java.util.Scanner;

public class FileExistenceChecker {


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

System.out.print("Enter the file name: ");


String fileName = scanner.nextLine();
File file = new File(fileName);

if (file.exists()) {
System.out.println("The file " + fileName + " exists.");
} else {
System.out.println("The file " + fileName + " does not exist.");
}

scanner.close();
}
}

 Output:
Practical 39
AIM: Write a java program to create a file to the specified location.
Program
 Code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileCreator {


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

System.out.print("Enter the file path: ");


String filePath = scanner.nextLine();
File file = new File(filePath);

try {
if (file.exists()) {
System.out.println("The file " + filePath + " already exists.");
} else {
if (file.createNewFile()) {
System.out.println("The file " + filePath + " has been created successfully.");
} else {
System.out.println("Failed to create the file " + filePath + ".");
}
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file: " + e.getMessage());
}

scanner.close();
}
}

 Output:
Practical 40
AIM: Write a java program to demonstrate the way contents are read from a file.
Program
 Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileReaderExample {


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

System.out.print("Enter the full file path: ");


String filePath = scanner.nextLine();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
// Read and print each line from the file
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}

scanner.close();
}
}

 Output:
Practical 41
AIM: Write a program in Java to demonstrate use of synchronization of threads when multiple
threads are trying to update common variable for “Account” class.
Program
 Code:
public class Account {
private int balance;

public Account(int initialBalance) {


this.balance = initialBalance;
}
public synchronized void deposit(int amount) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited " + amount + ". Current
balance: " + balance);
}

public synchronized void withdraw(int amount) {


if (balance >= amount) {
balance -= amount;
System.out.println(Thread.currentThread().getName() + " withdrew " + amount + ". Current
balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + " tried to withdraw " + amount + ".
Insufficient balance.");
}
}

public int getBalance() {


return balance;
}
}
public class BankingThread extends Thread {
private Account account;
private boolean deposit;
private int amount;

public BankingThread(Account account, boolean deposit, int amount) {


this.account = account;
this.deposit = deposit;
this.amount = amount;
}

@Override
public void run() {
if (deposit) {
account.deposit(amount);
} else {
account.withdraw(amount);
}
}
}
public class Main {
public static void main(String[] args) {
Account account = new Account(1000);

Thread t1 = new BankingThread(account, true, 500); // Deposit 500


Thread t2 = new BankingThread(account, false, 300); // Withdraw 300
Thread t3 = new BankingThread(account, false, 700); // Withdraw 700
Thread t4 = new BankingThread(account, true, 200); // Deposit 200

t1.start();
t2.start();
t3.start();
t4.start();

try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final balance: " + account.getBalance());


}
}
 Output:
Practical 42
AIM: Write a java program to count the availability of text lines in the particular file. A file is
read before counting lines of a particular file.
Program
 Code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class LineCounter {


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

System.out.print("Enter the file path: ");


String filePath = scanner.nextLine();

int lineCount = 0;

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


// Read each line from the file and count the lines
while (reader.readLine() != null) {
lineCount++;
}
System.out.println("The file " + filePath + " has " + lineCount + " lines.");
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}

scanner.close();
}
}

 Output:
Practical 43
AIM: Write a generic method to count the number of elements in a collection that have a specific
property (for example, odd integers, prime numbers, palindromes).
Program
 Code:
import java.util.*;
import java.util.function.Predicate;

public class GenericCounter {


public static <T> int countElementsWithProperty(Collection<T> collection, Predicate<T>
property) {
int count = 0;
for (T element : collection) {
if (property.test(element)) {
count++;
}
}
return count;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a list of integers (space-separated): ");


String[] intInput = scanner.nextLine().split(" ");
List<Integer> integers = new ArrayList<>();
for (String s : intInput) {
integers.add(Integer.parseInt(s));
}

System.out.print("Enter a list of strings (space-separated): ");


String[] strInput = scanner.nextLine().split(" ");
List<String> strings = Arrays.asList(strInput);

Predicate<Integer> isOdd = n -> n % 2 != 0;


int oddCount = countElementsWithProperty(integers, isOdd);
System.out.println("Number of odd integers: " + oddCount);

Predicate<Integer> isPrime = n -> {


if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
};
int primeCount = countElementsWithProperty(integers, isPrime);
System.out.println("Number of prime numbers: " + primeCount);
Predicate<String> isPalindrome = s -> s.equals(new StringBuilder(s).reverse().toString());
int palindromeCount = countElementsWithProperty(strings, isPalindrome);
System.out.println("Number of palindromes: " + palindromeCount);

scanner.close();
}
}

 Output:
Practical 44

AIM: Write a generic method to exchange the positions of two different elements in an array.
Program
 Code:
import java.util.Arrays;
import java.util.Scanner;

public class ArrayUtils {


public static <T> void swap(T[] array, int index1, int index2) {
if (index1 < 0 || index1 >= array.length || index2 < 0 || index2 >= array.length) {
throw new IndexOutOfBoundsException("Invalid index");
}
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the type of array (integer/string): ");


String type = scanner.nextLine().toLowerCase();

if (type.equals("integer")) {
System.out.print("Enter the integer array elements (space-separated): ");
String[] intInput = scanner.nextLine().split(" ");
Integer[] intArray = new Integer[intInput.length];
for (int i = 0; i < intInput.length; i++) {
intArray[i] = Integer.parseInt(intInput[i]);
}

System.out.print("Enter the first index to swap: ");


int index1 = scanner.nextInt();
System.out.print("Enter the second index to swap: ");
int index2 = scanner.nextInt();

swap(intArray, index1, index2);


System.out.println("After swapping: " + Arrays.toString(intArray));

} else if (type.equals("string")) {
System.out.print("Enter the string array elements (space-separated): ");
String[] strArray = scanner.nextLine().split(" ");

System.out.print("Enter the first index to swap: ");


int index1 = scanner.nextInt();
System.out.print("Enter the second index to swap: ");

int index2 = scanner.nextInt();


swap(strArray, index1, index2);
System.out.println("After swapping: " + Arrays.toString(strArray));

} else {
System.out.println("Invalid array type.");
}

scanner.close();
}
}
 Output:

You might also like