0% found this document useful (0 votes)
2 views55 pages

New Lab Manual in Java[1]

The document is a lab manual for Object-Oriented Programming (OOP) in Java, detailing various lab exercises and objectives related to Java programming concepts. It covers topics such as arrays, classes and objects, methods, encapsulation, and exception handling, along with example code snippets and assignments for practical implementation. The manual aims to provide students with hands-on experience in Java programming through structured lab activities.
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)
2 views55 pages

New Lab Manual in Java[1]

The document is a lab manual for Object-Oriented Programming (OOP) in Java, detailing various lab exercises and objectives related to Java programming concepts. It covers topics such as arrays, classes and objects, methods, encapsulation, and exception handling, along with example code snippets and assignments for practical implementation. The manual aims to provide students with hands-on experience in Java programming through structured lab activities.
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
You are on page 1/ 55

OBJECT ORIENTED PROGRAMMING

(LAB MANUAL)

LAB #
REGNO
NAME
DATE
STUDENT
SIGNATURE

Teacher’s Signature
CONTENT
Remarks /
Lab no Objective Signature

1 Introduction to Java & Installation of IDE

2 Review of Basic Programming Concepts

3 Arrays

4 Introducing Classes and Objects

5 Method and Access Modifiers

6 Encapsulation and Information Hiding

7 Array of Object and Method Overloading

8 Introduction to Inheritance

9 Introducing JavaFX – Java GUI

10 Abstract Class and Interface

11 Collection and Generic Class

12 Exception Handling

13 Files, Streams and Object Serialization

14 Project Submission
Arrays Lab 3

Array
An array is a group of variables (called elements or components) containing values that all have the same
type. Arrays are objects, so they’re considered reference types. As you’ll soon see, what we typically think of
as an array is actually a reference to an array object in memory. The elements of an array can be either
primitive types or reference types (including arrays, as we’ll see in Section 7.9). To refer to a particular
element in an array, we specify the name of the reference to the array and the position number of the
element in the array.

Syntax:

elementType[] arrayRefVar = new elementType[arraySize]; // 1d array


elementType[][] arrayRefVar; // 2d array

To assign values to the elements, use the syntax:

arrayRefVar[index] = value; // 1d array


arrayRefVar[row][column] = value; // 2d array

Examples Using Arrays

1. class ArrayDemo{
2. public static void main(String args[]){
3. int array[] = new int[7];
4. for (int count=0;count<7;count++){
5. array[count]=count+1;
6. }
7. for (int count=0;count<7;count++){
8. System.out.println("array["+count+"] = "+array[count]);
9. }
10. //System.out.println("Length of Array = "+array.length);
11. // array[8] =10;
12. }
13. }

1-Write a program using one-dimensional array of numbers and finds the average of a set of numbers.

1. class Average {
2. public static void main(String args[]) {
3. double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
4. double result = 0;
5. int i;
6. for(i=0; i<5; i++)
7. result = result + nums[i];
8. System.out.println("Average is " + result / nums.length);
9. }
10. }
11.

2-Finding the smallest index of the largest element:

1. public class MyClass {


2. public static void main(String[] args)
3. {
4. double myList[]= {2,4,5,5,3,1};
5. double max = myList[0];
6. int indexOfMax = 0;
7. for (int i = 1; i < myList.length; i++) {
8. if (myList[i] > max) {
9. max = myList[i];
10. indexOfMax = i;
11. }
12. }
13. System.out.println("Max Value :"+max);
14. System.out.println("Max Value's Index :"+indexOfMax);
15. }
16.
17. }

3-Write a program to initialize the elements of 2D array with random numbers.

1. public class Test {


2.
3. public static void main(String[] args) {
4. double[][] array2d = new double[5][5];
5.
6. for (int row = 0; row < array2d.length; row++) {
7. for (int col = 0; col < array2d.length; col++) {
8. array2d[row][col] = Math.round(((Math.random()) * 100));
9. }
10. }
11.
12. for (int row = 0; row < array2d.length; row++) {
13. for (int col = 0; col < array2d.length; col++) {
14. System.out.print(array2d[row][col] + " ");
15. }
16. System.out.print("\n");
17. }
18.
19. }
20.
21. }

Foreach Loops

In Java, the enhanced for loop, also known as the foreach loop, provides a concise way to iterate over arrays
and collections. Here's the basic syntax for a foreach loop in Java

for (datatype element: array) {


// code to be executed for each element
}

4- Write a Java program that calculates the sum of all elements in an integer array using a foreach loop.

1. public class sumOFArray {


2. public static void main(String[] args) {
3. // Create an integer array
4. int[] numbers = {5, 10, 15, 20, 25};
5.
6. // Initialize a variable to store the sum
7. int sum = 0;
8.
9. // Use foreach loop to iterate over the array and calculate the sum
10. for (int num : numbers) {
11. sum += num;
12. }
13.
14. // Display the result
15. System.out.println("Sum of array elements: " + sum);
16. }
17. }
18.
Lab #3 Assignment:

1. Write a Java program that checks whether a given string is a palindrome or not. Ex: CIVIC is palindrome?

2. Write a Java program for sorting a given array of numbers in ascending order?
3. Write a program to sort an array of strings.
4. Write a Java program to multiply two given matrices using 2D array.
Introducing Classes and Objects Lab 4

Objective: Understanding concepts of class and object in java. Implementing a class with members including
data, methods and constructors.

Classes
A class consists of
• Data(variables)
• Methods
• Constructors

Classes are constructs that define objects of the same type. A Java class uses variables to define data fields
and methods to define behaviors. Additionally, a class provides a special type of methods, known as
constructors, which are invoked to construct objects from the class.

class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}

Declaring/Creating Objects in a Single Step


