0% found this document useful (0 votes)
4 views41 pages

Java Lab Manual

The document is a lab report for the Java Programming Lab course (IFT2308) submitted by Angeleena Maria Roy for the academic year 2023-2026. It includes a series of programming tasks and examples, covering topics such as Fibonacci series, prime numbers, palindrome checking, arithmetic operations, array sorting, matrix multiplication, and banking system implementation. Each task is accompanied by Java code snippets demonstrating the required functionality.

Uploaded by

angeleena.m.r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views41 pages

Java Lab Manual

The document is a lab report for the Java Programming Lab course (IFT2308) submitted by Angeleena Maria Roy for the academic year 2023-2026. It includes a series of programming tasks and examples, covering topics such as Fibonacci series, prime numbers, palindrome checking, arithmetic operations, array sorting, matrix multiplication, and banking system implementation. Each task is accompanied by Java code snippets demonstrating the required functionality.

Uploaded by

angeleena.m.r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

IFT2308 -JAVA PROGRAMMING LAB

Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

AMITY INSTITUTE OF INFORMATION TECHNOLOGY

LAB REPORT
(ACADEMIC YEAR 2023-2026)

COURSE NAME: JAVA PROGRAMMING LAB

COURSE CODE: IFT2308

DEPARTMENT: BSc IT (AIIT)

FACULTY NAME: Mr. Debesh Das

SUBMITTED BY

STUDENT NAME: ANGELEENA MARIA ROY

ENROLLMENT NUMBER: A71004923010

CLASS: B

SEMESTER: 3rd

P a g e 1 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

Sr. Title
No.
1 a. WAP to find fibonacci upto given number using
for loop.
b. WAP to print prime numbers using while loop.
c. WAP whether a given string is palindrome or
not?
d. WAP to perform arithmetic operations(menu
driven).
2 a. WAP to sort the elements of array in ascending
order.
b. WAP for calculating Matrix multiplication
operation.
c. WAP for sorting given list of names in ascending
order.
3 a. WAP to demonstrate the working of banking-
system where we deposit and withdraw amount
from our account.
b. WAP using class and object for calculating area
of circle, rectangle, triangle using menu driven.
c. WAP to create a room class, the attributes of this
class is roomno, roomtype, roomarea, and ac-
machine. In this class the member functions are
setdata and displaydata.
4 Given the classes EmployeeDetails, DepartmentDetails, and Salary,
implement a multilevel inheritance structure in Java:

1. EmployeeDetails: Stores basic employee information (employeeName,


employeeId).

2. DepartmentDetails: Inherits from EmployeeDetails, adding department


information (departmentName, departmentId).

3. Salary: Inherits from DepartmentDetails, adding monthlySalary.


In the Salary class, add a method to display the annual salary in LPA
(Lakhs Per Annum) by converting the monthly salary.

Task: Create an instance of the Salary class for an employee with


monthly salary $75,000, and call printDetails() to display employee,
department, and salary details in LPA.

P a g e 2 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

5 Consider a multilevel inheritance structure in Java with the following


classes:

1. School: This base class holds basic information about a school, such as
schoolName and schoolId, and includes a printDetails() method to
display these details.

2. Student: This class inherits from School and adds student-specific


attributes like studentName and studentId. It also overrides the
printDetails() method to include both school and student information.

3. GraduateStudent: This class inherits from Student and adds a


graduationYear attribute. It overrides the printDetails() method to display
all three levels of information (school, student, and graduation year).

Task: Write a Java program that creates an instance of GraduateStudent


for a student named "Alice Brown" with ID "STU789", who graduated
in 2024 from "XYZ University"
(school ID: "UNI123"). Call the printDetails() method to display all
information from each level of the inheritance chain (school, student, and
graduation year).

6 a. Write a Java program with two variables: an int variable a and a String
variable b. Set default values in the default constructor and print the values in the
constructor.
b. Write a Java program with three constructors: the first is a default constructor
that will print an introduction, the second is a parameterized constructor with
a String parameter name to print the name, and the third is a
parameterized constructor with a String parameter school and an int
parameter roll to print the school name and roll number.
7 a. WAP to illustrate use of abstract class that has abstract and non-
abstract methods.
b. WAP to illustrate use of interface.

