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

Lab Manual OOP1

The document is a laboratory manual for Object Oriented Programming-I (3140705) for B.E. Semester 4th students at Government Engineering College, Rajkot. It includes course outcomes, practical objectives, industry-relevant skills, safety instructions, teaching and examination schemes, suggested learning resources, and installation instructions for Java. The manual also outlines various experiments and programming tasks to develop students' skills in Java programming and object-oriented concepts.

Uploaded by

heetkarena123
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)
10 views41 pages

Lab Manual OOP1

The document is a laboratory manual for Object Oriented Programming-I (3140705) for B.E. Semester 4th students at Government Engineering College, Rajkot. It includes course outcomes, practical objectives, industry-relevant skills, safety instructions, teaching and examination schemes, suggested learning resources, and installation instructions for Java. The manual also outlines various experiments and programming tasks to develop students' skills in Java programming and object-oriented concepts.

Uploaded by

heetkarena123
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/ 41

A Laboratory Manual for

Object Oriented Programming -I


(3140705)

B.E. Semester 4th


(Department of Computer
Engineering)

Government Engineering College, Rajkot


Gujarat
Government Engineering College, Rajkot

Certificate

This is to certify that Mr. /Ms. ___________________________________

Enrollment No. _______________ of B.E. Semester 4th in Computer

Engineering / Artificial Intelligence& Data Science of this Institute has

satisfactorily completed the Practical / Tutorial work for the subject Object

Oriented Programming-I(3140705) for the academic year 2024-25.

Date: __________

Name and Sign of Faculty member

Head of the Department


Object Oriented Programming-I (3140705)

Practical – Course Outcome matrix

Course Outcomes (COs):


1. Use various Java constructs, features and libraries for simple problems.
2. Demonstrate how to define and use classes, interfaces, create objects and methods, how to
override and overload methods, compile and execute programs.
3. Write a program using exception handling, multithreading with synchronization.
4. Write a program using Files, binary I/O, collection Frameworks for a given problem.
5. Design and develop GUI based applications in a group using modern tools and frameworks.
Sr.
Objective(s) of Experiment CO1 CO2 CO3 CO4 CO5
No.

1. To learn basic java programming constructs.

To learn Arrays and Strings in Java. √


2.

3. To implement basic object-oriented concepts. √


4. To implement inheritance and object-oriented concepts. √
To demonstrate the use of abstract classes and
5. √
interfaces.
To implement packages and exception handling in
6. √
JAVA application.
7. To demonstrate I/O from files. √
8. To learn JAVA FX UI Controls. √
9. To implement event handling and animation. √
10. To learn recursion and generics. √
11. To demonstrate the use of Collection framework. √
12. To demonstrate the use of multithreading. √
Industry Relevant Skills

The following industry relevant competency is expected to be developed in the student by


undertaking the practical work of this laboratory.
1. Object oriented application development
2. Networking application development
3. GUI based application development

Instructions for Students


1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination
scheme, skill set to be developed etc.
2. Students shall organize the work in the group and make record of all observations.
3. Students shall develop maintenance skill as expected by industries.
4. Student shall attempt to develop related hand-on skills and build confidence.
5. Students shall make a small project/application in Java.
6. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart from
those included in scope of manual.
7. Student shall refer technical magazines and books.
8. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

Common Safety Instructions


Students are expected to
1. Switch on the PC carefully (not to use wet hands)
2. Shutdown the PC properly at the end of your Lab
3. Carefully Handle the peripherals (Mouse, Keyboard, Network cable etc)
4. Use Laptop in lab after getting permission from Teacher
1. COURSE OUTCOMES

After learning the course, the students should be able to:


1. Use various Java constructs, features and libraries for simple problems.
2. Demonstrate how to define and use classes, interfaces, create objects and methods,
how to override and overload methods, compile and execute programs.
3. Write a program using exception handling, multithreading with synchronization.
4. Write a program using Files, binary I/O, collection Frameworks for a given problem.
5. Design and develop GUI based applications in a group using modern tools and
frameworks.

2. TEACHING AND EXAMINATION SCHEME

Teaching Scheme Credits Examination Marks Total


Marks
L T P C Theory Marks Practical Marks
ESE (E) PA (M) ESE (V) PA (I)
4 0 2 5 70 30 30 20 150

3. SUGGESTED LEARNING RESOURCES

