0% found this document useful (0 votes)
3 views47 pages

Java Labmanual

This document is a laboratory manual for the Java Programming Lab course at MGM University, aimed at third-year Computer Science students. It includes guidelines, objectives, and a list of experiments designed to enhance practical understanding of Java programming concepts. The manual emphasizes hands-on experience and encourages students to engage actively with the material to build a strong foundation for their future careers.

Uploaded by

max.pi1969
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)
3 views47 pages

Java Labmanual

This document is a laboratory manual for the Java Programming Lab course at MGM University, aimed at third-year Computer Science students. It includes guidelines, objectives, and a list of experiments designed to enhance practical understanding of Java programming concepts. The manual emphasizes hands-on experience and encourages students to engage actively with the material to build a strong foundation for their future careers.

Uploaded by

max.pi1969
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

MGM University, Chh.

Sambhajinagar
Jawaharlal Nehru Engineering College

Department of Computer Science & Engineering

LAB MANUAL

Program (UG/PG) : UG
Year : Third Year

Semester : V

Course Code : CSE21PCP307

Course Title : Java Programming Lab

Prepared By : Mrs. [Link].


[Link].

Department of Computer Science & Engineering


2025-26 ( Part-II)
FOREWORD

It gives me immense pleasure to present this Laboratory Manual for Third Year Engineering
students for the subject of Java Programming Lab with guidelines of NEP 2020.

This manual is designed to provide clarity and guidance on the key concepts, practical
implementations, and problem-solving strategies related to the subject. Students are
encouraged to explore beyond the prescribed experiments, reflect on each exercise, and
strengthen their understanding through hands-on experience.

At MGM University, we continuously strive to enhance the learning experience of our


students. The institution is proud to be ISO 9001:2015 and 14001:2015 certified, and we
believe in leveraging systematic academic practices for overall student development. We
emphasizes that students should actively utilize this lab manual not just as a procedural
document, but as a stepping stone to sharpen their technical skills. The knowledge and
exposure gained through these experiments will contribute significantly to building a strong
foundation for industry-readiness and innovation.

Faculty members are encouraged to facilitate conceptual understanding during lab sessions,
ensuring that students develop a deep insight into the subject matter. Once concepts are clear,
students will engage with enthusiasm, easing the teaching process and promoting self-directed
learning.

Let this manual be a guide for skill enhancement and a tool for excellence in your academic
journey.

Dr. Vijaya B. Musande


Principal
LABORATORY MANUAL CONTENTS

This manual is intended for the Third Year students of Computer Science and
Engineering in the subject of Java programming. The lab manual typically contains
practical/Lab Sessions related Java programming covering various aspects related to
the subject to enhance understanding.

Students are advised to thoroughly go through this manual rather than only topics
mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.

Good Luck for your Enjoyable Laboratory Sessions

[Link] Dr. Deepa Deshpande


Subject Teacher HOD
DOs and DON’Ts in Laboratory:

1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left
to right.
3. All the students are supposed to enter the terminal number in the log book.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the program/concept
to be implemented.
6. Strictly observe the instructions given by the teacher/Lab Instructor.
7. Do not disturb machine Hardware / Software Setup.
8. Uniform & I-Card are compulsory.
9. Do not use Mobile phones during lab sessions.

Instruction for Laboratory Teachers:


1. Submission related to whatever lab work has been completed should be done
during the next lab session along with signing the index.
2. The promptness of submission should be encouraged by way of marking and
evaluation patterns that will benefit the sincere students.
3. Continuous assessment in the prescribed format must be followed.
MGM University
Jawaharlal Nehru Engineering College,
Chh. Sambhajinagar
Department of Computer Science and Engineering

Vision of CSE Department:

To develop computer engineers with necessary analytical ability and human values who
can creatively design, implement a wide spectrum of computer systems for welfare of
the society.

Mission of the CSE Department:

I. Preparing graduates to work on multidisciplinary platforms


associated with their professional positions both independently and
in a team environment.
II. Preparing graduates for higher education and research in Computer
Science And Engineering enabling them to develop systems for
society development.

Programme Educational Objectives: Graduates will be able to

I. To analyze, design and provide optimal solution for Computer


Science and Engineering and multidisciplinary problems.

II. To pursue higher studies and research by applying knowledge of


mathematics and fundamentals of computer science.

III. To exhibit professionalism, communication skills and adapt to current


trends by engaging in lifelong learning.
Programme Outcomes (POs): Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze


complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of


the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
LIST OF EXPERIMENTS

Course Code: CSE21PCP307


Course Title: Java Programming Lab

Sr. Name of the Experiment


No
Write a program to demonstrate basic syntactical constructs of java.
1.

2. Write a program to demonstrate Arrays & Vector in java.

Write a program to demonstrate Classes and Objects, Methods


3. Constructor in java.
Write a program to implement multiple inheritances with interfaces
4. and method overloading and method overriding.
5. Write a program to create a package & use it in another program
Write a program for this keyword, super keyword, final keyword, static
6. keyword in java.
Write a program to implement exception handling using built-in and user
7. defined exceptions.

8 Write a program to implement the concept of Multithreading.

9 Write a program to demonstrate String class methods.

10 Write a program to retrieve data from Employee Database

11 Mini project
Practical No: 1

Aim: Write simple programs to understand Input-Output statements, Decision


making, control flow statements & Operators in java.