8 WAP for null pointer exception and illustrate finally block and
throws keyword.
9 a. WAP to create a text file.
b. WAP to write text in text file.
c. WAP to read text from text file
10 Write a java program for calculator operation using AWT controls

11 a. WAP to demonstrate LinkedList and it's methods.


b. WAP to demonstrate HashSet and it's methods.

P a g e 3 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

1.
A - WAP to find fibonacci upto given number using for loop

import [Link];

public class FibonacciSeries {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of terms: ");
int n = [Link]();

int a = 0, b = 1, next;
[Link]("Fibonacci series: " + a + " " + b);

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


next = a + b;
[Link](" " + next);
a = b;
b = next;
}
}
}

OUTPUT :-

B - WAP to print prime numbers using while loop.

import [Link];

public class PrimeNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

P a g e 4 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Enter the range (up to): ");


int n = [Link]();

int num = 2;
while (num <= n) {
boolean isPrime = true;
int i = 2;
while (i <= [Link](num)) {
if (num % i == 0) {
isPrime = false;
break;
}
i++;
}
if (isPrime) {
[Link](num + " ");
}
num++;
}
}
}

OUTPUT :-

C - WAP whether a given string is palindrome or not?

import [Link];

public class PalindromeCheck {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

P a g e 5 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

String reversed = "";


for (int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);
}

if ([Link](reversed)) {
[Link]("The string is a palindrome.");
} else {
[Link]("The string is not a palindrome.");
}
}
}

OUTPUT :-

D - Menu-driven program for arithmetic operations

import [Link];

public class ArithmeticOperations {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int choice;
double num1, num2;

do {
[Link]("\n--- Menu ---");
[Link]("1. Addition");
[Link]("2. Subtraction");
[Link]("3. Multiplication");
[Link]("4. Division");
[Link]("5. Exit");

P a g e 6 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Enter your choice: ");


choice = [Link]();

if (choice >= 1 && choice <= 4) {


[Link]("Enter the first number: ");
num1 = [Link]();
[Link]("Enter the second number: ");
num2 = [Link]();
} else {
num1 = num2 = 0; // Default initialization
}

switch (choice) {
case 1:
[Link]("Result: " + (num1 + num2));
break;
case 2:
[Link]("Result: " + (num1 - num2));
break;
case 3:
[Link]("Result: " + (num1 * num2));
break;
case 4:
if (num2 != 0) {
[Link]("Result: " + (num1 / num2));
} else {
[Link]("Division by zero is not
allowed.");
}
break;
case 5:
[Link]("Exiting program.");
break;
default:
[Link]("Invalid choice! Please try again.");
}
} while (choice != 5);
}

P a g e 7 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

OUTPUT :-

2.
A - WAP to sort the elements of array in ascending order.

import [Link];

public class ArraySort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int n = [Link]();

int[] arr = new int[n];


[Link]("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Sorting the array using Bubble Sort


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]

P a g e 8 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

int temp = arr[j];


arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

[Link]("Sorted array in ascending order:");


for (int num : arr) {
[Link](num + " ");
}
}
}

OUTPUT :-

B - WAP for calculating Matrix multiplication operation.

import [Link];

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows of the first matrix:


");
int rows1 = [Link]();
[Link]("Enter the number of columns of the first
matrix: ");
int cols1 = [Link]();
[Link]("Enter the number of rows of the second
matrix: ");

P a g e 9 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

int rows2 = [Link]();


[Link]("Enter the number of columns of the second
matrix: ");
int cols2 = [Link]();

if (cols1 != rows2) {
[Link]("Matrix multiplication is not possible
(columns of first matrix != rows of second matrix).");
return;
}

int[][] matrix1 = new int[rows1][cols1];


int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2];

[Link]("Enter elements of the first matrix:");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = [Link]();
}
}

[Link]("Enter elements of the second matrix:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = [Link]();
}
}