Reference Books:
1. Intro to Java Programming, 10th edition, Y.Daniel Liang, Pearson
2. Object oriented programming with Java , RajkumarBuyya,SThamaraiSelvi, Xingchen
Chu, McGrawHill
3. Programming in Java, SachinMalhotra, SaurabhChoudhary, Oxford
4. Programming with JAVA , E Balagurusamy, McGrawHill
5. CORE JAVA volume -I Cay Horstmann, Pearson
Major Equipment: Computer, Laptop
List of Open Source Software/learning website:
https://docs.oracle.com/javase/tutorial/java/index.html
https://www.tutorialspoint.com/JAVA/
https://dev.java/learn/
https://www.codecademy.com/learn/learn-java
https://www.w3schools.com/java/
Java:
Java is a high-level, class-based, object-oriented programming language that is designed to have
as few implementation dependencies as possible. It is a general-purpose programming language
intended to let programmers write once, run anywhere (WORA), meaning that compiled Java
code can run on all platforms that support Java without the need for recompilation. Java
applications are typically compiled to bytecode that can run on any Java virtual machine (JVM)
regardless of the underlying computer architecture.

OpenJDK:
OpenJDK (Open Java Development Kit) is a free and open-source implementation of the Java
Platform, Standard Edition (Java SE). It is the result of an effort Sun Microsystems began in 2006.
The implementation is licensed under the GPL-2.0-only with a linking exception. Were it not for
the GPL linking exception, components that linked to the Java class library would be subject to
the terms of the GPL license. OpenJDK is the official reference implementation of Java SE since
version 7.

JVM:
The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default
JRE, but developers are free to choose another that meets the specific resource needs of their
applications.

JRE:
The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default
JRE, but developers are free to choose another that meets the specific resource needs of their
applications. The Java Virtual Machine, or JVM, executes live Java applications. Every JRE
includes a default JRE, but developers are free to choose another that meets the specific resource
needs of their applications.

JAVA IDEs:
IDEs typically provide a code editor, a compiler or interpreter and a debugger that the developer
accesses through a unified graphical user interface (GUI). Here are a few popular Java IDEs:

Eclipse: a Java-based open source platform that enables the creation of highly customized IDEs
from plug-in components built by Eclipse members. The platform is user-friendly for beginners
and also suitable for the creation of more sophisticated applications. Eclipse includes a lot of plug-
ins that allow developers to develop and test code written in other languages.

NetBeans: a Java-based IDE and underlying application platform framework. In addition to Java,
JavaScript and JavaFX, NetBeans supports C/C++, PHP, Groovy, and HTML5.
How to install Java for Windows:

Following are the steps on how to install Java in Windows 10 for JDK 8 free download for 32 bit
or JDK8 download for Windows 64 bit and installation

Step 1) Go to https://www.oracle.com/java/technologies/downloads/. Click on JDK Download for


Java download JDK 8.

Step 2) Next,

1. Accept License Agreement


2. Download Java 8 JDK for your version 32 bit or JDK download 64 bit.

Step 3) When you click on the Installation link the popup will be open. Click on I reviewed and
accept the Oracle Technology Network License Agreement for Oracle Java SE development kit
and you will be redirected to the login page. If you don’t have an oracle account you can easily
sign up by adding basics details of yours.
Step 4) Once the Java JDK 8 download is complete, run the exe for install JDK. Click Next

Step 5) Select the PATH to install Java in Windows… You can leave it Default. Click next.
Step 6) Once you install Java in windows, click Close

How to set Environment Variables in Java: Path and Classpath:

The PATH variable gives the location of executables like javac, java etc. It is possible to run a
program without specifying the PATH but you will need to give full path of executable like
C:\Program Files\Java\jdk1.8.0_271\bin\javac A.java instead of simple javac A.java
The CLASSPATH variable gives location of the Library Files.
Let’s look into the steps to set the PATH and CLASSPATH

Step 1) Right Click on the My Computer and Select the properties


Step 2) Click on advanced system settings

Step 3) Click on Environment Variables to set Java runtime environment


Step 4) Click on new Button of User variables

Step 5) Type PATH in the Variable name.


Step 6) Copy the path of bin folder which is installed in JDK folder.

Step 7) Paste Path of bin folder in Variable value. Click on OK Button.

Note: In case you already have a PATH variable created in your PC, edit the PATH variable to
PATH = <JDK installation directory>\bin;%PATH%;

Here, %PATH% appends the existing path variable to our new value

Step 8) You can follow a similar process to set CLASSPATH.


Step 9) Click on OK button

Step 10) Go to command prompt and type javac commands.


If you see a screen like below, Java is installed.
Government Engineering College, Rajkot
Department of Computer Engineering
B.E. 4th Semester
Object Oriented Programming I (3140705)

Enrolment No.___________________ Batch: _____________

Sr. No. Experiment No Page No Date Sign

1. Experiment 1

2. Experiment 2

3. Experiment 3

4. Experiment 4

5. Experiment 5

6. Experiment 6

7. Experiment 7

8. Experiment 8

9. Experiment 9

10. Experiment 10

11. Experiment 11

12. Experiment 12
Experiment No: 1

AIM: To learn basic JAVA programming constructs.

Date:

CO mapped: CO-1

Objectives: (a) To learn and understand the different basic structures in java, such as
syntax, logics, libraries and proper indentation.