Objective: The objective of this experiment is that student must familiar with java
environment, understand syntax& semantics of java programming language & enhance
their programming confidence . Student must use all the statements, control structure,
looping statements, type casting etc.
Theory: Java is true object oriented programming language with the important Features
like Platform dependencies, distributed, robust, secure, multitasking, Dynamic and many
more.
In this program we are finding the Prime No’s between the ranges. Depends upon
the value of the variable we are initializing in program. We are printing the series of
prime No’s within that range. The particular part is explained below with the Java
programming Syntax.

Class Declaration: As java is true Object oriented language therefore everything


must be placed inside the class. Syntax: class class-Name E.g. class Demo Class is a
keyword, Demo is the identifier that specifies the name of the class to be defined inside
opening & closing Braces.

The Main Line:

Every java application program must include the main() method.

Syntax: public static void main ( String args[] )

Every program begins with the main() method. All the Java applications begin
execution by calling main(). The full meaning of each part of this is:
public:
The public keyword i s an access specifier, w h i c h allows the
programmer to control the visibility of class members. When a class member is preceded
by public, then that member may be accessed by code outside the class in which it is
declared. main( ) must be declared as public, since it must be called by code outside of its class
when the program is started.

static: The keyword static allows main( ) to be called without having to


instantiate a particular instance of the class. This is necessary since main ( ) is called by
the JVM before any objects are made.

void: The keyword void simply tells the compiler that main ( ) doesn’t return a value.

String args[]:
In main ( ), there is only one parameter, albeit a complicated one. String args [ ]
declares a parameter named args, which is an array of instances of the class String. args
receives any command-line arguments present when the program is executed.
The Output Line:
The executable statement in the program is
Syntax: [Link](“Java is better then C++”);
The println() method invoked with the object out of the System class. This line prints the
string Java is better then C++ in Command prompt.
Journal Write-up:
 History of java
 Features of java
 Java virtual machine
 Java architecture & JDK tools
 Typecasting
 Java program structure
List of programs: Problem Statements

1. Implement a program to display the sum of two given numbers if the numbers are same.
If the numbers are not same, display the double of the sum
Sample Input and Output
Sample Input Expected Output
6, 5 22
5, 5 10

2. Implement a program to generate and display the next date of a given date.
The date will be provided as day, month and year as shown in the below table.
The output should be displayed in the format: day-month-year.
Assumption: The input will always be a valid date.
Sample Input and Output

Sample Input Expected Output


Day = 1 2 - 9 - 2015
Month = 9
Year = 15

3. Implement a program to calculate Factorial of a given number.


Sample Input and Output

Sample Input Expected Output


5 120
7 5040

4. Implement a geometric sequence as shown below for a given value n , where n is the
number of elements in the sequence.
1, 2, 4, 8, 16, 32, 64, ................ , 1024
Sample Input and Output

Sample Input Expected Output


5 1, 2, 4, 8, 16
8 1, 2, 4, 8, 16, 32, 64, 128

5. Implement a program to check whether a given number is a palindrome.


Palindrome is a sequence that reads the same backwards as forwards.
E.g.: 121, 1331, 2332, 78900987, 123456654321, etc.
Sample Input and Output
Sample Input Expected Output
1331 1331 is a palindrome
46362 46362 is not a palindrome

6. Implement a program to find out whether a number is divisible by the sum of its digits
Display appropriate messages.
Sample Input and Output
Sample Input Expected Output
2250 2250 is divisible by sum of its digits
123 123 not divisible by sum of its digits

7. Implement a program to check whether a given number is an Armstrong number.


An Armstrong number is an n-digit number that is equal to the sum of the nth powers of
its individual digits.

Eg: 371 is an Armstrong number as 3^3 + 7^3 + 1^3 = 371


1634 is an Armstrong number as 1^4 + 6^4 + 3^4 + 4^4 = 1634.
⮚ Hint :[Link](double a, double b) method to calculate the power of a number.
Sample Input and Output

Sample Input Expected Output


371 371 is an Armstrong number
1635 1635 is not an Armstrong number

8. Implement a program to find and display the least common multiple (LCM) of two
whole numbers.
Least Common Multiple (LCM) of two numbers, num1 and num2 is the smallest
positive number that is divisible by both num1 and num2.
Sample Input and Output

Sample Input Expected Output


num1 = 5, num2 = 10 10
num1 = 7, num2 = 9 63

9. Implement a program to calculate the product of three positive integer values. However,
if one of the Integers is 7, consider only the values to the right of 7 for calculation. If 7 is
the last integer, then display -1.
Note: Only one of the three values can be 7.
Sample Input and Output
Sample Input Expected Output
1, 3, 5 15
3, 7, 8 8
7, 2, 9 18
2, 6, 7 -1

10. Implement a program to find the number of rabbits and chickens in a farm. Given the
number of heads and legs of the chickens and rabbits in a farm, identify and display the
number of chickens and rabbits in the farm.
If the given input cannot make a valid number of rabbits and chickens, them display an
appropriate message.
Sample Input and Output

Sample Input Expected Output


Heads = 150, legs = 500 Chickens = 50
Rabbits = 100
Heads = 3, legs = 11 The number of chickens and rabbits cannot
be found

11. Implement a program to check whether a given number is a palindrome.


Palindrome is a sequence that reads the same backwards as forwards.
E.g.: 121, 1331, 2332, 78900987, 123456654321, etc.
Sample Input and Output

Sample Input Expected Output