// Matrix multiplication
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

P a g e 10 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Resultant matrix after multiplication:");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
}
}

OUTPUT :-

C - WAP for sorting given list of names in ascending order.

import [Link];
import [Link];

public class NameSort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of names: ");
int n = [Link]();
[Link](); // Consume the newline character

String[] names = new String[n];


[Link]("Enter the names:");

P a g e 11 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

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


names[i] = [Link]();
}

// Sorting the array of names


[Link](names);

[Link]("Sorted list of names in ascending order:");


for (String name : names) {
[Link](name);
}
}
}

OUTPUT :-

3.
A - WAP to demonstrate the working of banking- system where
we deposit and withdraw amount from our account.

import [Link];

class BankAccount {
private String accountHolderName;
private double balance;

public BankAccount(String accountHolderName, double


initialBalance) {
[Link] = accountHolderName;

P a g e 12 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link] = initialBalance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
[Link]("Successfully deposited: " + amount);
} else {
[Link]("Deposit amount must be positive.");
}
}

public void withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Successfully withdrew: " + amount);
} else if (amount > balance) {
[Link]("Insufficient balance.");
} else {
[Link]("Withdrawal amount must be positive.");
}
}

public void displayBalance() {


[Link]("Current Balance: " + balance);
}
}

public class BankingSystem {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter account holder's name: ");


String name = [Link]();
[Link]("Enter initial balance: ");
double initialBalance = [Link]();

P a g e 13 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

BankAccount account = new BankAccount(name,


initialBalance);

int choice;
do {
[Link]("\n--- Banking Menu ---");
[Link]("1. Deposit");
[Link]("2. Withdraw");
[Link]("3. Display Balance");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter amount to deposit: ");
double depositAmount = [Link]();
[Link](depositAmount);
break;
case 2:
[Link]("Enter amount to withdraw: ");
double withdrawAmount = [Link]();
[Link](withdrawAmount);
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice, please try again.");
}
} while (choice != 4);
}
}

OUTPUT :-

P a g e 14 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

B - WAP using class and object for calculating area of circle,


rectangle, triangle using menu driven.

import [Link];

P a g e 15 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

class AreaCalculator {
public double calculateCircleArea(double radius) {
return [Link] * radius * radius;
}

public double calculateRectangleArea(double length, double


width) {
return length * width;
}

public double calculateTriangleArea(double base, double height) {


return 0.5 * base * height;
}
}

public class AreaMenu {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
AreaCalculator calculator = new AreaCalculator();

int choice;
do {
[Link]("\n--- Area Calculator Menu ---");
[Link]("1. Circle");
[Link]("2. Rectangle");
[Link]("3. Triangle");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();

switch (choice) {
case 1:
[Link]("Enter radius of the circle: ");
double radius = [Link]();
[Link]("Area of Circle: " +
[Link](radius));
break;
case 2:

P a g e 16 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Enter length of the rectangle: ");


double length = [Link]();
[Link]("Enter width of the rectangle: ");
double width = [Link]();
[Link]("Area of Rectangle: " +
[Link](length, width));
break;
case 3:
[Link]("Enter base of the triangle: ");
double base = [Link]();
[Link]("Enter height of the triangle: ");
double height = [Link]();
[Link]("Area of Triangle: " +
[Link](base, height));
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice, please try again.");
}
} while (choice != 4);
}
}

OUTPUT :-

P a g e 17 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

C - WAP to create a room class, the attributes of this class is


roomno, roomtype, roomarea, and ac- machine. In this class the
member functions are setdata and displaydata.

class Room {
private int roomNo;
private String roomType;
private double roomArea;
private boolean acMachine;

public void setData(int roomNo, String roomType, double


roomArea, boolean acMachine) {

P a g e 18 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link] = roomNo;
[Link] = roomType;
[Link] = roomArea;
[Link] = acMachine;
}