Lab Task 1:
class Box {
double width;
double height;
double depth;

// compute and return volume


double volume() {
return width * height * depth;
}
}

// ___________ Demo Class ___________


class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/*
assign different values to mybox2's instance variables
*/
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

1. Default constructor (no-arg constructor)


2. Parameterized constructor
Example of Default constructors

//Java Program to create and call a default constructor


class demo{
//creating a default constructor
demo(){
System.out.println("Hello World");}
//main method
public static void main(String args[]){
//calling a default constructor
demo b=new demo();
}
}

Example of parameterized constructor

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Adding Constructor in lab task 1

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Lab # 4 Assignment:

Create a class Calculator with following details;

• The class should contain default and parameterized constructor. The constructors should just print the
statement as follows.
▪ “Inside Default Constructor”
▪ “Inside Parameterized Constructor”.

• The class should contain following data fields and methods;


▪ int square = 2 ;
▪ int cube = 3;
▪ calculateSquare(int x)
▪ calculateCube(int x)
▪ calculateFactorial (int x)
▪ generateTable(int x)

• Create objects of this class using both Constructors in main Class.


• Call all three functions via object.
Methods Lab 5

Objective:
The goal of this lab is to understand and implement the concept of methods in Java. You will learn how to
define, call, and utilize methods to perform specific tasks, promote code reusability, and improve program
structure and readability.

Methods
Methods are functions that are associated with classes and objects. They define the behavior of objects and
allow them to perform specific actions or operations. Methods in Java shows/perform the behavior of
objects by bundling related functionality together.

Syntax :

In Java, methods are defined using a syntax that specifies the method's name, return type, parameters (if
any), and the code block that contains the method's implementation.

1. // Method declaration
2. returnType methodName(parameterType1 parameter1, parameterType2 parameter2, ...) {
3. // Method body (code block)
4. // Perform task using parameters
5. // Optionally, return a value using the return statement
6. }

Access Modifiers: Methods in Java can have access modifiers like public, private, protected, or default (no
modifier). These modifiers control the visibility and accessibility of methods from other parts of the program.

Return Type: Methods in Java can optionally specify a return type, which indicates the type of value that the
method returns after execution. If a method does not return any value, its return type is specified as void.

Parameters: Methods in Java can accept zero or more input parameters (arguments), which are specified
within parentheses after the method name. Parameters allow you to pass data to a method for processing.

Method Overloading: Java supports method overloading, which allows multiple methods with the same
name but different parameter lists to coexist within the same class. This provides flexibility and allows for
methods with similar functionality to be grouped together.

Method Invocation/Calling: Methods in Java are invoked using dot notation (object.method() or
class.method()), where the method is called on an object or class instance. The method's code is executed
when it is invoked.

Static Methods: Java allows the declaration of static methods, which are associated with the class itself
rather than individual objects. Static methods can be called directly on the class without needing to create an
instance of the class.

Instance Methods: Instance methods in Java are associated with individual objects created from a class.
They operate on the state of the object and can access instance variables and other instance methods.