1331 1331 is a palindrome
46362 46362 is not a palindrome

12. Implement a program to display the below pattern.


*****
****
***
**
*
13. Implement a program to find out whether a number is a seed of another number, A
number X is said to be a seed of number Y if multiplying X by its every digit equates to
Y.
E.g.: 123 is a seed of 738 as 123*1*2*3=738
Sample Input and Output
Sample Input Expected Output
123, 738 123 is a seed of 738
45, 1000 45 is not a seed of 1000

Conclusion: Hence we have studied syntax of semantics of java


Practical No: 2

Aim: Write a program to demonstrate Arrays & Vector in java.


Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad++)
Theory:
Arrays:
An array is a group of like-typed variables. To create an array, you have to follow
following steps:
1. Declaring an Array.
2. Creating memory location
3. Putting values in memory location
One-dimensional Arrays:
A list of items can be given one variable name using only one subscript and such a
variable called a single subscript variable or One-dimensional array.
The general form of a one-dimensional array declaration is: Syntax:
type var_name[ ] ;
Here, type declares the base type of the array. The base type determines the data
type of each element that comprises the array. Thus the base type for the array determines
what type of data the array will hold.
E.g:int month_days[];
The above line declares an array name month days with the type “array of int” .
new operator:
It is a special operator that allocates memory. The general form of new as it
applies to one-dimensional arrays appears as follows:
Syntax: array-var=new type[size];

here, type specifies the type of data being allocated, size specifies the number of elements
in the array, and the array-var is the array variable that is linked to the array. That is,to
use new to allocate an array, you must specify the type and the number of elements to
allocate. The elements in an array allocated by new will automatically be initializing to
zero.
E.g.: Month_days=new int[12];
This example allocates a 12 – element array of integers and links them to month_days.
Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will see, there
are a couple of subtle differences. To declare this variable, specify each additional index
using another set of square brakets. For example, the following declares a two-
dimensional array variable called twoD.
int two D[][]=new int [4][5];
This allocates a 4 by 5 array and assigns it to two D. Internally this matrix is implements as
an array of arrays of int.
What is Vector in Java?
Vector is a resizable array in Java, part of the Java Collection Framework.
It is synchronized, which means it is thread-safe (multiple threads can access it without
corrupting data).
It implements the List interface, so it maintains the order of insertion and allows duplicate
elements.
Key Features:
Dynamic resizing: Automatically grows its size when elements are added beyond its current
capacity.
Synchronized: Thread-safe operations, unlike Array List which is not synchronized.
Legacy class: Introduced in Java 1.0, but later retrofitted to implement the List interface.
Random access: Elements can be accessed in constant time using index.

List of programs: Problem Statements


1. WAP to print highest &lowest number from an array.
2. WAP to find sum & average of numbers.
3. WAP to Store the elements in Array and print.
4. WAP to reverse the elements of Array.
5. WAP to Arrange array in ascending & descending order.
6. WAP to add Elements in specified position and remove from that position
7. WAP to Addition Subtraction multiplication. Of matrix.
8. WAP to implement different methods of Vector class.
9. WAP to accept name of five students from the command line & store them in a vector.
Perform the following operations-
• Display the size& capacity
• Delete an item in the list
• Add an item at a specified location
• Print the contents of the vector
10. [Link] find first & second biggest number from an array

Conclusion: Hence we studied Arrays & Vector in java


Practical No 3
Aim: Write a program to demonstrate Classes and Objects, methods constructor in java
Theory: Java is true object oriented programming language so everything is placed inside the
class. Class is user defined data type containing Members of class.
Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad++)
Class Definition:
Syntax
Class classname{
type instance-variable1;

type instance-variable2;

//……
Type instance-variable N;
Type methodName1(parameter-list){
//body of method
}
Type methodName2(parameter-list){
//bodyofmethod
}
//……
Type methodNameN(parameter-list){
//bodyofmethod
}
}
E.g:classDemo
{
int i;
void getdata();
}
Class is keyword and declares that a new class definition follows. Demo is a java
identifier that specifies the name of class to be defined with the class Members .
The general form of a method declaration is type
method name ( parameter – list )
{
method–body;
}
Method declaration have four basic parts:
1. The name of the method
2. The type of the value the method returns
3. A list of parameters
4. The body of the method
Creating Object:
Object is instance of class, is block of memory that contains space to store all the instance
variables. Object in java is created using new operator. It is a special operator that
allocates memory.
Syntax: Obj-name=new Class-name();
E.g: Student S1;// Declare the object
S1=new Student();//instantiate the object S1 is the
object of Student class.
Accessing class Members:
Once we create object of class,each containing its set of variables we should assign
values to those variables in order to use them in our program. All variables must assign
values before they used.
Syntax:
classname classobjname= new classname ( ) ; [Link] = Value;
Object [Link] (ParameterList);
Here Object name is name of object,variable name is name of instance variable inside the
object that we wish to access, Method name is the method we wish to call.
E.g:[Link]=80;
[Link]();
S1is object name,Marks is variable name, getdata( ) is method which is accessed with the
object and dot operator.
Algorithm:
1) Creating a class, define class variables, member functions of class.
2) Initialize the class variables
3) Define main class, create object of above class with the help of (.) Dot operator
and obj name. Access members of above class in main class.
List of programs: Problem Statements