public void displayData() {


[Link]("\nRoom Details:");
[Link]("Room Number: " + roomNo);
[Link]("Room Type: " + roomType);
[Link]("Room Area: " + roomArea + " sq. meters");
[Link]("AC Available: " + (acMachine ? "Yes" :
"No"));
}
}

public class RoomDetails {


public static void main(String[] args) {
Room room = new Room();

[Link](101, "Deluxe", 25.5, true);


[Link]();
}
}

OUTPUT :-

4.
A – Given the classes EmployeeDetails, DepartmentDetails, and
Salary, implement a multilevel inheritance structure in Java:

P a g e 19 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

1. EmployeeDetails: Stores basic employee information


(employeeName, employeeId).

2. DepartmentDetails: Inherits from EmployeeDetails, adding


department information (departmentName, departmentId).

3. Salary: Inherits from DepartmentDetails, adding


monthlySalary. In the Salary class, add a method to display the
annual salary in LPA (Lakhs Per Annum) by converting the
monthly salary.

Task: Create an instance of the Salary class for an employee with


monthly salary $75,000, and call printDetails() to display
employee, department, and salary details in LPA.

class EmployeeDetails {
private String employeeName;
private int employeeId;

public void setEmployeeDetails(String employeeName, int


employeeId) {
[Link] = employeeName;
[Link] = employeeId;
}

public void printEmployeeDetails() {


[Link]("Employee Name: " + employeeName);
[Link]("Employee ID: " + employeeId);
}
}

class DepartmentDetails extends EmployeeDetails {


private String departmentName;
private int departmentId;

public void setDepartmentDetails(String departmentName, int


departmentId) {
[Link] = departmentName;

P a g e 20 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link] = departmentId;
}

public void printDepartmentDetails() {


[Link]("Department Name: " + departmentName);
[Link]("Department ID: " + departmentId);
}
}

class Salary extends DepartmentDetails {


private double monthlySalary;

public void setSalary(double monthlySalary) {


[Link] = monthlySalary;
}

public void printSalaryDetails() {


[Link]("Monthly Salary: $" + monthlySalary);
double annualSalaryLPA = (monthlySalary * 12) / 100000; //
Convert to LPA
[Link]("Annual Salary (LPA): ₹" +
annualSalaryLPA + " Lakhs");
}

public void printDetails() {


printEmployeeDetails();
printDepartmentDetails();
printSalaryDetails();
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
// Create an instance of the Salary class
Salary employee = new Salary();

// Set employee, department, and salary details


[Link]("John Doe", 101);

P a g e 21 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Software Development", 202);


[Link](75000); // Monthly salary is $75,000

// Display all details


[Link]();
}
}

OUTPUT :-

5.
A - Consider a multilevel inheritance structure in Java with the
following classes:
1. School: This base class holds basic information about a school,
such as schoolName and schoolId, and includes a printDetails()
method to display these details.

2. Student: This class inherits from School and adds student-


specific attributes like studentName and studentId. It also
overrides the printDetails() method to include both school and
student information.

3. GraduateStudent: This class inherits from Student and adds a


graduationYear attribute. It overrides the printDetails() method
to display all three levels of information (school, student, and
graduation year).

Task: Write a Java program that creates an instance of


GraduateStudent for a student named "Alice Brown" with ID
"STU789", who graduated in 2024 from "XYZ University"

P a g e 22 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

(school ID: "UNI123"). Call the printDetails() method to display


all information from each level of the inheritance chain (school,
student, and graduation year).

class School {
private String schoolName;
private String schoolId;

public void setSchoolDetails(String schoolName, String schoolId)


{
[Link] = schoolName;
[Link] = schoolId;
}

public void printDetails() {


[Link]("School Name: " + schoolName);
[Link]("School ID: " + schoolId);
}
}