1- Create a program in which create a method void type without any parameters and print any statement
in a body.
12. class Activity {
13. // method without return type
14. public void method() {
15. System.out.println("hello");
16. }

2-Create a program to get sum of two values by a method which take two parameters and don’t return
anything.

1. class Activity2 {
2. // method with parameters:
3. public void sum(int a, int b) {
4. result = a + b;
5. System.out.println("Sum : " + a + " + " + b + " = " + result);
6. }
7.}

3- Create a program to get power of a number by a method which take two parameters and return the
power without using Math.pow() function.

22. class Activity3 {


23. // method with a return value
24. public double power(double base, double exponent) {
25. double res = 1;
26.
27. for (int i = 1; i <= exponent; i++) {
28. res = res * base;
29. }
30.
31. return res;
32. }
33. }
Lab # 5 Assignment :
Encapsulation Lab 6

Lab Objective:
The objective of this lab is to understand the concept of encapsulation in Java and practice implementing encapsulation
in classes.

Encapsulation:
Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that refers to the bundling of
data (variables) and methods (functions) that operate on the data into a single unit, called a class. It allows the internal
state of an object to be hidden from the outside world, and only allows access to it through well-defined interfaces. In
simpler terms, encapsulation helps in hiding the implementation details of a class from its users and provides a
controlled way to access and modify data.

To implement encapsulation in Java, follow these general guidelines:

• Declare Data Members as Private: Make instance variables private to prevent direct access from outside the class.
• Provide Getter and Setter Methods: Create public getter methods to retrieve the values of private variables, and
public setter methods to modify the values of private variables. These methods should act as controlled interfaces
for accessing and modifying data.
• Encapsulate Complex Data Types: If your class contains complex data types (e.g., arrays, collections), ensure that
they are also encapsulated properly. Provide methods to interact with these data types, rather than exposing them
directly.
• Ensure Data Validation: Implement data validation checks within setter methods to ensure that the data remains
consistent and valid. For example, you can check if a value being set violates any constraints or business rules.

public class Person {


private int age;
private String name;
public void setAge(int val) {
if(val>0) {
age=val;
System.out.println("Age Record Saved !");
}
else
System.out.println("Wrong Age input");
}
public void setName(String val) {
if(val.length()>10 && val.length()<30) {
name=val;
System.out.println("Name Record Saved !");
}
else {
System.out.println("Wrong Name input");
}
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Access modifiers:
Access modifiers are keywords that define the visibility or accessibility of classes, methods, and fields. They control the
level of access that other classes or packages have to the elements of a class. There are four main access modifiers in
Java

Public (public):
● Public members are accessible from any other class.
There is no restriction on accessing public members.

public class MyClass {

public int myPublicVariable;

public void myPublicMethod() {

// code here

Private (private):

● Private members are only accessible within the same class.


● They are not visible to other classes or packages.

public class MyClass {

private int myPrivateVariable;

private void myPrivateMethod() {

// code here

Protected (protected):

● Protected members are accessible within the same class, same package, and subclasses in other
packages.
● They are not accessible to unrelated classes in different packages.

public class MyClass {

protected int myProtectedVariable;

protected void myProtectedMethod() {

// code here

}
}

Default (Package-Private):

● If no access modifier is specified (also known as package-private or default access), it is visible only
within the same package.
● It is not visible to classes outside the package.

class MyClass {

int myPackagePrivateVariable;

void myPackagePrivateMethod() {

// code here

Exercise 1:

• Define a Java class called Person.


• Add private instance variables for name, and age.
• Ensuring that the age cannot be zero or less.
• Create public getter and setter methods for each variable.
• Test your class by creating Person objects, setting values using setter methods, and retrieving values
using getter methods.

Exercise 2:

• Define a Java class named "BankAccount".


• Add private instance variables for account number (accountNumber), balance (balance), and
account holder name (accountHolderName).
• Implement getter methods (getAccountNumber(), getBalance(), getAccountHolderName()) to
access the values of these variables.
• Implement setter methods (setAccountNumber(), setAccountHolderName()) to set the values of
account number and account holder name respectively.
• Implement a setter method setBalance() to set the balance, ensuring that the balance cannot be
negative. If an attempt is made to set a negative balance, set it to 0 instead.
• Test your class by creating BankAccount objects, setting values using setter methods, and retrieving
values using getter methods. Ensure that negative balances are handled correctly.

Exercise 3:

• Define a Java class named "Customer".


• Add private instance variables for customer ID (customerId), name (name), and email (email).
• Implement getter methods (getCustomerId(), getName(), getEmail()) to access the values of these
variables.
• Implement setter method setEmail(String email) to set the value of the email variable. Ensure that
the email address follows a valid format before setting it. If the email address does not contain "@"
or ".", print an error message and do not set the email.
• Test your class by creating Customer objects, setting values using setter methods, and retrieving
values using getter methods. Try setting both valid and invalid email addresses to ensure proper
validation.
LAB # 6 ASSIGNMENT:
1. Create a Java class named Book to represent a book in a library. Encapsulate the book details
such as ISBN, title, author, and number of available copies. Implement methods to borrow and
return books, and ensure that the number of available copies is updated accordingly. Then,
design a Library class to manage multiple books. Encapsulate the library details and book
collection, and provide methods to add new books, remove books, search for books by title or
author, and display all books in the library.
Q2). Develop a Java class called Employee to represent an employee in a company. Encapsulate the
employee details including employee ID, name, position, and salary. Implement methods to give a
salary raise, change position, and display employee details. Ensure that the salary is a non-negative
value. Then, create a Company class to manage multiple employees. Encapsulate the company
details and employee roster, and provide methods to add new employees, remove employees,
search for employees by name or position, and calculate the total payroll.
These exercises provide opportunities to practice encapsulation in various scenarios, such as
managing products in an online shopping system, accounts in a banking system, books in a library, or
employees in a company. They involve designing classes with private instance variables,
implementing getter and setter methods, and ensuring data integrity and abstraction through
encapsulation.
Array of Object and Method Overloading Lab:7
Objective:

The objective of this lab is to understand and practice the concepts of arrays of objects and method
overloading in Java programming. By the end of this lab, participants should be able to:

• Create and manipulate arrays of objects in Java.


• Implement method overloading to define multiple methods with the same name but different
parameter lists.
• Understand the importance of method overloading in improving code readability and reusability.
• Demonstrate the use of arrays of objects and method overloading in solving practical programming
problems.

Method Overloading:

Method overloading refers to the capability of defining multiple methods with the same name but with
different parameter lists within the same class. The Java compiler uses the number and types of arguments
provided to determine which method to execute. Here's a simple example to illustrate method overloading.

public class MathOperations {

// Method to add two integers


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

// Method to add two doubles


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

Task 1
To practice method overloading by creating multiple add() methods to perform different tasks.

Instructions:
Create a Java class named Calculator.Define multiple overloaded add() methods within the Calculator class as
described below.Test each add() method by invoking them with different arguments from the main() method.

Requirements:

• add(): This method should take two integer inputs from user and display their sum.
• add(int a): This method should take one integer input and display the result of adding it to itself.
• add(int a, int b): This method should take two integer inputs and display their sum.
• add(double a): This method should take one double input and display the result of adding it to itself.
• add(int[] arr): This method should take an integer array as input and display the sum of all elements in the
Array.

Task 2
To practice method overloading in Java by creating a class named AreaCalculator with overloaded methods
to calculate the area of different shapes such as rectangle, circle, and triangle.

• Define a Java class named AreaCalculator.


• Inside the class, create overloaded methods for calculating the area of different shapes: rectangle, circle,
and triangle.
• Implement each method to accept parameters specific to the shape and return the calculated area.
• Calculates the area of a rectangle when two integer arguments are passed
• Calculates the area of a circle when 1 integer arguments is passed.
• Calculates the area of a triangle when two double arguments are passed
• Provide the necessary formulas for calculating the area of each shape within the respective methods:
o For rectangle: Area = length * width
o For circle: Area = π * radius * radius
o For triangle: Area = 0.5 * base * height
• Test the class by creating an instance of AreaCalculator and invoking each overloaded method with
appropriate parameters. Print the calculated areas with change name to verify the correctness of the
implementations.

Array of Object:

an array of objects can be created to store multiple instances of a particular class. Here's a simple example
demonstrating how to create an array of objects in Java
class Book { class Library {
private String title; private Book[] books;
private String author; private int capacity;
private int numberOfBooks;
// Constructor
public Book(String title, String author) { // Constructor
this.title = title; public Library(int capacity) {
this.author = author; this.capacity = capacity;
} books = new Book[capacity];
numberOfBooks = 0;
// Getter methods }
public String getTitle() {
return title; // Add a book to the library
} public void addBook(Book book) {
if (numberOfBooks < capacity) {
public String getAuthor() { books[numberOfBooks] = book;
return author; numberOfBooks++;
} System.out.println("Book added to the
library.");
} else {
System.out.println("Library is full. Cannot add
more books.");
}
}

// Display all books in the library


public void displayBooks() {
System.out.println("Books in the library:");
for (int i = 0; i < numberOfBooks; i++) {
System.out.println("Title: " +
books[i].getTitle() + ", Author: " +
books[i].getAuthor());
}
}
}

public class Main {


public static void main(String[] args) {
// Create a library with a capacity of 3 books
Library library = new Library(3);

// Add some books to the library


library.addBook(new Book("The Great Gatsby", "F. Scott Fitzgerald"));
library.addBook(new Book("To Kill a Mockingbird", "Harper Lee"));
library.addBook(new Book("1984", "George Orwell"));

// Try to add another book (should fail)


library.addBook(new Book("Pride and Prejudice", "Jane Austen"));

// Display all books in the library


library.displayBooks();
}
}

Task 3 ( Array of Object )

Creating Employee Class:


Define a Java class named Employee with the following attributes:

• id (int)
• name (String)
• gender (char)
• contactData (String)

Creating Company Class:


Define a Java class named Company with the following attributes:
• employees (an array of Employee objects)

Adding Employees to Company:


In the main function, create instances of the Company and Employee classes. Allow manual input for
employee details (id, name, gender, contact data) and add these employees to the company employee
array.

Displaying Employee Details:


Write a method in the Company class to display details of all employees in the company. The method
signature should be:

Assignment:
Write a Java program to create a class named Student with the following data fields: id, name, lastName,
and fatherName. Include appropriate constructors and getter methods.
• Implement a class named School that contains an array of Student objects. The School class should have
overloaded methods for searching students based on different criteria.
• Implement an overloaded method in the School class named searchStudent that takes an integer id as
input and print the student's details if match found. If no student is found with the given ID, return null.
• Implement another overloaded method in the School class named searchStudent that takes a String
lastName as input and print the students detail if match found. If no student is found with the given last
name, return an empty array.
• Write a method which display total number or male and female in the class.
• Implement a method for adding the students in array.
Inheritance Lab 8

Inheritance
In programming, inheritance is like building blocks where you create a main block with some common
features. This main block is called a superclass. Then, you can make smaller blocks, called subclasses, that
inherit from the main one. These subclasses add their own special features to the common ones. So,
inheritance helps in organizing and reusing code efficiently. In Java, the main block is the superclass, and the
smaller blocks inheriting from it are subclasses. It's a way to make code more structured and easier to
manage.

Syntax :
In Java, inheritance is implemented using the “extends” keyword. Here's the basic syntax:

// inheritance syntax

1. // parent class
2. class Superclass {
3. // Superclass members and methods
4. }
5. // child class / sub class
6. class Subclass extends Superclass {
7. // Subclass members and methods
8. }

// Syntax -2
1. // parent class
2.
3. class Animal {
4. void eat() {
5. System.out.println("Animal is eating...");
6. }
7. }
8. // child/sub class
9.
10. class Dog extends Animal {
11. void bark() {
12. System.out.println("Dog is barking...");
13. }
14. }

Types Of Inheritance

1.Single Inheritance: This is the simplest form, where a subclass inherits from only one
superclass. It's like passing down traits from one parent to one child. For example, a Car class
may inherit from a Vehicle class.
2.Multilevel Inheritance: In this type, a subclass can inherit from another subclass, creating a
chain of inheritance. It's like generations in a family tree, where traits pass from grandparents
to parents and then to children. For instance, a SUV class may inherit from a Car class, which in
turn inherits from a Vehicle class.

3.Hierarchical Inheritance: Here, multiple subclasses inherit from a single superclass. It's like
siblings sharing traits from the same parent. For example, both Car and Motorcycle classes may
inherit from a common Vehicle class.

Task 1

create a class called `Person` with attributes `id` and `name`. Use a constructor to get user input
for these attributes. Implement a method `display()` to show the person's details.

Then, create a class `Student` that extends `Person`. Add attributes `regNo` and `program`. In its
constructor, get user input for these attributes and call the superclass constructor to set `id` and
`name`. Include a method `viewDetails()` to display the student's information.

1. public class Person {


2. int id;
3. String name;
4. Scanner sc = new Scanner(System.in);
5. Person(){
6. System.out.println("Enter id :");
7. id =sc.nextInt();
8. System.out.println("Enter Name :");
9. sc.nextLine();
10. name =sc.nextLine();
11. }
12. void display(){
13. System.out.println("Name :"+name);
14. System.out.println("id :"+id);
15. }
16. }
17. class Student extends Person{
18. int regNo;
19. String program;
20. Scanner sc = new Scanner(System.in);
21.
22. public Student(int regNo) {
23. this.regNo = regNo;
24. System.out.println("Enter Program :");
25. program=sc.nextLine();
26. }
27. public void viewDetails(){
28. display();
29. System.out.println("REGNO :"+regNo);
30. System.out.println("program :"+program);
31. }
32. }

Task 2

Create a Java class named Person with attributes id and name. Develop a constructor method
within this class and pass parameters id and name, initializing the attributes accordingly.
Additionally, include a method named display() to display the details of the person. Now, create
a subclass named Employee, extending the Person class. Introduce specific attributes for
employees, such as employeeNo, deptNo, and des (designation). Within the constructor
method of the Employee class, prompt the user to input values for employeeNo and deptNo,
while simultaneously calling the superclass constructor to set id and name. Implement a
method named view() to present information about an employee, including both personal and
employment details

34. public class Person {


35. int id;
36. String name;
37. Scanner sc = new Scanner(System.in);
38. Person(int id ,String name){
39. this.id =id;
40. this.name =name;
41. }
42. void display(){
43. System.out.println("Name :"+name);
44. System.out.println("id :"+id);
45. }
46. }class Employee extends Person{
47. int employeeNo;
48. int deptNo;
49. String des;
50. Scanner sc = new Scanner(System.in);
51. public Employee(int employeeNo, int deptNo) {
52. super(1,"Farhad");
53. this.employeeNo = employeeNo;
54. this.deptNo = deptNo;
55. System.out.println("Enter Designation");
56. des=sc.nextLine();
57. }
58. public void view(){
59. display();
60. System.out.println("Employee No :"+employeeNo);
61. System.out.println("Employee Dept No :"+deptNo);
62. System.out.println("Employee Designation :"+des);
63. }
64. }

public class Shape {


String colour;
public Shape(String colour) {
this.colour = colour;
}

public void calculateArea(){


System.out.println("No Area Specified in this Area");
}

}
class Circle extends Shape{
double radius;

public Circle(double radius) {


super("blue");
this.radius = radius;
}

public void calculateArea(){


System.out.println("Circle Area :"+(Math.PI*Math.pow(radius,2)));
}
}
class Triangle extends Shape{
double breth, height;

public Triangle(double breth, double height) {


super("Green");
this.breth = breth;
this.height = height;
}
public void calculateArea(){
double ans = (0.5)*breth*height;
System.out.println("Triangle Area :"+ans);
}
}
class Rectangle extends Shape{
double width, height;

public Rectangle(double width, double height) {


super("brown");
this.width = width;
this.height = height;
}

public void calculateArea(){


System.out.println("Rectangle Area :"+(width*height));
}
}
class Main{
public static void main(String[] args) {
Shape []list = new Shape[3];
list[0]= new Circle(2.2);
System.out.println("Colour "+list[0].colour);
list[0].calculateArea();

list[1]= new Triangle(5.5,33.2);


System.out.println("Colour "+list[1].colour);
list[1].calculateArea();

list[2]= new Rectangle(12.2,22.1);


System.out.println("Colour "+list[2].colour);
list[2].calculateArea();
}

JavaFX LAB 9
Objectives:

To familiarize students with JavaFX, its components, and event handling mechanisms through hands-on
exercises. By the end of the lab, students should be able to create interactive user interfaces using JavaFX,
understand the lifecycle of JavaFX applications, and handle user input effectively.".

javaFX:

JavaFX is a set of Java libraries for building desktop and rich internet applications (RIAs) that can run across
multiple platforms. It provides a comprehensive toolkit for creating modern graphical user interfaces (GUIs),
animations, multimedia, and interactive content in Java. JavaFX supports a wide range of features including
2D and 3D graphics, audio and video playback, and integration with web technologies

JavaFX Application Structure

Stage

● A stage (a window) contains all the objects of a JavaFX application.

Scene

● A scene represents the physical contents of a JavaFX application. It contains all the contents of a
scene graph.

Scene Graph

● A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene.
● Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
● UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
● Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
● Media elements such as Audio, Video and Image Objects.

Layouts

● VBox (Vertical Box): Arranges its children nodes in a single vertical column.
VBox vbox = new VBox();
vbox.getChildren().addAll(node1, node2, node3);

● HBox (Horizontal Box): Arranges its children nodes in a single horizontal row.
HBox hbox = new HBox();
hbox.getChildren().addAll(node1, node2, node3);

● BorderPane: Divides the space into five regions: top, bottom, left, right, and center.
BorderPane borderPane = new BorderPane();
borderPane.setTop(topNode);
borderPane.setLeft(leftNode);
borderPane.setCenter(centerNode);
borderPane.setRight(rightNode);
borderPane.setBottom(bottomNode);

● GridPane: Arranges its children nodes in a grid of rows and columns.


GridPane gridPane = new GridPane();
gridPane.add(node1, 0, 0); // node1 at (0, 0)
gridPane.add(node2, 1, 0); // node2 at (1, 0)
gridPane.add(node3, 0, 1); // node3 at (0, 1)

● StackPane: Stacks its children nodes on top of each other. Useful for layering nodes.
StackPane stackPane = new StackPane();
stackPane.getChildren().addAll(node1, node2, node3);

● AnchorPane: Allows you to anchor nodes to the edges of the pane.


AnchorPane anchorPane = new AnchorPane();
AnchorPane.setTopAnchor(node, 10.0);
AnchorPane.setLeftAnchor(node, 10.0);

Task 1:

Design a simple GUI by adding single button on scene.

Task 2:

Design a login page using javaFX with eventHandler


package application;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;

public class Main extends Application {


@Override
public void start(Stage PStage) {
GridPane pane=new GridPane();
pane.setAlignment(Pos.CENTER);

pane.add(new Label("User Name"), 0, 0);


TextField usernameInput=new TextField();
pane.add(usernameInput, 1, 0);
pane.add(new Label("Password"), 0, 1);
PasswordField passwordInput=new PasswordField();
pane.add(passwordInput, 1, 1);
Button signin=new Button("Log in");
pane.add(signin, 1, 2);

signin.setOnAction(e -> {
String username = usernameInput.getText();
String password = passwordInput.getText();

// Here you can perform authentication logic


if (check(username, password)) {
System.out.println("Login successful!");
// You can navigate to another scene or perform other actions here
} else {
System.out.println("Invalid username or password. Please try again.");
}
});

Scene myScene=new Scene(pane,300,300);


PStage.setTitle("Login");
PStage.setScene(myScene);
PStage.show();
}
Boolean check(String username, String password) {
// Dummy credentials for demonstration
return username.equals("admin") && password.equals("password");
}

public static void main(String[] args) {


launch(args);
}
}

Lab Assignment:

Design a Simple calculation with basic operation such as addition, multiplication, subtraction & Division.
Abstract Class & Interfaces Lab 10

Objective
The objective of this lab is to understand the concepts of abstract classes and interfaces in Java and their
respective use cases. By the end of this lab, students should be able to differentiate between abstract classes
and interfaces and implement them in practical scenarios.

Abstract Class:

• An abstract class is a class that cannot be instantiated on its own; it must be subclassed.
• It can contain both abstract (methods without a body) and concrete methods (methods with
implementation).
• Abstract methods in an abstract class must be implemented by subclasses, providing a way to
enforce certain behaviors across subclasses.
• Abstract classes can also have fields and constructors.
• Abstract classes are used when you have a common base implementation to share among several
related classes.

Syntax :
1. abstract class Animal {
2. String name;
3.
4. Animal(String name) {
5. this.name = name;
6. }
7.
8. abstract void sound();
9. }
10.
11. class Dog extends Animal {
12. Dog(String name) {
13. super(name);
14. }
15.
16. void sound() {
17. System.out.println(name + " says Woof");
18. }
19. }

Activity 1:

Define Abstract Class:


Create an abstract class named BankAccount.

Include data fields for account number (accountNumber), account holder's name
(accountHolderName), and account balance (balance).
• Include abstract methods deposit, withdraw, and checkBalance.
Implement Deposit Method:
• Implement the deposit method which takes a parameter for the deposit amount and adds it to
the account balance.
Implement Withdraw Method with Validation:
• Implement the withdraw method with validation criteria:
• Ensure that the withdrawal amount is greater than 499.
• Ensure that the withdrawal amount is divisible by 500.
• Deduct the withdrawal amount from the account balance if the validation passes.
• If the validation fails, print an appropriate error message.
Implement Check Balance Method:
• Implement the checkBalance method to return the current account balance.
Create Subclasses:
Create concrete subclasses such as HBL and JS that extend the BankAccount class.
Provide implementations for the abstract methods in each subclass.

Interface:
• An interface is a reference type in Java that is similar to a class but contains only constants, method
signatures, default methods, static methods, and nested types.
• All methods in an interface are implicitly abstract and public (before Java 8), or they can be declared
as default or static (Java 8 and later).
• A class implements an interface, thereby inheriting the abstract methods of the interface.
• Interfaces provide a way to achieve multiple inheritance in Java, as a class can implement multiple
interfaces.
• Interfaces are used when you want to specify a set of methods that a class must implement,
irrespective of the actual implementation.

Syntax :

1. interface Animal {
2. void sound();
3. }
4.
5. class Dog implements Animal {
6. public void sound() {
7. System.out.println("Woof");
8. }
9. }

Acitvity 2:

Define Interface:

• Create an interface named DatabaseConnection.


• Include method signatures for connect(), executeQuery(String query), and disconnect().

Implement Interface:

• Create a class named MySQLDatabase to implement the DatabaseConnection interface.


• Provide implementations for all the methods in the MySQLDatabase class, establishing a connection
to a MySQL database, executing queries, and disconnecting.
Test the Database Connectivity:
• Write a main class to test the database connectivity.
• Create an instance of MySQLDatabase.
• Invoke the connect(), executeQuery(String query), and disconnect() methods to perform database
operations.
Collection and Generic Class LAB 11

Objectives:

● Understand the concept of collections and generic classes in Java.


● Learn how to use built-in collections.
● Implement generic classes to create reusable code components.

Generic Class:

A generic class allows you to create classes that can work with any data type. Here's a simple example of a
generic class .

public class MyGeneric<E > {


E var;
MyGeneric (E val){
var=val;
}
void print() {
System.out.println(var);
}
}
------------------------------------------------------------------------
public class Driver {
public static void main(String[] arg) {
MyGeneric<Integer> obj1=new MyGeneric<>(10);
MyGeneric<Double> obj2=new MyGeneric<>(10.454);
MyGeneric<String> obj3=new MyGeneric<>("Welcome");
test obj=new test();
MyGeneric<test> obj4=new MyGeneric<>(obj);
obj1.print();
obj2.print();
obj3.print();
obj4.print();
}
}

Object Class.

Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if
extends another class then it is indirectly derived. Therefore the Object class methods are available to all Java
classes. Hence object class acts as a root of the inheritance hierarchy in any Java Program.

Task 1:

Write a Java program where an Array can contain multiple values of different types.

package lab13;

public class list<E> {


static Object[] list=new Object[5];
E var;
list(E val) {
var=val;
}
void add(int key,E val) {
list[key]=val;
}
void display() {
for(int i=0;i<list.length;i++) {
System.out.println(i+"th index :-- "+list[i]);
}
}
}

package lab13;

public class Driver {


public static void main(String[] arg) {
list<Integer> obj1=new list<>(10);
list<Double> obj2=new list<>(10.454);
list<String> obj3=new list<>("Welcome");
test obj=new test();
list<test> obj4=new list<>(obj);
obj1.add(0, obj1.var);
obj2.add(1, obj2.var);
obj3.add(2, obj3.var);
obj4.add(3, obj4.var);
obj4.display();

}
}

Task 2
Create a generic class in Java where the type of array or list is specified by an object. The class should have
methods for adding elements by index to the array or list and searching for elements within it. Use required
arguments in methods

package lab13;

public class list<E> {


Object[] list;
int size;
list(int size) {
this.size=size;
list=new Object[size];
}
void add(int index, E val) {
list[index]=val;
}
void display() {
for(int i=0;i<list.length;i++) {
System.out.println(list[i]);
}

}
void search(E val) {
Boolean check=false;
for(int i=0;i<list.length;i++) {
if(list[i]==val) {
System.out.println("Record found at index :"+i);
check=true;
break;
}

}
if(!check) {
System.out.println("Record not Found");
}

}
}

Collection:

Collection refers to a framework or set of classes and interfaces in the Java Collections Framework (JCF) that
provides an architecture to store and manipulate groups of objects. Collections provide various data
structures and algorithms to efficiently handle data, offering flexibility, performance, and ease of use.

Some key points about collections in Java:

1. Java Collections Framework (JCF): Introduced in Java 2, the JCF provides a unified architecture for
representing and manipulating collections. It includes interfaces such as List, Set, Map, and classes such
as ArrayList, LinkedList, HashSet, HashMap, etc.

2. Interfaces: Interfaces in the JCF define common behaviors and operations for different types of
collections. For example, the List interface represents an ordered collection of elements, the Set
interface represents a collection that does not allow duplicate elements, and the Map interface
represents a mapping of keys to values.

3. Classes: Classes in the JCF provide implementations of these interfaces. For example, ArrayList and
LinkedList implement the List interface, HashSet and TreeSet implement the Set interface, and HashMap
and TreeMap implement the Map interface.

4. Common Operations: Collections support common operations such as adding and removing elements,
accessing elements by index or key, searching for elements, iterating over elements, and more.
5. Generics: Java collections extensively use generics to provide type safety. Generics allow you to specify
the type of elements that a collection can contain, reducing the need for explicit type casting and
improving compile-time type checking.

ArrayList:
An ArrayList in Java is a resizable array implementation of the List interface provided by the Java Collections
Framework. It's a dynamic data structure that can grow or shrink in size as needed.

import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> arrayList = new ArrayList<>();

// Adding elements to the ArrayList


arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Orange");

// Accessing elements by index


System.out.println("Element at index 0: " + arrayList.get(0)); // Output: Apple

// Iterating through the ArrayList


System.out.println("Elements in the ArrayList:");
for (String element : arrayList) {
System.out.println(element);
}

// Removing an element
arrayList.remove("Banana");
System.out.println("After removing Banana:");
for (String element : arrayList) {
System.out.println(element);
}
}
}

Lab Assignment:

You are tasked with implementing a generic class called ShoppingCart to simulate a shopping cart
functionality. This class should be able to store items of any data type. You will utilize an user defined
ArrayList to manage the items internally.

Requirements:

1. Implement the ShoppingCart class with the following methods:

● addToCart(T item): Adds an item to the shopping cart.


● removeFromCart(T item): Removes the specified item from the shopping cart.
● getTotalItems(): int: Returns the total number of items in the cart.
● getTotalCost(): double: Calculates and returns the total cost of all items in the cart.
● (Optional) Implement any additional methods you think are necessary for a shopping cart.

2. Create a Java program to test your ShoppingCart class. In this program:

● Create an instance of ShoppingCart to store items of different types (e.g., Electronics, Groceries,
Clothing).
● Add items to the cart and display the cart contents.
● Remove items from the cart and display the updated cart contents.
● Calculate and display the total number of items and the total cost of the items in the cart.
Exception Handling Lab 12

Objective:

The objective of this lab session is to introduce students to the concept of exception handling in Java

Exception in OOP:
Exception handling allows you to deal with unexpected or erroneous situations that may occur during
program execution. Here's a basic overview of how it works:

• Try Block: The code that may throw an exception is enclosed within a try block.

• Catch Block(s): If an exception occurs within the try block, it's caught by a corresponding catch block.
Each catch block handles a specific type of exception.

• Finally Block: This block, if included, is executed whether an exception occurs or not. It's typically
used for cleanup tasks like closing files or releasing resources.

• Throw Keyword: You can use the throw keyword to manually throw an exception. This is useful when
you want to handle exceptional situations explicitly.

TASK 1: Implementing Simple Exception Handling

package demo;

public class Driver {

public static void main(String[] args) {


// TODO Auto-generated method stub
int a,b;
a=10;
b=0;
try {
int res=a/b;
System.out.println("result"+res);
}
catch(ArithmeticException obj) {
System.out.println("Divide by Zero is invalid operation");
}
System.out.println("After exception occured");
}

Task 2: Implementing Exception Handling by using multiple catch block


package demo;

import java.util.*;
public class Driver {

public static void main(String[] args) {


// TODO Auto-generated method stub
int arr[]= {1,4,7,3,10};
int index;

Scanner in=new Scanner(System.in);


System.out.println("Enter An index");

try {
index=in.nextInt();
if(arr[index]%2==0) {
System.out.println("Even number :"+arr[index]);
}
else {
System.out.println("Odd number :"+arr[index]);
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Wrong Index");
}
catch(InputMismatchException e) {
System.out.println("Wrong input type"+e.getMessage());
}

System.out.println("After Exception");
}

Task 3:

package demo;
import java.util.*;
public class Driver {

public static void main(String[] args) {


Scanner in=new Scanner(System.in); // TODO Auto-generated method stub
int arr[]=new int[4];
String temp;
for(int i=0;i<arr.length;i++) {
System.out.println("Index value in string for index :"+i);
temp=in.nextLine();
try {
arr[i]=Integer.parseInt(temp);
}
catch(NumberFormatException e) {
System.out.println("Wrong input");
i--;

}
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}

int index;

System.out.println("Enter An index");

try {
index=in.nextInt();
if(arr[index]%2==0) {
System.out.println("Even number :"+arr[index]);
}
else {
System.out.println("Odd number :"+arr[index]);
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println();
}

Task 4: Using throw Keyword

package demo;
import java.util.*;
public class Driver {

public static void main(String[] args) {


Scanner in=new Scanner(System.in); // TODO Auto-generated method stub

int val=in.nextInt();
if(val>=10) {
System.out.println("Valid input");
}
else {
try {
throw new ArithmeticException("Demo ************");
}
catch(ArithmeticException e) {
System.out.println("Caught by user");
}
}

}
}

Lab Assignment:
Files, Streams and Object Serialization Lab 13
Objective:

The objective of this lab is to provide students with hands-on experience in working with files, streams, and
object serialization in Java

Files
Files can be classified as either text or binary.

Text File
A file that can be processed (read, created, or modified) using a text editor is called a text file.

Binary File
All files other than text files are called binary files.

For example,

Java source programs are stored in text files and can be read by a text editor, but Java class files are stored in
binary files and are read by the JVM.

How Is Text I/O Handled in Java?

• File object encapsulates the properties of a file but does not contain the methods for reading/writing
data from/to a file
• In order to perform I/O, objects using appropriate Java I/O classes need to be created.
I/O classes can be classified as input classes and output classes.
• FileWriter, BufferedWriter, PrintWriter are output classes
• FileReader, BufferedFileReader, Scanner are input classes

Task 1: Create a Java program that writes a specified text string to a text file. The program should follow
these steps:

• Initialize a FileWriter object to create or open a file where the text will be written.
• Wrap the FileWriter in a BufferedWriter to enhance writing efficiency by reducing the number of I/O
operations.
• Use the BufferedWriter to write the text string to the file.
• Ensure that the BufferedWriter is properly closed to flush any remaining data from the buffer to the
file and release system resources.

FileWriter fileWriter = new FileWriter(fileName);

BufferedWriter bufWriter = new BufferedWriter(fileWriter);

bufWriter.write(“ writing a file.");

bufWriter.close();

Task 2 Create a Java program that reads the content from a text file and displays it on the console. The
program should follow these steps:

• Initialize a FileReader object to open the file from which the text will be read.
• Wrap the FileReader in a BufferedReader to enhance reading efficiency by allowing buffered reading
of characters, arrays, and lines.
• Use the BufferedReader to read the text from the file line by line.
• Print each line to the console as it is read.
• Ensure that the BufferedReader is properly closed to release system resources associated with the
stream.

FileReader fileReader = new FileReader(fileName);


BufferedReader bufReader = new BufferedReader(fileReader);
while((line = bufReader .readLine()) != null)
{
System.out.println(line);
}
bufReader.close();

Object I/O

• ObjectInputStream/ObjectOutputStream classes can be used to read/write serializable objects


• ObjectInputStream/ObjectOutputStream perform I/O for objects
• ObjectInputStream/ObjectOutputStream perform I/O for primitive type values, and strings

Serialization

• Serialization in java is a mechanism of writing the state of an object into a byte stream.
• An object can be represented as a sequence of bytes (that includes the object's data as well as information
about the object's type and the types of data stored in the object) in the file. This mechanism is called Object
Serialization

Deserialization

• The reverse operation of serialization is called deserialization.

• An Object can be read from the file, the type information and bytes that represent the object and its data
can be used to recreate the object in memory. This mechanism is called Object Deserialization

Task 3: Create a Java program that saves the state of a Student class instance to a file using serialization.
The program should follow these steps:

• Define a Student class that implements the Serializable interface.


• Create an instance of the Student class and populate it with data.
• Initialize a FileOutputStream to create or open the file where the serialized object will be stored.
• Wrap the FileOutputStream in an ObjectOutputStream to handle the serialization process.
• Use the ObjectOutputStream to write the Student object to the file.
• Ensure that the ObjectOutputStream is properly closed to complete the serialization and release
system resources.

public class Student implements Serializable{


int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
______________________________________________

Student studentObject = new Student( 777,“Simon");


FileOutputStream fout = new FileOutputStream("file.txt");
ObjectOutputStream OutSt = new ObjectOutputStream(fout);
OutSt.writeObject(studentObject);
OutSt.flush();

Task 4: Create a Java program that reads and restores the state of a student class instance from a file using
deserialization. The program should follow these steps:

• Define a student class that implements the Serializable interface.


• Initialize a FileInputStream to open the file containing the serialized Student object.
• Wrap the FileInputStream in an ObjectInputStream to handle the deserialization process.
• Use the ObjectInputStream to read the Student object from the file.
• Cast the deserialized object back to a Student type.
• Display or process the restored Student object's data.
• Ensure that the ObjectInputStream is properly closed to release system resources.

Lab Assignment :

• Define a Serializable Book Class: Create a Book class that implements the Serializable interface. This
class represents a book in the library and includes attributes such as title, author, ISBN, genre, and
availability status. Ensure all fields are serializable to facilitate smooth storage and retrieval.
• Generate Book Records: Simulate the library's catalog by generating an array of Book objects.
Populate these objects with relevant data, including titles, authors, ISBNs, genres, and availability
statuses, reflecting the library's collection.
• Serialization: Serialize the array of Book objects to a file. Use ObjectOutputStream to write the array
to a file in a serialized format. This step mimics the system's action of persistently storing book
records for future access and management.
• Deserialization: Implement the deserialization process to restore the array of Book objects from the
file. Utilize ObjectInputStream to read the serialized objects from the file and reconstruct the array.
This mirrors the system's functionality in retrieving book records from storage.
• Verification and Processing: After deserialization, verify that the array of Book objects has been
successfully restored to its original state. Perform operations such as searching for specific books,
updating availability statuses, or calculating statistics on the library's collection to validate data
integrity.

You might also like