[Link] a class of object interest with a constructor. WAP to find the simple interest using the
formula 21 Simple Interest=PNR/100 Where P –principal amount N – No of years R –rate of
interest
Simple Interest=PNR/100 Where P –principal amount
N–No of years R –rate of interest

1. WAP using different type of constructors to find the area of rectangle.

3. WAP to find average of the marks of students. Use methods.

4. WAP to find average of the marks of students. Use methods & constructors.
5. WAP to find product of two numbers using Default constructor.
6. WAP to implement complex number operations
8. Implement a class Calculator with the instance variable and method mentioned below.
Method Description: sumOfDigits()
 Calculate and return the sum of the digits of the num member variable
 Test the functionalities using the provided Tester class.
7. Implement a class Rectangle with the instance variables and methods mentioned below.
calculateArea()
 Calculate and return the area of the rectangle. The area should be rounded off to two
decimal digits.
calculatePerimeter()
 Calculate and return the perimeter of the rectangle. The perimeter should be rounded off
to two decimal digits.
 Test the functionalities using the provided Tester class.

Conclusion:
Hence we have studied how to create classes & objects, methods constructors
in java .
Practical No. 4

Aim: Write a program to implement multiple inheritance with interfaces and method
overloading and method overriding.
Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad++)
Theory: Reusability is important aspect of object oriented programming. It is always nice that
we would reuse something that is already exists rather than creating same all over again. Java
supports this concept. Java classes can be reused in several ways.
This is done by creating new classes reusing the properties of existing once. The mechanism of
deriving new class from old class is called Inheritance. The old class is known as base class
(Parent class) and new class is known as Derived class (child class). The inheritance allows child
class to inherit all the variables and methods of
The inheritance allows child class to inherit all the variables and methods of their parent classes.
Types of inheritance: - Single inheritance
- Multilevel inheritance
- Hierarchical inheritance
Defining a Sub-class: A sub-Class is defined as follows:
Syntax: class sub-
classname extends superclassname
{
Variables declarartion;
Method declaration;
}
The extends keyword signifies that the properties of the superclass name are extended to the
subclass name.
The sub class also contain its own variables and methods along with super class.
A derived class with multilevel base class is as follows:
Class A {
}
Class B extends A //First Level
{
} Class C extends B //Second Level
{
}
This process may be extended to any members of level. The C class can inherit members of both
class A and B. Java does not directly implement Multiple inheritance. This concept is
implemented using a secondary inheritance path in the form of interfaces.
Interface
 Interface is a blue print of class.
 It specifies what class must do and not how.
 It is used to achieve abstraction.
 It support multiple Inheritance.
 It can be used to achieve loose coupling.
 We cannot create interface object.
Syntax of creating interface
interface InterfaceName
{
public abstract methods
public static final fields
default concrete methods
static methods
}
List of Programs: Problem Statement:
Problem 1: University Information System
Design a university information system where multiple roles exist — such as Student, Professor,
and Administrator. A Person is-a base class for all roles, while each role has specific behavior
and attributes (e.g., a Student has-a list of Courses, a Professor has-a Department, and an
Administrator has-a Role). The system should support course enrollment, teaching assignments,
and administrative tasks like generating reports. Implement a mechanism to enforce role-specific
permissions.
Ensure polymorphic behavior for tasks like login and access control.
Problem 2: Online Marketplace System
Problem Statement:
Build a backend for an online marketplace. An Account is-a base class, and it branches into
Buyer, Seller, and Admin. Each Seller has-a list of Products, and each Buyer has-a Cart. A
Product has-a Category, Price, and DiscountPolicy. Use inheritance for different types of
discounts like PercentageDiscount and BuyOneGetOne.
 Design polymorphic discount calculation.
 Manage different account privileges and data ownership securely.
 Multiple Interface Inheritance for Payment Methods in an E-Commerce System
Problem:3
Define two interfaces:
 CardPayment with method payWithCard(double amount).
 OnlinePayment with method payOnline(String provider, double amount).
Create a class PaymentProcessor that implements both interfaces. Implement the methods to
print confirmation messages with payment details.
Write a test class where you demonstrate payments using both card and online payment methods.
Multiple Inheritance with Interfaces to Model an Employee Management System
Problem:4
Design the following interfaces:
 Workable with methods startWork() and stopWork().
 Trainable with method attendTraining (String topic).
 Evaluable with method evaluatePerformance().
Create classes representing different employee roles:
Developer implements Workable and Trainable.
Manager implements Workable, Trainable, and Evaluable.
Intern implements Trainable only.
Implement all the methods with meaningful console outputs indicating which role is performing
which action.
Multiple Interface Inheritance for Payment Methods in an E-Commerce System
Problem 5 Encapsulation
Design a class BankAccount to simulate a simple bank account with the following private fields:
 accountNumber (String)
 accountHolderName (String)
 balance (double)
 Implement public getter and setter methods to access and update these fields with proper
validation: The accountNumber and accountHolderName should not be allowed to be
empty or null.
 The balance should never be set to a negative value.
 Provide methods to deposit(double amount) and withdraw(double amount) that update
the balance accordingly, ensuring the balance never goes below zero.
Write a test program to create a BankAccount object, perform deposits and withdrawals, and
display the account details after each operation.

Conclusion: Hence we have studied how to achieve multiple inheritance by using interface in
java.
Practical 5

Aim: Write a program to create a package & use it in another program.


Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad++)
Theory: Package:
Packages are containers for classes that are used to keep the class name space
compartmentalized. It is defined as a collection of classes.
Packages are similar to the directories and classes within a package are similar to files in the
directory. Two categories of packages are in java