Background:

Java Variables

A variable is a container that holds the value while the Java program is executed. A variable
is assigned with a data type. Variable is a name of a memory location. There are three types
of variables in java: local, instance, and static.

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.

There are 8 types of primitive data types:

● boolean data type


● byte data type
● char data type
● short data type
● int data type
● long data type
● float data type
● double data type

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
● Unary Operator,
● Arithmetic Operator,
● Shift Operator,
● Relational Operator,
● Bitwise Operator,
● Logical Operator,
● Ternary Operator and
● Assignment Operator.

Java Control Statements

Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
● Decision Making statements
○ if statements
○ switch statement
● Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
● Jump statements
○ break statement
○ continue statement

Practical questions:
1. Install JDK and IDE in your system. Write down the steps of installation with
screenshots.
2. Write a Program that displays Welcome to Java, Learning Java Now and
Programming is fun.
3. Write a program that solves the following equation and displays the value x and y:
a) 3.4x+50.2y=44.5 2) 2.1x+.55y=5.9 (Assume Cramer’s rule to solve equation
b) ax+by=e x=ed-bf/ad-bc cx+dy=f y=af-ec/ad-bc )
4. Write a program that reads a number in meters, converts it to feet, and displays the
result.
5. Body Mass Index (BMI) is a measure of health on weight. It can be calculated by
taking your weight in kilograms and dividing it by the square of your height in meters.
Write a program that prompts the user to enter weight in pounds and height in inches
and displays the BMI.
Note:- 1 pound=.45359237 Kg and 1 inch=.0254 meters.
6. Write a program that prompts the user to enter three integers and display the integers
in decreasing order.
7. Write a program that prompts the user to enter a letter and check whether a letter is a
vowel or constant.

Additional programs:
8. A cashier has currency notes of denominations 1, 2, 5, 10, 50 and 100. If the amount
to be withdrawn is input through the keyboard, find the total number of currency
notes of each denomination the cashier will have to give to the withdrawer.
9. If a five-digit number is input through the keyboard, write a program to print a new
number by adding one to each of its digits. For example, if the number that is input is
12391 then the output should be displayed as 23502.
10. If lengths of three sides of a triangle are input through the keyboard, write a program
to print the area of the triangle.
11. Write a program to produce the following patterns.

**** 1234
*** 123
** 12
* 1

1234 *
567 ***
89 *****
0 *******
*****
***
*

Observations: Put Output of the program

Conclusion:

Quiz:

1. What is the primary purpose of Java??


2. What is the main method in Java used for?
3. How Java Language is Platform Independent?
4. What is JVM and JRE?

Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 2

AIM: To learn Arrays and Strings in Java.

Date:

CO mapped: CO-1

Objectives:

a) Array manipulation: Learn how to create, populate, access, and modify arrays in Java.
b) String manipulation: Understand how to create and manipulate strings, including
concatenation, comparison, and extraction of substrings.
c) Array and String methods: Explore common array and string methods available in
Java's standard library.

Background:
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on the 1st index, and so on.

There are two types of array.


● Single Dimensional Array
● Multidimensional Array

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.

Practical questions:
1. Write a program that generate 6*6 two-dimensional matrix, filled with 0’s and 1’s ,
display the matrix, check every raw and column have an odd number’s of 1’s.
2. Write a generic method that returns the minimum elements and their indices in a two
dimensional array.
3. Write a method that returns a new array by eliminating the duplicate values in the
array.
4. Write a program to add, subtract or multiply two 3*3 integer arrays as per choice of
user.
Sample Input:
Array 1:
123
456
789
Array 2:
567
120
432
Symbol: +
Sample Output:
6 8 10
576
11 11 11

5. Write a program to sort an array of 10 elements using selection sort.

6. Write a program that prompts the user to enter a string and displays the number of
vowels and consonants in the string.

7. Write a program that prompts the user to enter two strings and displays the largest
common prefix of the two strings.

8. Some websites impose certain rules for passwords. Write a method that checks
whether a string is a valid password. Suppose the password rules are as follows: A
password must have at least eight characters. A password consists of only letters and
digits. A password must contain at least two digits. Write a program that prompts the
user to enter a password and displays Valid Password if the rules are followed or
Invalid Password otherwise.

Observations: Put Output of the program

Conclusion:

Quiz:

1. What are ragged arrays in java and how are they implemented?
2. Differentiate String class and StringBuffer class.
3. How Create a two dimensional array. Instantiate and Initialize it?
4. Explain the various String functions with their syntax.

Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 3

AIM: To implement basic object-oriented concepts.

Date:

CO mapped: CO-2

Objectives:

a) To apply fundamental object-oriented principles, such as class design, encapsulation,


inheritance, and polymorphism, to improve software modularity, code organization,
and maintainability.

b) Implementing these basic object-oriented concepts in your software development