class Student extends School {


private String studentName;
private String studentId;

public void setStudentDetails(String studentName, String


studentId) {
[Link] = studentName;
[Link] = studentId;
}

@Override
public void printDetails() {
[Link](); // Call the parent class's printDetails
method
[Link]("Student Name: " + studentName);
[Link]("Student ID: " + studentId);
}

P a g e 23 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

class GraduateStudent extends Student {


private int graduationYear;

public void setGraduationYear(int graduationYear) {


[Link] = graduationYear;
}

@Override
public void printDetails() {
[Link](); // Call the parent class's printDetails
method
[Link]("Graduation Year: " + graduationYear);
}
}

public class MultilevelInheritanceSchool {


public static void main(String[] args) {
// Create an instance of GraduateStudent
GraduateStudent graduateStudent = new GraduateStudent();

// Set details for School, Student, and GraduateStudent


[Link]("XYZ University",
"UNI123");
[Link]("Alice Brown", "STU789");
[Link](2024);

// Display all details


[Link]();
}
}

OUTPUT :-

P a g e 24 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

6.
A - Write a Java program with two variables: an int variable a
and a String variable b. Set default values in the default
constructor and print the values in the constructor.

class DefaultConstructorDemo {
private int a;
private String b;

// Default constructor
public DefaultConstructorDemo() {
// Set default values
a = 0;
b = "Default String";

// Print values in the constructor


[Link]("Default values:");
[Link]("a = " + a);
[Link]("b = " + b);
}
}

public class DefaultConstructorExample {


public static void main(String[] args) {
// Create an instance of DefaultConstructorDemo
DefaultConstructorDemo obj = new DefaultConstructorDemo();
}
}

OUTPUT :-

P a g e 25 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

B - Write a Java program with three constructors: the first is a


default constructor that will print an introduction, the second is
a parameterized constructor with a String parameter name to
print the name, and the third is a parameterized constructor
with a String parameter school and an int parameter roll to print
the school name and roll number.

class ConstructorDemo {
// Default constructor
public ConstructorDemo() {
[Link]("Welcome to Constructor Demo!");
}

// Parameterized constructor with one String parameter


public ConstructorDemo(String name) {
[Link]("Hello, " + name + "!");
}

// Parameterized constructor with String and int parameters


public ConstructorDemo(String school, int roll) {
[Link]("School Name: " + school);
[Link]("Roll Number: " + roll);
}
}

public class MultipleConstructorsExample {


public static void main(String[] args) {
// Use the default constructor
ConstructorDemo obj1 = new ConstructorDemo();

// Use the constructor with one parameter


ConstructorDemo obj2 = new ConstructorDemo("Alice");

P a g e 26 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

// Use the constructor with two parameters


ConstructorDemo obj3 = new ConstructorDemo("XYZ High
School", 123);
}
}

OUTPUT :-

7.
A - WAP to illustrate use of abstract class that has abstract and
non-abstract methods.

// Abstract class
abstract class Shape {
// Abstract method
abstract void calculateArea();

// Non-abstract method
void displayShapeName(String shapeName) {
[Link]("The shape is: " + shapeName);
}
}

// Concrete class inheriting from abstract class


class Circle extends Shape {
private double radius;

public Circle(double radius) {


[Link] = radius;
}

// Implementing the abstract method


@Override

P a g e 27 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

void calculateArea() {
double area = [Link] * radius * radius;
[Link]("Area of the Circle: " + area);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
// Create an instance of Circle
Circle circle = new Circle(5.0);

// Use methods from abstract and concrete classes


[Link]("Circle");
[Link]();
}
}

OUTPUT :-

B - WAP to illustrate use of interface

// Interface definition
interface Animal {
void makeSound(); // Abstract method

default void eat() { // Default (non-abstract) method


[Link]("This animal eats food.");
}
}

// Class implementing the interface


class Dog implements Animal {
@Override
public void makeSound() {

P a g e 28 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("The dog barks: Woof! Woof!");


}
}

public class InterfaceExample {


public static void main(String[] args) {
// Create an instance of Dog
Dog dog = new Dog();

// Use methods from the interface


[Link]();
[Link]();
}
}

OUTPUT :-

8.
A - WAP for null pointer exception and illustrate finally
block and throws keyword.

1. NullPointerException and Finally Block Example

public class NullPointerExceptionExample {


public static void main(String[] args) {
String str = null; // Null pointer

try {
// Attempting to call a method on a null object
[Link]([Link]()); // This will throw
NullPointerException
} catch (NullPointerException e) {
// Catching the NullPointerException

P a g e 29 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Caught NullPointerException: " + e);


} finally {
// Finally block always executes
[Link]("Finally block executed!");
}
}
}

OUTPUT :-

2. Throws Keyword Example

import [Link].*;

public class ThrowsKeywordExample {

// Method that declares throws IOException


public static void readFile() throws IOException {
FileReader file = new FileReader("[Link]"); //
This will throw FileNotFoundException
BufferedReader fileInput = new BufferedReader(file);
[Link]([Link]());
[Link]();
}

public static void main(String[] args) {


try {
// Calling the method that throws an exception
readFile();
} catch (IOException e) {
// Catching the exception declared in readFile()
[Link]("IOException caught: " + e);
} finally {
// Finally block always executes

P a g e 30 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]("Finally block executed in


ThrowsKeywordExample.");
}
}
}

OUTPUT :-

9.
A - WAP to create a text file.

import [Link];
import [Link];

public class CreateTextFile {


public static void main(String[] args) {
// Creating a file object
File file = new File("[Link]");

try {
// Checking if the file already exists
if ([Link]()) {
[Link]("File created: " +
[Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

OUTPUT :-

P a g e 31 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

B - WAP to write text in text file.

import [Link];
import [Link];

public class WriteTextToFile {


public static void main(String[] args) {
// Specifying the file name
String fileName = "[Link]";

try {
// Creating a FileWriter object to write text to the file
FileWriter writer = new FileWriter(fileName);

// Writing some text to the file


[Link]("Hello, this is a sample text written to the file.\n");
[Link]("Java file handling is easy to learn!");

// Closing the file after writing


[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

OUTPUT :-

C - WAP to read text from text file

import [Link];
import [Link];

P a g e 32 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

import [Link];

public class ReadTextFromFile {


public static void main(String[] args) {
// Specifying the file to be read
File file = new File("[Link]");

try {
// Creating a Scanner object to read the file
Scanner reader = new Scanner(file);

// Reading the file line by line


while ([Link]()) {
String line = [Link]();
[Link](line);
}

// Closing the reader


[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred. File not found.");
[Link]();
}
}
}

OUTPUT :-

10.
A - Write a java program for calculator operation
using AWT controls

import [Link].*;
import [Link].*;

P a g e 33 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

public class CalculatorAWT {


// Creating frame and components
Frame frame;
TextField textField;
Button[] numberButtons;
Button addButton, subButton, mulButton, divButton,
equalButton, clearButton;
String currentText = "";

public CalculatorAWT() {
// Creating frame
frame = new Frame("AWT Calculator");

// Creating TextField
textField = new TextField();
[Link](30, 40, 280, 30);
[Link](textField);

// Creating number buttons


numberButtons = new Button[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new Button([Link](i));
numberButtons[i].setBounds(30 + (i % 3) * 70, 80 + (i /
3) * 50, 60, 40);
numberButtons[i].addActionListener(new
ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText += [Link]();
[Link](currentText);
}
});
[Link](numberButtons[i]);
}

// Creating operation buttons


addButton = new Button("+");
[Link](30, 230, 60, 40);

P a g e 34 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText += "+";
[Link](currentText);
}
});
[Link](addButton);

subButton = new Button("-");


[Link](100, 230, 60, 40);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText += "-";
[Link](currentText);
}
});
[Link](subButton);

mulButton = new Button("*");


[Link](170, 230, 60, 40);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText += "*";
[Link](currentText);
}
});
[Link](mulButton);

divButton = new Button("/");


[Link](240, 230, 60, 40);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText += "/";
[Link](currentText);
}
});
[Link](divButton);

P a g e 35 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

// Equal button
equalButton = new Button("=");
[Link](100, 280, 60, 40);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// Evaluating the expression manually
String result = evaluateExpression(currentText);
[Link](result);
currentText = result; // Store the result for further
operations
} catch (Exception ex) {
[Link]("Error");
currentText = "";
}
}
});
[Link](equalButton);