Types of Java Packages


Built-in Packages
User-defined Packages
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of the
commonly used built-in packages are:
[Link]: Contains language support classes(e.g. classes which defines primitive data types,
math operations). This package is automatically imported.
[Link]: Contains classes for supporting input / output operations.
[Link]: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
[Link]: Contains classes for creating Applets.
[Link]: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
[Link]: Contain classes for supporting networking operations.
Steps:
 A directory that contains one or more class files.
 Creating a folder
 Moving the class file to the new folder (or creating them there)
 Calling the package from any applications
 The location of packages are defined by using the CLASSPATH environmental variable
 Each class in the package must have the following as its first line package ;
 The classes in the package are loaded into a Java application by using import .* ;

1. Create the Package:


First we create a directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package names.
Example:
package myPackage;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}
2. Use the Class in Program:
Now we will use the MyClass class in our program.
import [Link];
public class Geeks {
public static void main(String args[]) {
// Initializing the String variable with a value
String s = "GeeksforGeeks";
// Creating an instance of class MyClass in the package.
MyClass o = new MyClass();
[Link](s); }}
List of Programs: Problem Statements
Problem 1: Library Management System Package
Create a user-defined package called library to manage a small library system. The package
should have the following classes:
Book: Contains attributes like bookID, bookTitle, authorName, availableCopies. It should have
methods for adding a book, removing a book, and checking availability.
Member: Contains member details like memberID, memberName, contactInfo, and methods for
borrowing and returning books.
Library: Contains a collection of books and members. It should have methods like addBook(),
removeBook(), registerMember(), and issueBook().
Demonstrate the usage of the classes in a main program.
Problem 2: Student Management System Package
Design a user-defined package called student to manage student information. The package
should contain:
A class Student with properties like studentID, studentName, course, and methods to add,
display, and update student details.
A class Course with properties like courseCode, courseName, courseDuration, and methods to
add, display, and update course information.
A class Enrollment to associate a student with a course and track the enrollment date.
Demonstrate the usage of these classes in a main program.
Problem Statement:3
Create a user-defined package called calculator which implements a basic calculator system.
The package should contain:
A class BasicOperations with methods for addition, subtraction, multiplication, and division.
A class AdvancedOperations with methods for square root, power, and logarithmic
calculations.
A class Calculator that imports both BasicOperations and AdvancedOperations and allows a
user to select different operations to perform.
Demonstrate the usage of these operations in a simple console application.

Conclusion: Hence we studied how to implement Package in java.


Practical No. 6
Aim : To study use of this, super, static, and final keywords in Java.
Objective:
The objective of this lab experiment is to understand the use of the following keywords in Java
[Link] 2. Super [Link] [Link]
Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad)
Theory:
1. this Keyword:
The this keyword refers to the current instance of the class. It can be used to:
Differentiate between instance variables and local variables when they have the same name.
Invoke the current object's method.
Pass the current instance of the object to other methods.
2. super Keyword:
The super keyword is used to:
Access superclass methods or constructors.
Access superclass instance variables.
Invoke the constructor of the superclass.
3. static Keyword:
The static keyword is used to:
Define class-level variables and methods that are shared by all instances of the class.
Access static variables and methods without creating an instance of the class.
4. final Keyword:
The final keyword is used to:
Define constants (immutable values).
Prevent method overriding.
Prevent inheritance (final class cannot be subclassed).
1. this Keyword Example:
Create a simple Java class Student where we use the this keyword to differentiate between
instance variables and local variables.
class Student {
private String name;
private int age;

// Constructor
public Student(String name, int age) {
[Link] = name; // 'this' refers to the current object's instance variable
[Link] = age;
}

public void displayDetails() {


[Link]("Name: " + [Link]); // Referring to instance variable using 'this'
[Link]("Age: " + [Link]);
}
}

public class ThisKeywordExample {


public static void main(String[] args) {
Student student = new Student ("John", 20);
[Link]();
}
}
2. super Keyword Example:
Create a superclass Animal and a subclass Dog where the super keyword is used to call the
superclass constructor and methods.
java
CopyEdit
class Animal {
public void speak() {
[Link]("Animal speaks");
}
}
class Dog extends Animal {
@Override
public void speak() {
[Link](); // Calling the superclass method
[Link]("Dog barks");
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
Dog dog = new Dog();
[Link]();
}
}
3. static Keyword Example:
Create a class Counter that uses the static keyword to count the number of instances created.
java
CopyEdit
class Counter {
static int count = 0;

public Counter() {
count++; // Static variable, shared across all instances
}

public static void displayCount() {


[Link]("Number of instances created: " + count);
}
}

public class StaticKeywordExample {


public static void main(String[] args) {
Counter c1 = new Counter ();
Counter c2 = new Counter ();
Counter c3 = new Counter ();

[Link](); // Calling static method without creating an instance


}
}
4. final Keyword Example:
Create a class MathConstants with a constant using the final keyword and demonstrate the use of
final for methods and inheritance.
class MathConstants {
public static final double PI = 3.14159; // Constant, cannot be changed

public final void displayPI() { // Final method, cannot be overridden


[Link]("Value of PI: " + PI);
}
}

class ExtendedMathConstants extends MathConstants {


// This will cause an error: Cannot override the final method from MathConstants
// public void displayPI() {
// [Link]("Overridden PI: " + PI);
// }
}

