Java Labmanual
Java Labmanual
Sambhajinagar
Jawaharlal Nehru Engineering College
LAB MANUAL
Program (UG/PG) : UG
Year : Third Year
Semester : V
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.
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.
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.
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.
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.
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.
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.
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
11 Mini project
Practical No: 1
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.
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.
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
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
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
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
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
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.
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
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
// Constructor
public Student(String name, int age) {
[Link] = name; // 'this' refers to the current object's instance variable
[Link] = age;
}
public Counter() {
count++; // Static variable, shared across all instances
}
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.
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.
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]();
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.)
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]("!!!"));
// 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
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.)
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);
try {
// Load JDBC driver (optional for newer versions)
[Link]("[Link]");
// Establish connection
Connection conn = [Link](url, user, password);
// Create a statement
Statement stmt = [Link]();
// Close connection
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link] ();
}
}
}
Expected Output:
yaml
CopyEdit
Employee Records:
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.