practices will help you create more structured, maintainable, and reusable code, which
is essential for building robust and scalable software systems.

Background:
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:

● Object: Any entity that has a state and behavior is known as an object. For example, a
chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can be
defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the
type of response returned by the objects.
● Class: Collection of objects is called class. It is a logical entity. A class can also be
defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
● Inheritance: When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.
● Polymorphism: If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer differently, to draw something,
for example, shape, triangle, rectangle, etc. In Java, we use method overloading and
method overriding to achieve polymorphism. Another example can be to speak
something; for example, a cat speaks meow, dog barks woof, etc.
● Abstraction: Hiding internal details and showing functionality is known as
abstraction. For example, phone call, we don't know the internal processing. In Java,
we use abstract class and interface to achieve abstraction.
● Encapsulation: Binding (or wrapping) code and data together into a single unit are
known as encapsulation. For example, a capsule, it is wrapped with different
medicines. A java class is an example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
Practical questions:
1. Write a Java application which takes several command line arguments, which are
supposed to be names of students and prints output as given below: (Suppose we enter
3 names then output should be as follows):
Number of arguments = 3
1: First Student Name is =Tom
2: Second Student Name is =Dick
3: Third Student Name is =Harry (Hint: An array may be used for converting
from numeric values from 1 to 20 into String.)

2. Design a class named Rectangle to represent a rectangle. The class contains: Two
double data fields named width and height that specify the width and height of the
rectangle. The default values are 1 for both width and height.

A no-arg constructor that creates a default rectangle.


A constructor that creates a rectangle with the specified width and height.
A method named getArea() that returns the area of this rectangle.
A method named getPerimeter() that returns the perimeter.
Write a test program that creates two Rectangle objects—one with width 4 and height
40 and the other with width 3.5 and height 35.9. Display the width, height, area, and
perimeter of each rectangle in this order.

3. Define a class called Cartesian Point, which has two instance variables, x and y.
Provide the methods get X() and get Y() to return the values of the x and y values
respectively, a method called move() which would take two integers as parameters
and change the values of x and y respectively, a method called display() which would
display the current values of x and y. Now overload the method move() to work with
single parameter, which would set both x and y to the same values,provide
constructors with two parameters and overload to work with one parameter as well.
Now define a class called Test Cartesian Point, with the main method to test the
various methods in the Cartesian Point class.

4. Create a class Employee which has two private data members name and salary and it
has two public member functions named as getData() and putData() where getData()
gets name and salary from the user putData() displays name and salary for any user.

5. Define a class Time with hours and minutes astwo data members, add necessary
member functions to initialize and display data of class. Do not use constructors in a
class. Define a member function sum () which adds two Time objects. (Use the
statements like T3.sum (T1, T2)).

6. Define Class named Point which represents 2-D Point, i.e P (x, y). Define
Defaultconstructor to initialize both data member value 5, Parameterized constructor
to initialize member according to value supplied by user and Copy Constructor.
Define Necessary Function and Write a program to test class Point.

7. Create a class Account. It has three data member account id, name and balance.
Define function to assign value and display value. Define function that search account
number given by the user. If account number exists, print detail of that account. Write
a program using array of object. Declare at least 5 account and print details.
Observations: Put Output of the program

Conclusion:

Quiz:

1. Explain the concept of encapsulation and why it is important in OOP.


2. What is a class, and how does it relate to objects in OOP?
3. Define and explain static and dynamic binding.
4. Explain the concept of method overloading and method overriding in OOP.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 4

AIM: To implement inheritance and object-oriented concepts.

Date:

CO mapped: CO-2

Objectives:

a) To master the fundamental principles of inheritance and object-oriented concepts,


enabling the design and development of efficient, maintainable, and scalable software
solutions by leveraging the power of class hierarchies and code reuse.
b) Implementing these basic object-oriented concepts in your software development
practices will help you create more structured, maintainable, and reusable code, which
is essential for building robust and scalable software systems.

Background:
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system). The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and fields in
your current class also.
Terms used in Inheritance

● Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class that inherits the other class. It is also called
a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
● Reusability: As the name specifies, reusability is a mechanism that facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

Practical questions:
1. A set of 5 words (strings) will be taken as command line arguments. Write a program
to reverse each word and check whether it is palindrome or not using method.
2. Define the class BankAccount to represent an account we open with bank. Define the
subclasses SavingAccount and FixedDepositAccount. Implement the operations like
openAccount(), deposit(), checkBalance(), withdraw() and calInterest() for these
classes.
3. Write a program that finds area of any shape by overloading area () method for
Square, Rectangle, Triangle and Square.
4. Write a program that finds Volume of any shape by overloading volume () method for
Cube, Rectangular Cube and Sphere.
5. Write a Program to maintain employee’s information. Program should illustrate
Inheritance concept. (Use your imagination to create class or subclass used for
employee).
6. Create a base class Shape. Use this class to store two double type values that could be
used to compute area of any shape. Derive two specific classes called Triangle and
Rectangle from the base shape. Add to the base a member function getdata() to
initialize base class data member and another member function display_area() to
compute and display the area of figures. (Use Method Overriding).