// Clear button
clearButton = new Button("C");
[Link](170, 280, 60, 40);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentText = "";
[Link](currentText);
}
});
[Link](clearButton);

// Frame settings
[Link](350, 400);
[Link](null);
[Link](true);

// Window closing action


[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {

P a g e 36 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link](0);
}
});
}

// Method to evaluate the expression (simple arithmetic only)


private String evaluateExpression(String expression) {
try {
// Splitting the expression into numbers and operators
String[] tokens = [Link]("(?=[-+*/])|(?<=[-
+*/])");
double result = [Link](tokens[0]);

// Iterate over the tokens to evaluate the expression


for (int i = 1; i < [Link]; i += 2) {
String operator = tokens[i];
double number = [Link](tokens[i + 1]);

// Perform arithmetic operations based on the operator


switch (operator) {
case "+":
result += number;
break;
case "-":
result -= number;
break;
case "*":
result *= number;
break;
case "/":
if (number != 0) {
result /= number;
} else {
return "Error"; // Handle division by zero
}
break;
}
}

P a g e 37 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

return [Link](result);
} catch (Exception e) {
return "Error"; // Return "Error" in case of invalid
expression
}
}

public static void main(String[] args) {


new CalculatorAWT();
}
}

11.
A - WAP to demonstrate LinkedList and it's methods
.