public class FinalKeywordExample {


public static void main(String[] args) {
MathConstants math = new MathConstants();
[Link](); // Accessing constant and final method
// Uncommenting below line will cause an error as the class is already final.
// ExtendedMathConstants extendedMath = new ExtendedMathConstants();
}}
List of programs: Problem Statements
1. this Keyword:
Write a class Student that has instance variables and a constructor.
Use this keyword to refer to the instance variables inside the constructor.
Create a method to display the student's details using this.
2. super Keyword:
Create a class Animal with a method speak().
Create a subclass Dog that overrides speak() and calls the superclass method using super.
Display the result in the main method.
3. static Keyword:
Write a class Counter with a static variable count.
Increment count in the constructor and display the count using a static method.
4. final Keyword:
Define a constant PI using the final keyword.
Create a method displayPI() with the final keyword.
Try overriding the method in a subclass to show how the final method works.
Demonstrate how a final class cannot be extended.

5. Create a class Book that includes a builder pattern, where you can set various attributes of the
Book (e.g., title, author, price, and year). The this keyword will be used to return the current
object (Book) from each method to allow method chaining.
Procedure:
Create a class Book with private fields: title, author, price, and year.
Implement a nested static Builder class inside Book, which will have methods for setting the
properties.
In the Builder class, use this to return the Builder object itself, enabling method chaining.
Create a constructor in the Book class that initializes the object from the Builder class.

6. Create a class hierarchy where:


A Person class has a name and age.
A Student class inherits from Person and has an additional field rollNumber.
In the Student constructor, use super to invoke the Person constructor and initialize inherited
fields.
Procedure:
Create a class Person with fields name and age and a constructor to initialize them.
Create a subclass Student that adds a rollNumber field.
Use the super () constructor in the Student constructor to initialize the Person class fields.
Override the displayDetails() method in the Student class to include rollNumber.

Conclusion: Hence we have studied how to use this, super, static and final keyword in java
programming.
Practical No.7
Aim: Write a Program to Implement Exception Handling Using User-defined Exceptions
with throw and throws Keywords in Java.
Objective:
To understand how to implement exception handling in Java using user-defined exceptions, and
to use the throw and throws keywords for explicitly throwing and declaring exceptions.
Software Requirements:
 JDK (Java Development Kit) 8 or higher
 Text Editor or IDE (Eclipse / IntelliJ IDEA / NetBeans / VS Code)
Theory:
What is Exception Handling?
Exception handling in Java is a mechanism to handle runtime errors, so that the normal flow of
the application can be maintained.
 Purpose of Exception Handling:
 The Purpose of exception handling is to be able to define the regular flow of the program
in part of the code without worrying about all the special cases. Then, in a separate block
of code, you cover the exceptional cases.
 It does the task like
– Find the problem ( Hit the exception)
– Inform that the error is encountered (Throw exception)
 Run the error handling (exception Catch) code.
 Take corrective action.
syntax of try-catch Block in Java

try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Handler for ExceptionType1
} catch (ExceptionType2 e2) {
// Handler for ExceptionType2
}
// Optional finally block
finally {
// Code that will always execute (cleanup code)
}
User-defined Exceptions or custom exceptions:
Java allows users to define their own exceptions by extending the Exception class or its subclass.
Keywords Used:
 throw: Used to explicitly throw an exception.
 throws: Declares the exceptions that a method might throw.

Example // A Class that represents user-defined exception

class MyException extends Exception {


public MyException(String m) {
super(m);
}
}

// A Class that uses the above MyException


public class setText {
public static void main(String args[]) {
try {

// Throw an object of user-defined exception


throw new MyException("This is a custom exception");
}
catch (MyException ex) {
[Link]("Caught");
[Link]([Link]());
}
}
}

Output
Caught
This is a custom exception
List of programs: Problem Statements
Problem Statement 1: Age Validation
Description:
Write a program that asks the user to enter their age. If the age is less than 18, throw a user-
defined exception AgeTooSmallException with a message "Age must be at least 18 to
register."
Objective:
 Use throw and throws.
 Create a custom exception class extending Exception.
Problem Statement 2: Bank Withdrawal Limit
Description:
Create a program to simulate a bank account withdrawal. If the withdrawal amount is greater
than the account balance, throw a user-defined exception called InsufficientFundsException.
Objective: Implement a method withdraw(double amount) that throws the custom exception.
Handle the exception in the main method.
Problem Statement 3: Student Marks Validation
Description:
Write a program to accept marks for a student. If marks are negative or greater than 100, throw a
user-defined exception called InvalidMarksException.
Objective:
 Validate input range using a custom exception.
 Apply exception handling with try-catch.

Conclusion: In this experiment, we learned how to define and use custom exceptions in Java and
how to use throw to explicitly throw an exception and throws to declare it. This enhances error
handling in user-specific scenarios.
Practical No. 8
Aim: Write a Program to Implement the Concept of Multithreading in Java
Objective:
To understand and implement the concept of multithreading in Java using both:
 Extending the Thread class
 Implementing the Runnable interface
Software Requirements:
 JDK (Java Development Kit) 8 or higher
 Text Editor or IDE (Eclipse / IntelliJ IDEA / NetBeans / VS Code)