Observations: Put Output of the program

Conclusion:

Quiz:
1. What is inheritance in java? Explain different types of inheritance with proper example.
2. Explain the use of final and Super keyword in JAVA
3. Define polymorphism with its need.
4. Explain about Encapsulation, Abstraction.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 5

AIM: To demonstrate the use of abstract classes and interfaces.

Date:

CO mapped: CO-2

Objectives:

a) To understand the purpose and usage of abstract classes and interfaces in object-
oriented programming. Develop the ability to design and implement abstract classes
and interfaces effectively to promote code reusability, ensure consistent behavior in
class hierarchies, and facilitate the development of flexible and extensible software
systems.
b) Abstract classes and interfaces are important OOP concepts that allow you to define
common contracts and behaviors for classes. Achieving this objective will enable you
to use these tools to create more modular and maintainable software, especially when
dealing with class hierarchies and multiple implementations.

Background:
A class that is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
● An abstract class must be declared with an abstract keyword.
● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the
method.

An interface in Java is a blueprint of a class. It has static constants and abstract methods. The
interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not the method body. It is used to achieve abstraction and multiple
inheritance in Java. In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.

Practical questions:
1. Describe abstract class called Shape which has three subclasses say Triangle,
Rectangle, Circle. Define one method area() in the abstract class and override this
area() in these three subclasses to calculate for specific object, i.e., area() of Triangle
subclass should calculate area of triangle etc. Same for Rectangle and Circle.
2. Write a program that demonstrates the instance of operator. Declare interfaces I1 and
I2. Interface I3 extends both of these interfaces. Also declare interface I4. Class X
implements I3. Class W extends X and implements I4. Create an object of class W.
Use the instance of operator to test if that object implements each of the interfaces and
is of type X.
3. Write a java program to implement an interface called Exam with a method Pass (int
mark) that returns a boolean. Write another interface called Classify with a method
Division (int average) which returns a String. Write a class called Result which
implements both Exam and Classify. The Pass method should return true if the mark
is greater than or equal to 50 else false. The Division method must return "First" when
the parameter average is 60 or more, "Second" when average is 50 or more but below
60, "No division" when average is less than 50.

Observations: Put Output of the program

Conclusion:

Quiz:

1. Explain how interfaces promote the concept of multiple inheritances in OOP.


2. What is an interface, and how does it differ from an abstract class?
3. When would you choose to use an abstract class over an interface, and vice versa, in
your software design?
4. Can a class implement multiple interfaces? If so, what benefits does this provide?
5. Can you declare an interface method static? Justify your answer.

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 6

AIM: To implement packages and exception handling in JAVA application.

Date:

CO mapped: CO-3

Objectives:

To effectively implement packages and exception handling in a Java application,


organizing code into logical modules for improved maintainability, and ensuring
robust error handling to enhance the application's reliability and user experience.

Background:

A java package is a group of similar types of classes, interfaces, and sub-packages. Package
in java can be categorized in two forms, built-in package, and user-defined package. There
are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here,
we will have the detailed learning of creating and using user-defined packages.
Exception Handling in Java is one of the powerful mechanisms to handle runtime errors so
that the normal flow of the application can be maintained. In this practical, we will learn
about Java exceptions, their types, and the difference between checked and unchecked
exceptions.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Practical questions:
1. Write a program in Java to develop user defined exception for “Divide by Zero” error.
2. Write a program in Java to demonstrate throw, throws, finally, multiple try block and
multiple catch exception.
3. Write a small application in Java to develop Banking Application in which user
deposits the amount Rs 1000.00 and then start withdrawing ofRs 400.00, Rs 300.00
and it throws exception "Not Sufficient Fund" when user withdraws Rs 500 thereafter.
4. Write an application that contains a method named average () has one argument that is
an array of strings. It converts these to double values and returns their average. The
method generates a NullPointerException,if an array elements is null or a
NumberFormatException, if an element is incorrectly formatted. Include throws
statement in method declaration.
5. Write an application that generates custom exception if first argument from command
line argument is 0.
6. A marklist containing reg.no and marks for a subject is given.if the marks are <0,user-
defined IllegalMarkException is thrown out and handled with the message "Illegal
Mark". For all valid marks, the candidate will be declared as "PASS" if the marks are
equal to or greater than 40, otherwise it will be declared as "FAIL".Write a class
called IllegalMarkException.
7. Assume that there are two packages, student and exam. A student package contains
Student class and the exam package contains Result class. Write a program that
generates mark sheet for students.
8. Define a class A in package a pack. In class A, three variables are defined of access
modifiers protected, private and public. Define class B in package bpack which
extends A and write display method which accesses variables of class A. Define class
C in package cpack which has one method display() in that create one object of class
A and display its variables. Define class ProtectedDemo in package dpack in which
write main() method. Create objects of class B and C and class display method for
both these objects.