import [Link];

public class LinkedListDemo {


public static void main(String[] args) {
// Create a LinkedList of String type
LinkedList<String> list = new LinkedList<>();

// Adding elements to the LinkedList


[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// Displaying the LinkedList


[Link]("Initial LinkedList: " + list);

// Adding an element at the first position


[Link]("Orange");
[Link]("After adding Orange at the beginning: " + list);

// Adding an element at the last position


[Link]("Grapes");
[Link]("After adding Grapes at the end: " + list);

P a g e 38 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

// Removing the first element


[Link]();
[Link]("After removing the first element: " + list);

// Removing the last element


[Link]();
[Link]("After removing the last element: " + list);

// Accessing elements
String firstElement = [Link]();
String lastElement = [Link]();
[Link]("First element: " + firstElement);
[Link]("Last element: " + lastElement);

// Checking if an element exists


boolean hasBanana = [Link]("Banana");
[Link]("Does the list contain 'Banana'? " + hasBanana);

// Size of the LinkedList


int size = [Link]();
[Link]("Size of the LinkedList: " + size);

// Clearing all elements


[Link]();
[Link]("After clearing the list: " + list);
}
}

OUTPUT :-

P a g e 39 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

B - WAP to demonstrate HashSet and it's methods

import [Link];

public class HashSetDemo {


public static void main(String[] args) {
// Create a HashSet of String type
HashSet<String> set = new HashSet<>();

// Adding elements to the HashSet


[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

// Displaying the HashSet


[Link]("Initial HashSet: " + set);

// Adding a duplicate element (won't be added as HashSet


doesn't allow duplicates)
[Link]("Apple");
[Link]("After attempting to add duplicate
'Apple': " + set);

// Removing an element from the HashSet


[Link]("Banana");
[Link]("After removing 'Banana': " + set);

// Checking if an element exists


boolean hasCherry = [Link]("Cherry");
[Link]("Does the set contain 'Cherry'? " +
hasCherry);

// Size of the HashSet


int size = [Link]();
[Link]("Size of the HashSet: " + size);

// Clearing all elements

P a g e 40 | 41
IFT2308 -JAVA PROGRAMMING LAB
Name: ANGELEENA MARIA ROY Enrollment No.: -A71004923010

[Link]();
[Link]("After clearing the HashSet: " + set);
}
}

OUTPUT :-

P a g e 41 | 41

You might also like