Theory:
What is Multithreading?
Multithreading is a feature of Java that allows concurrent execution of two or more parts of a
program for maximum CPU utilization. Each part is called a thread.
Thread Creation Methods:
1. Extending the Thread class
2. Implementing the Runnable interface
Key Thread Methods:
 start(): Begins execution of the thread.
 run(): Contains the code executed by the thread.
 sleep(milliseconds): Puts the thread to sleep.
 join(): Waits for a thread to die.
Program Code:
Approach 1: Extending the Thread class
java
CopyEdit
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread 1 - Count: " + i);
try {
[Link](500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
[Link](e);
}
} }}
Approach 2: Implementing the Runnable interface
java
CopyEdit
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread 2 - Count: " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
Main Class to Run Both Threads
java
CopyEdit
public class MultithreadingDemo {
public static void main(String[] args) {
// Thread by extending Thread class
MyThread t1 = new MyThread();
[Link]();

// Thread by implementing Runnable interface


Thread t2 = new Thread(new MyRunnable());
[Link]();
}
}

Expected Output:
Thread 1 - Count: 1
Thread 2 - Count: 1
Thread 1 - Count: 2
Thread 2 - Count: 2
Thread 1 - Count: 3
Thread 2 - Count: 3
Thread 1 - Count: 4
Thread 2 - Count: 4
Thread 1 - Count: 5
Thread 2 - Count: 5
(Note: Output order may vary due to thread scheduling by the JVM.)

List of programs: Problem Statements


Problem Statement 1: Railway Reservation System
Description:
Simulate a railway ticket reservation system using multithreading. Assume there is only 1 seat
available. Create two threads representing two users trying to book the same seat
simultaneously. Ensure that only one user is able to book the seat.
Objective:
 Use synchronization to prevent race conditions.

 Implement multithreading using the Thread class.


Problem Statement 2: ATM Withdrawal Simulation
Description:
Create a program to simulate an ATM withdrawal using multithreading. Assume a shared bank
account with a balance. Multiple users (threads) try to withdraw money at the same time. Use
synchronization to ensure correct balance updates and avoid overdrafts.
Objective:
 Practice shared resource access using threads.

 Prevent inconsistent account state using synchronization.


Problem Statement 3: Online Exam System Timer
Description:
Simulate a countdown timer for an online exam using a thread. The timer counts down from 10
seconds, displaying the remaining time every second.
Objective:
 Use [Link]() to simulate real-time countdown.
 Understand basic thread execution.
Problem Statement 4: Printer Queue Simulation
Description:
Simulate a printer queue where multiple users (threads) send documents to print. Only one
document can be printed at a time. Use threads to represent each print job.
Objective:
 Implement threads to simulate print jobs.

 Use synchronization to ensure one job prints at a time.

Conclusion:
This experiment demonstrates how multithreading works in Java, enabling concurrent execution
of code for efficient CPU usage. It also shows how threads can be created and controlled using
both Thread and Runnable.
Practical No. 9
Aim: Write a Program to Demonstrate String Class Methods in Java
Objective:
To understand and use the String class methods in Java for various string operations such as
length, comparison, substring, concatenation, and character extraction.
Software Requirements:
 JDK (Java Development Kit) 8 or above
 IDE or Text Editor (e.g., Eclipse, IntelliJ, VS Code, Notepad++)
Theory:
What is a String in Java?
In Java, a String is an object that represents a sequence of characters. It is immutable, meaning
once a String object is created, it cannot be changed.
Commonly Used String Methods:

Method Description
length() Returns the length of the string
charAt(int index) Returns character at a specific index
substring(int start, int end) Returns a part of the string
equals(String s) Compares two strings for equality
equalsIgnoreCase(String s) Compares two strings ignoring case
concat(String s) Concatenates two strings
toUpperCase() / Converts case
indexOf(char ch) Returns index of first occurrence
trim() Removes leading and trailing spaces