Observations: Put Output of the program

Conclusion:

Quiz:
1. Explain the benefits of organizing classes into packages in a Java application.
2. How do you declare and define a package in Java?
3. What is an exception in Java, and why is exception handling important in software
development?
4. Explain the try-catch-finally block and its role in handling exceptions.
5. What is difference between throw and throws?

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 7

AIM: To demonstrate I/O from files.

Date:

CO mapped: CO-4

Objectives:

To showcase proficiency in reading data from and writing data to files in various
formats using programming languages, demonstrating the ability to implement
reliable and efficient file I/O operations, which are essential for tasks such as data
storage, retrieval, and processing in software applications.

Background:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.

Practical questions:
1. Write a program that removes all the occurrences of a specified string from a text file.
For example, invoking java Practical7_1 John filename removes the string John from
the specified file. Your program should read the string as an input.
2. Write a program that will count the number of characters, words, and lines in a file.
Words are separated by whitespace characters. The file name should be passed as a
command-line argument.
3. Write a program to create a file named Practical7.txt if it does not exist. Write 100
integers created randomly into the file. Integers are separated by spaces in the file.
Read the data back from the file and display the data in increasing order.

Observations: Put Output of the program

Conclusion:
Quiz:
1. What is file input/output (I/O), and why is it important in software development?
2. What are the common modes for opening files, and how do they differ (e.g., read,
write, append)?
3. Describe the concept of file streams and how they are used in file I/O operations.
4. Write short notes about I/O stream classes.

Suggested Reference:
1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 8

AIM: To learn JAVA FX UI Controls.

Date:

CO mapped: CO-5

Objectives:

a) To gain proficiency in JavaFX UI controls, including understanding their features and


capabilities, and developing the ability to create interactive and visually appealing user
interfaces for Java applications. This knowledge will enable the design and
development of user-friendly, responsive, and feature-rich graphical user interfaces
(GUIs) in Java applications.
b) Learning JavaFX UI controls is essential for creating modern and engaging graphical
user interfaces for Java applications. This objective emphasizes not only understanding
the various UI controls but also the practical skills to design and implement user
interfaces effectively.

Background:
Every user interface considers the following three main aspects –

UI elements − These are the core visual elements that the user eventually sees and interacts
with. JavaFX provides a huge list of widely used and common elements varying from basic to
complex, which we will cover in this practical.
Layouts − They define how UI elements should be organized on the screen and provide a
final look and feel to the GUI (Graphical User Interface). This part will be covered in the
Layout chapter.
Behavior − These are events that occur when the user interacts with UI elements.
JavaFX provides several classes in the package javafx.scene.control. To create various GUI
components (controls), JavaFX supports several controls such as date picker, button text
field, etc.
Each control is represented by a class; you can create a control by instantiating its respective
class.

Common elements in a JavaFX application


All JavaFX applications contain the following elements:
1. A main window, called a stage in JavaFX.
2. At least one Scene in the stage.
3. A system of panes and boxes to organize GUI elements in the scene.
4. One or more GUI elements, such as buttons and labels.
The usual procedure for setting up a scene is to build it from the bottom up. First, we make
the GUI elements, then we make boxes and panes to organize the elements, and finally, we
put everything in the scene.
All JavaFX elements such as boxes and panes that are meant to contain other elements have a
child list that we can access via the getChildren() method. We put elements inside other
elements by adding things to child lists. In the code above you can see the button and the
label objects being added as children of a VBox, and the VBox, in turn, is set as the child of a
StackPane.
In addition to setting the structure for the window, we also call methods designed to set the
properties of various elements. For example, the code in this example uses the button's
setText() method to set the text the button will display.
Follow the procedure outlined in the section above to make a new JavaFX application.
Replace the start() method in the App class with the following code:
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");

StackPane root = new StackPane();


VBox box = new VBox();
box.getChildren().add(btn);
Label label = new Label();
box.getChildren().add(label);
root.getChildren().add(box);

btn.setOnAction(new ClickHandler(label));

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

Practical questions:
1. Write a program that displays five texts vertically, as shown in Figure. Set a random
color and opacity for each text and set the font of each text to Times Roman, bold,
italic, and 22 pixels.
2. Write a program that uses a bar chart to display the percentages of the overall grade
represented by projects, quizzes, midterm exams, and the final exam, as shown in
Figure b. Suppose that projects take 20 percent and are displayed in red, quizzes take
10 percent and are displayed in blue, midterm exams take 30 percent and are
displayed in green, and the final exam takes 40 percent and is displayed in orange.
Use the Rectangle class to display the bars. Interested readers may explore the
JavaFXBarChart class for further study.

3. Write a program that displays a rectanguloid, as shown in Figure a. The cube should
grow and shrink as the window grows or shrinks.
Observations: Put Output of the program

Conclusion:

Quiz:
1. Explain the evolution of Java GUI technologies since awt,swing and JavaFX.
2. What is the purpose of a TextField control, and how can it be used to collect user
input?
3. How to create an ImageView from an Image, or directly from a file or a URL?.
4. What are the primary layout controls in JavaFX, and how do they impact the
arrangement of UI components?
5. What is CSS, and how is it used for styling JavaFX UI controls?

Suggested Reference:

1. https://www.tutorialspoint.com/java/
2. https://www.geeksforgeeks.org/
3. https://www.w3schools.com/java/
4. https://www.javatpoint.com/
Experiment No: 9

AIM: To implement event handling and animation.

Date:

CO mapped: CO-5

Objectives:

To proficiently implement event handling and animation in software applications,


fostering user interaction and engagement. Mastery of event-driven programming and
animation techniques will empower the creation of dynamic, responsive, and visually
captivating software experiences that cater to user needs and preferences.

Background:

Responding to user events


For a GUI application to be interactive, various elements such as buttons have to be able to
respond to interactions from the user, such as clicks. In GUI applications user actions such as
mouse clicks and key presses are called events. To set up an element such as a button to
respond to user events, we arrange to connect special event handling code to the button.
Our first example demonstrates one way to do this in JavaFX. The first step is to connect an
object to the button as the button's event handler via the button's setOnAction() method. The
requirement here is that the object that we link to the button has to implement a particular
interface, the EventHandler<ActionEvent> interface. That interface has one method in it, a
handle() method that will get called when the user clicks on the button.
For the event handler code to do something useful, it will typically need to have access to one
or more elements in the scene that will be affected by the button click. In this example,
clicking the button will trigger a change in the text displayed in a label in the scene. To make
this all work, the class we set up needs to have a member variable that is a reference to the
label object. The code in handle() will use that reference to change the text shown in the label
when the user clicks on the button.
Also, insert the code for the following class at the bottom of the App.java file:
classClickHandler implements EventHandler<ActionEvent> {
publicClickHandler(Label label) {
this.label = label;
}

public void handle(ActionEventevt) {


label.setText("Hello, World!");
}
private Label label;
}

A better way to handle events

Although the process for linking an event handler to a button is fairly straightforward, it is a
little clunky. This process can get even more tedious when we start building applications with
many buttons that need event handlers. As a fix for this, JavaFX allows us to use a simpler
mechanism to set up event handlers.
To see how this mechanism works, remove the ClickHandler class completely and replace the
line of code in start() that calls the button's setOnAction() method with this:
btn.setOnAction((e)->{label.setText("Hello, World!");});
The ClickHandler class that you just eliminated had a handle() method in it. That method
took a single parameter, which was an ActionEvent object, e. The code we just put in place of
the original code contains a lambda expression mapping that parameter e to a chunk of code
that will run when the event takes place. This code is the code that used to live in the body of
the handle() method. The new statement saves a lot of space over the original. The lambda
expression replaces the ClickHandler class and its handle() method with a simpler alternative.

Practical questions:
1. Write a program that can dynamically change the font of a text in a label displayed on
a stack pane. The text can be displayed in bold and italic at the same time. You can
select the font name or font size from combo boxes, as shown in Figure. The available
font names can be obtained using Font.getFamilies(). The combo box for the font size
is initialized with numbers from 1 to 100.

2. Write a program that displays a moving text, as shown in Figure. The text moves from
left to right circularly. When it disappears in the right, it reappears from the left. The
text freezes when the mouse is pressed and moves again when the button is released.
3. Create animation in Figure to meet the following requirements:

■ Allow the user to specify the animation speed in a text field.

■ Get the number of iamges and image’s file-name prefix from the user. For example, if
the user enters n for the number of images and L for the image prefix, then the files are
L1.gif, L2.gif, and so on, to Ln.gif. Assume that the images are stored in the image
directory, a subdirectory of the program’s class directory. The animation displays the
images one after the other.

■ Allow the user to specify an audio file URL. The audio is played while the animation
runs.

Observations:

Conclusion:

Quiz:
1. How does event handling work in Java, and what is the event-driven programming model?
2. What is the role of the java.awt.event and javafx.event packages in Java event handling?
3. Explain: MouseEvent, KeyEvent, ActionEvent
4. What are the primary libraries or frameworks for creating animations in Java, and which one
do you prefer?
5. How to set the cycle count of an animation to infinite?
Experiment No: 10

AIM: To learn recursion and generics.

Date:

CO mapped: CO-4