Program Code:
public class StringMethodsDemo {
public static void main(String[] args) {
String str1 = "Hello World";
String str2 = " Java Programming ";

// 1. length()
[Link]("Length of str1: " + [Link]());

// 2. charAt()
[Link]("Character at index 4 in str1: " + [Link](4));
// 3. substring()
[Link]("Substring of str1 (0 to 5): " + [Link](0, 5));

// 4. equals()
[Link]("str1 equals 'Hello World': " + [Link]("Hello World"));

// 5. equalsIgnoreCase()
[Link]("str1 equalsIgnoreCase 'hello world': " + [Link]("hello
world"));

// 6. concat()
[Link]("Concatenated string: " + [Link]("!!!"));

// 7. toUpperCase() and toLowerCase()


[Link]("str1 in uppercase: " + [Link]());
[Link]("str1 in lowercase: " + [Link]());

// 8. indexOf()
[Link]("Index of 'W' in str1: " + [Link]('W'));

// 9. trim()
[Link]("Before trim: '" + str2 + "'");
[Link]("After trim: '" + [Link]() + "'");
}
}
Expected Output:
pgsql
CopyEdit
Length of str1: 11
Character at index 4 in str1: o
Substring of str1 (0 to 5): Hello
str1 equals 'Hello World': true
str1 equalsIgnoreCase 'hello world': true
Concatenated string: Hello World!!!
str1 in uppercase: HELLO WORLD
str1 in lowercase: hello world
Index of 'W' in str1: 6
Before trim: ' Java Programming '
After trim: 'Java Programming'

Result:
The program successfully demonstrates the use of various String class methods in Java such as
length calculation, comparison, case conversion, concatenation, substring extraction, and
trimming.
List of Programs: Problem Statement
Problem Statement 1: Student Name Validation
Description:
Write a Java program to validate a student’s name input. Perform the following checks using
String methods:
 Check if the name is not empty.
 Trim any leading or trailing spaces.
 Convert the name to proper case (first letter uppercase, rest lowercase).
 Display the processed name.
Objective:
 Use trim(), length(), substring(), and toUpperCase()/toLowerCase() methods.
Problem Statement 2: Password Strength Checker
Description:
Create a Java program that takes a password as input and checks:
 If the password length is at least 8 characters.
 If it contains a specific character (e.g., @ or #).
 If it is case-insensitive equal to a known weak password like "password".
Use appropriate String methods to perform these checks and display the result.
Objective:Use length(), contains(), and equalsIgnoreCase() methods.
Problem Statement 3: Sentence AnalyzerDescription:
Write a program that takes a sentence input from the user and performs the following:
 Print the length of the sentence.
 Display the first and last characters.
 Check if the sentence contains a specific word (e.g., "Java").
 Print a substring from position 5 to 10.
Objective:
 Use length(), charAt(), contains(), and substring() methods.

Conclusion:
This experiment helps in understanding the String class and its built-in methods, which are
essential for text processing in Java applications
Practical No. 10
Aim: Write a Program to Retrieve Data from an Employee Database using JDBC in Java
Objective:
To learn how to connect a Java program to a relational database (MySQL or any RDBMS) and
retrieve data from the Employee table using JDBC.
Software Requirements:
 JDK 8 or above

 MySQL or any other RDBMS


 MySQL JDBC Driver (Connector/J)
 Any Java IDE (Eclipse, IntelliJ, NetBeans) or text editor
 Command Line or MySQL Workbench for DB operations
Theory:
JDBC (Java Database Connectivity) is an API in Java that defines how a client may access a
database. It provides methods for querying and updating data in a database and is oriented
toward relational [Link] acts as a bridge between Java applications and various
databases, enabling Java programs to execute SQL statements, retrieve results, and propagate
changes back to the database.

JDBC Architecture:

The JDBC architecture consists of two layers:


JDBC API:
Provides interfaces and classes for writing database applications. The API lets you connect to a
database, send SQL queries, and process results.
JDBC Driver Manager:
Manages a list of database drivers.
Matches connection requests from Java applications with the appropriate driver using connection
URLs.
Components of JDBC Architecture:

Component Description
JDBC API Java interfaces and classes used by programmers
JDBC Driver Manager Loads and manages different database drivers
JDBC Drivers Vendor-specific implementations to communicate with DB
Database Actual relational database system (MySQL, Oracle, etc.)

JDBC Architecture Diagram (Conceptual):


Java Application
|
v
JDBC API ([Link] package)
|
v
JDBC Driver Manager
|
v
JDBC Driver (Vendor-specific)
|
v
Database (MySQL, Oracle, etc.)
JDBC (Java Database Connectivity) is a Java API that allows Java programs to interact with
relational databases using SQL.
Steps in JDBC Program:
1. Load the JDBC driver.
2. Establish a connection to the database.
3. Create a Statement or Prepared Statement.
4. Execute SQL query.
5. Process the result.
6. Close the connection.

Database Table: Employee


sql
CopyEdit
CREATE TABLE Employee (
id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
salary DOUBLE
);

Sample Data:
sql
CopyEdit
INSERT INTO Employee VALUES (1, 'Alice', 'HR', 50000);
INSERT INTO Employee VALUES (2, 'Bob', 'Finance', 60000);
INSERT INTO Employee VALUES (3, 'Charlie', 'IT', 75000);

Program Code (Java + JDBC):


import [Link].*;

public class RetrieveEmployeeData {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your DB
name
String user = "root"; // Replace with your DB username
String password = "your_password"; // Replace with your DB password

try {
// Load JDBC driver (optional for newer versions)
[Link]("[Link]");

// Establish connection
Connection conn = [Link](url, user, password);

// Create a statement
Statement stmt = [Link]();

// Execute SQL query


ResultSet rs = [Link]("SELECT * FROM Employee");

// Process the result


[Link]("Employee Records:");
[Link](" ");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String dept = [Link]("department");
double salary = [Link]("salary");
[Link]("ID: " + id + ", Name: " + name + ", Department: " + dept + ",
Salary: " + salary);
}

// Close connection
[Link]();
[Link]();
[Link]();

} catch (Exception e) {
[Link] ();
}
}
}

Expected Output:
yaml
CopyEdit
Employee Records:

ID: 1, Name: Alice, Department: HR, Salary: 50000.0


ID: 2, Name: Bob, Department: Finance, Salary: 60000.0
ID: 3, Name: Charlie, Department: IT, Salary: 75000.0

Result:
The program successfully connects to the database and retrieves all records from the Employee
table using JDBC.
List of Programs: Problem Statements
Problem Statement 1: Retrieve Employee Details by Department
Description:
Write a Java program using JDBC to retrieve and display all employee records who belong to a
specific department (e.g., "IT"). The department name should be taken as input from the user.
Objective:
Use PreparedStatement to safely query data based on user input.
Display employee details filtered by department.

Conclusion:
This experiment demonstrates how to use JDBC to retrieve data from a MySQL database in
Java. It highlights the basic steps of database connectivity, querying, and result processing.

You might also like