Objectives:

a) To develop a deep understanding of recursion and generics in programming. Mastery of


recursion will enable the development of elegant and efficient algorithms for solving complex
problems. Understanding generics will facilitate the creation of flexible, reusable, and type-
safe code in various programming languages.

b) Learning recursion and generics is crucial for building efficient algorithms and writing more
versatile and type-safe code in software development. Achieving this objective will help you
become a more proficient and well-rounded programmer.

Background:

Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called the recursive method.
Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time. Before generics, we can store any type of object in the
collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
object.

Practical questions:

1. Write a recursive method that converts a decimal number into a binary number as a
string. The method header is: public static String dec2Bin(int value)
2. Write a test program that prompts the user to enter a decimal number and displays its
binary equivalent.
3. Write the following method that returns a new ArrayList. The new list contains the
non-duplicate elements from the original list.

public static <E>ArrayList<E>removeDuplicates(ArrayList<E> list)

4. Implement the following method using binary search.


public static <E extends Comparable<E>>
intbinarySearch(E list, E key)

Observations:

Conclusion:

Quiz:

1. What is recursion in Java, and how does it differ from iteration in solving problems?
2. What are the advantages and disadvantages of using recursion in Java?
3. What are generics in Java, and why are they used for creating parameterized types?
4. How to define Generic class? What are restrictions of generic programming?
5. Can you provide an example of a generic class in Java, such as a generic ArrayList?
Experiment No: 11

AIM: To demonstrate the use of Collection framework.

Date:

CO mapped: CO-4

Objectives:

a) To proficiently demonstrate the use of Java's Collection framework, including


understanding its core interfaces (List, Set, Map), implementing and manipulating
data structures like lists, sets, and maps, and effectively applying collections for data
storage, retrieval, and manipulation in Java applications.

b) Mastery of the Java Collection framework is essential for managing and organizing
data efficiently in Java applications. This objective focuses on understanding the core
collection interfaces and using them to build versatile data structures to meet various
application needs.

Background:

The Collection in Java is a framework that provides architecture to store and manipulate a
group of objects. Java Collections can achieve all the operations that you perform on data
such as searching, sorting, insertion, manipulation, and deletion. Java Collection means a
single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue,
Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).

Practical questions:
1. Write a program that lets the user enter numbers from a graphical user interface and
displays them in a text area, as shown in Figure. Use a linked list to store the numbers.
Do not store duplicate numbers. Add the buttons Sort, Shuffle, and Reverse to sort,
shuffle, and reverse the list.

2. Create two priority queues, {"George", "Jim", "John", "Blake", "Kevin", "Michael"}
and {"George", "Katie", "Kevin", "Michelle", "Ryan"}, and find their union,
difference, and intersection.
3. Store pairs of 10 states and its capital in a map. Your program should prompt the user
to enter a state and should display the capital for the state.
Observations:

Conclusion:

Quiz:

1. Write a note on ‘Collection in JAVA’. Also discuss List and Enumeration Interface.
2. Differentiate between Enumeration and Iterator.
3. Compare List, Set and Map interfaces. Also compare ArrayList, TreeSet and
HashMap classes in java.
4. Explain the unique features of Map interface.
5. How do you perform common operations like sorting, searching, or filtering on
Collections?
Experiment No: 12

AIM: To demonstrate the use of multithreading.

Date:

CO mapped: CO-3

Objectives:

a) To effectively demonstrate the use of multithreading in software applications, including


creating and managing multiple threads, synchronizing their execution, and leveraging the
power of concurrent programming to improve performance, responsiveness, and resource
utilization.

b) Demonstrating the use of multithreading is crucial for building responsive and efficient
software applications, and this objective emphasizes understanding the concepts and practical
implementation of multithreading to achieve these goals.

Background:

Multithreading in Java is a process of executing multiple threads simultaneously. A thread is


a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking. However, we use multithreading than
multiprocessing because threads use a shared memory area. They don't allocate separate
memory areas so saves memory, and context-switching between the threads takes less time
than the process. Java Multithreading is mostly used in games, animation, etc.

Practical questions:

1. Write a program to create a thread extending Thread class and demonstrate the use of slip()
method.
2. Write a program to create a thread implementing Runnable interface and demonstrate the use
of join() method.
3. Write a program that launches 10 threads. Each thread adds 1 to a variable sum that initially is
0. Define an Integer wrapper object to hold sum. Run the program with and without
synchronization to see its effect.

Observations:

Conclusion:

Quiz:

1. Can you explain the difference between a process and a thread in the context of
multithreading?
2. What are the different states in the lifecycle of a Java thread, and how does a thread transition
between them?
3. What is runnable interface? How can you use this interface in creating thread?
4. Explain the concept of thread synchronization and the role of the synchronized keyword.
5. Explain: wait, sleep, notify and notify all.

You might also like