Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views38 pages

Java Lab Manual (2025)

The document outlines various Java programming laboratory exercises for the academic year 2025-2026, including applications for generating electricity bills, employee pay slips, word frequency counts, and abstract class implementations. Each exercise provides an aim, algorithm, program code, and sample output. The exercises are designed to enhance students' understanding of Java programming concepts and practical applications.
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)
8 views38 pages

Java Lab Manual (2025)

The document outlines various Java programming laboratory exercises for the academic year 2025-2026, including applications for generating electricity bills, employee pay slips, word frequency counts, and abstract class implementations. Each exercise provides an aim, algorithm, program code, and sample output. The exercises are designed to enhance students' understanding of Java programming concepts and practical applications.
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/ 38

IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No: 1 Java Application to Generate Electricity Bill


Date:

AIM:
To develop a java application to generate electricity bill.

ALOGITHM
1:Start the program.
2:Declare a class and include options to calculate if the bill is to be calculated for domestic use
or commercial use.
3:For domestic use,calculate the bill as follows as:
3.1 if the units are less than 100,then billpay=units*1.00.
3.2 if the units are less than 200,then billpay=100*1.00+(units-100)*2.50.
3.3 if the units are less than 500,then billpay= 100*1.00 + 100*2.50 + (units - 200)*4
3.4 if the units are greater than 500,then billpay= 100*1.00 + 100*2.50 + 300*4 + (units -
500)*6
4:For commercial use,calculate the bill as follows:
4.1 if the units are less than 100,then billpay=units*2.00.
4.2 if the units are less than 200,then billpay=100*2.00+(units-100)*4.50.
4.3 if the units are less than 500,then billpay= 100 * 2.00 + 100 * 4.50 + (units - 200) * 6
4.4 if the units are greater than 500,then billpay=
100 * 2.00 + 100 * 4.50 + 300 * 6 + (units - 500) * 7
5:Print the electricity bill.
6:Stop the program.

PROGRAM
import java.util.Scanner;

class EBILL {
static int consumerno, pmr, cmr;
static String consumername;

public static void details() {


Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the consumer number: ");
consumerno = scan.nextInt();
System.out.print("Enter the consumer name: ");
consumername = scan.next();
System.out.print("Enter the previous month reading: ");
pmr = scan.nextInt();
System.out.print("Enter the current month reading: ");
cmr = scan.nextInt();
}

public static void domestic() {


int units = cmr - pmr;
double total = 0;

1
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

System.out.println("\nYou are a Domestic user.");


System.out.println("Units Consumed: " + units);

if (units <= 100) {


total = units * 1.00;
} else if (units <= 200) {
total = 100 * 1.00 + (units - 100) * 2.50;
} else if (units <= 500) {
total = 100 * 1.00 + 100 * 2.50 + (units - 200) * 4.00;
} else {
total = 100 * 1.00 + 100 * 2.50 + 300 * 4.00 + (units - 500) * 6.00;
}

System.out.println("Your Electricity Bill: ₹" + total);


}

public static void commercial() {


int units = cmr - pmr;
double total = 0;
System.out.println("\nYou are a Commercial user.");
System.out.println("Units Consumed: " + units);

if (units <= 100) {


total = units * 2.00;
} else if (units <= 200) {
total = 100 * 2.00 + (units - 100) * 4.50;
} else if (units <= 500) {
total = 100 * 2.00 + 100 * 4.50 + (units - 200) * 6.00;
} else {
total = 100 * 2.00 + 100 * 4.50 + 300 * 6.00 + (units - 500) * 7.00;
}

System.out.println("Your Electricity Bill: ₹" + total);


}
public static void main(String[] args) {
int choice, type;
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("\nElectricity Bill Generation System");
System.out.print("1. Generate Bill\n2. Exit\nEnter your choice: ");
choice = scan.nextInt();

if (choice == 1) {
details();
System.out.print("Select Connection Type:\n1. Domestic\n2. Commercial\nEnter
your choice: ");
type = scan.nextInt();

2
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

if (type == 1) {
domestic();
} else if (type == 2) {
commercial();
} else {
System.out.println("Invalid connection type selected.");
}
} else if (choice == 2) {
System.out.println("Exiting... Thank you!");
break;
} else {
System.out.println("Invalid menu choice. Try again.");
}
}
}
}
OUTPUT
Electricity bill generation
Please enter your choice
1.Generate electricity bill
2.exit ::: 1
Enter the consumer no ::: 102
Enter the consumer name ::: mani
Enter the previos month reading ::: 0
Enter the current month reading ::: 100
Select your EB connection
1.Domestic
2.Commercial ::: 1
You are a Domestic user
Your Electricity Bill ::: 100

Electricity bill generation


Please enter your choice
1.Generate electricity bill
2.exit ::: 1
Enter the consumer no ::: 201
Enter the consumer name ::: suresh
Enter the previos month reading ::: 0
Enter the current month reading ::: 100
Select your EB connection
1.Domestic
2.Commercial ::: 2
You are a Commercial user
Your Electricity Bill ::: 200

RESULT:

3
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:2 Develop Java applications to generate Pay slip for an employee


Date:

AIM:
To write a JAVA program to calculate the pay slips of the employee.
Algorithm:
1: Start the program.
2: Create a class employee and get the name,address,employeeid,mailed,mobile number from
the user.
3: Create a class called programmer and extend the class employee.Calculate the gross salary
and net salary of the programmer.
4: Create a class called assistant professor and extend the class employee.Calculate the gross
salary and net salary of the assistant professor.
5: Create a class called associate professor and extend the class employee.Calculate the gross
salary and net salary of the associate professor.
6: Create a class called professor and extend the class employee.Calculate the gross salary and
net salary of the professor.
7: Print the gross payslip and net payslip of the employees.
8: Stop the program.

PROGRAM:
import java.util.Scanner;

// Base Class
class Employee {
String empName, empId, address, mailId, mobileNo;

void getDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Name: ");
empName = sc.nextLine();
System.out.print("Enter Employee ID: ");
empId = sc.nextLine();
System.out.print("Enter Address: ");
address = sc.nextLine();
System.out.print("Enter Mail ID: ");
mailId = sc.nextLine();
System.out.print("Enter Mobile Number: ");
mobileNo = sc.nextLine();
}

void displayDetails() {
System.out.println("\n----- Employee Details -----");
System.out.println("Name : " + empName);
System.out.println("ID : " + empId);
System.out.println("Address : " + address);
System.out.println("Mail ID : " + mailId);

4
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

System.out.println("Mobile No : " + mobileNo);


}
}

// Inherited class for common salary structure


class Salary extends Employee {
double basicPay, DA, HRA, PF, staffClub, grossSalary, netSalary;

void calculateSalary() {
DA = 0.97 * basicPay;
HRA = 0.10 * basicPay;
PF = 0.12 * basicPay;
staffClub = 0.001 * basicPay;

grossSalary = basicPay + DA + HRA;


netSalary = grossSalary - (PF + staffClub);
}

void generatePaySlip() {
displayDetails();
System.out.println("Basic Pay : ₹" + basicPay);
System.out.println("DA (97%) : ₹" + DA);
System.out.println("HRA (10%) : ₹" + HRA);
System.out.println("PF (12%) : ₹" + PF);
System.out.println("Staff Club (0.1%): ₹" + staffClub);
System.out.println("Gross Salary : ₹" + grossSalary);
System.out.println("Net Salary : ₹" + netSalary);
}
}

// Subclasses
class Programmer extends Salary {
void input() {
getDetails();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Basic Pay for Programmer: ₹");
basicPay = sc.nextDouble();
calculateSalary();
}
}

class AssistantProfessor extends Salary {


void input() {
getDetails();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Basic Pay for Assistant Professor: ₹");
basicPay = sc.nextDouble();

5
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

calculateSalary();
}
}

class AssociateProfessor extends Salary {


void input() {
getDetails();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Basic Pay for Associate Professor: ₹");
basicPay = sc.nextDouble();
calculateSalary();
}
}

class Professor extends Salary {


void input() {
getDetails();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Basic Pay for Professor: ₹");
basicPay = sc.nextDouble();
calculateSalary();
}
}

public class EmployeeSalaryApp {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice;

do {
System.out.println("\n--- Employee Payroll Menu ---");
System.out.println("1. Programmer");
System.out.println("2. Assistant Professor");
System.out.println("3. Associate Professor");
System.out.println("4. Professor");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();

switch(choice) {
case 1:
Programmer prog = new Programmer();
prog.input();
prog.generatePaySlip();
break;
case 2:
AssistantProfessor asst = new AssistantProfessor();

6
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

asst.input();
asst.generatePaySlip();
break;
case 3:
AssociateProfessor assoc = new AssociateProfessor();
assoc.input();
assoc.generatePaySlip();
break;
case 4:
Professor prof = new Professor();
prof.input();
prof.generatePaySlip();
break;
case 5:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Try again.");
}

} while (choice != 5);


}
}

OUTPUT:

--- Employee Payroll Menu ---


1. Programmer
2. Assistant Professor
3. Associate Professor
4. Professor
5. Exit

Enter your choice: 1

Enter Employee Name: Ravi


Enter Employee ID: E123
Enter Address: Chennai
Enter Mail ID: [email protected]
Enter Mobile Number: 9876543210
Enter Basic Pay for Programmer: ₹50000

----- Employee Details -----


Name : Ravi
ID : E123
Address : Chennai

7
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Mail ID : [email protected]
Mobile No : 9876543210
Basic Pay : ₹50000.0
DA (97%) : ₹48500.0
HRA (10%) : ₹5000.0
PF (12%) : ₹6000.0
Staff Club (0.1%): ₹50.0
Gross Salary : ₹103500.0
Net Salary : ₹97450.0

--- Employee Payroll Menu ---


1. Programmer
2. Assistant Professor
3. Associate Professor
4. Professor
5. Exit

Enter your choice: 5

RESULT:

8
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:3 Frequency count of words in a given text


Date:
AIM
To write java program for finding frequency count of words in a given text.

ALGORITHIM
1. Start
2. Accept a sentence from the user.
3. Extract a Word.
4. Count the no. of times it occurs in the sentence.
5. Print its frequency.
6. Repeat Steps 3 to 6 till all the frequencies are printed.
7. End

PROGRAM
import java.util.Scanner;

public class WordCountSimple {


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

// Get input
System.out.println("Enter a sentence:");
String text = sc.nextLine();

// Split into words


String[] words = text.split(" ");

// Count frequency
for (int i = 0; i < words.length; i++) {
if (words[i].equals("")) continue; // skip empty
int count = 1;
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
count++;
words[j] = ""; // mark as counted
}
}
if (!words[i].equals("")) {
System.out.println(words[i] + " : " + count);
}
}
}
}

9
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Output:
Enter a sentence:
hello world hello java world hello

hello : 3
world : 2
java : 1

RESULT:

10
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No: 4 Java Program to create Abstract class implementation


Date:

AIM
To write java program for creating abstract class implementation.

ALGORITHIM
1. Start
2. Create shape abstract class with print area as member function to print triangle,
rectangle and circle area.
3. Inherit the abstract class to define abstract method in the new class.
a. Create rectangle class and define abstract method to calculate area
b. Create triangle class and define abstract method to calculate area
c. Create circle class and define abstract method to calculate area
4. Create main class to get user input base, height and radius for rectangle, triangle and
circle.
5. Create rectangle, triangle, and circle objects to call respective defined function and pass
user inputs.
6. Stop

PROGRAM
abstract class Shape
{
int a=3,b=4;
abstract public void print_area();
}
class Rectangle extends Shape
{
public int area_rect;

public void print_area()


{
area_rect=a*b;
System.out.println("The area of rectangle is:"+area_rect);
}
}
class Triangle extends Shape
{
public double area_tri;

public void print_area()


{
area_tri=0.5*a*b;
System.out.println("The area of rectangle is:"+area_tri);
}
}

11
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

class Circle extends Shape


{
public double area_cir;

public void print_area()


{
area_cir=3.14*a*a;
System.out.println("The area of rectangle is:"+area_cir);
}
}
public class Demo
{
public static void main(String arg[])
{
Shape s;
s=new Rectangle();
s. print_area();
s=new Triangle();
s.print_area();
s=new Circle();
s.print_area();
}
}

Output:
The area of rectangle is:12
The area of triangle is:6
The area of circle is:28

RESULT:

12
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No: 5 Design java interface for ADT stack with proper exception handling
Date:

AIM
To design java interface for ADT stack with proper exception handling.

ALGORITHIM

1. Start
2. Create interface for stack operations(push, pop & display).
3. Create stack to insert, delete and display items.
4. Create stack implementation with
a. Push method to pushes an element to the stack.
b. POP method to remove an element top from stack.
c. Display method to view all elements in stack.
5. Stop

PROGRAM
import java.io.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else {
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
} }
catch(IOException e) {
System.out.println("e");

13
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

} }
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else {
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}}
public void display() {
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else {
String str=" ";
for(int i=0; i<=top; i++)
{str=str+stack[i]+" <--";}
System.out.println("Elements are:"+str);
}}}
class StackADT {
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do {
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch) {
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:

14
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

System.exit(0);
}}
while(ch<5);
}}

OUTPUT
Implementation of Stack using Array
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
23
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
34
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
45
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: Â 23  34 <-- 45 <--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped element:45
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: 23 <-- 34 <--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped element:34
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: 23 <--
1.Push 2.Pop 3.Display 4.Exit

RESULT:

15
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No: 6 Java Program to create Abstract class implementation


Date:

AIM
To write java program for creating abstract class implementation.

ALGORITHIM
1. Start
2. Create shape abstract class with print area as member function to print triangle,
rectangle and circle area.
3. Inherit the abstract class to define abstract method in the new class.
a. Create rectangle class and define abstract method to calculate area
b. Create triangle class and define abstract method to calculate area
c. Create circle class and define abstract method to calculate area
4. Create main class to get user input base, height and radius for rectangle, triangle and
circle.
5. Create rectangle, triangle, and circle objects to call respective defined function and pass
user inputs.
6. Stop

PROGRAM
Shape.java (save in pack1)

package pack1;
public abstract class Shape
{
Public int a=3,b=4;
abstract public void print_area();
}

Rectangle.java
package pack1;
class Rectangle extends Shape
{
public double area_rect;

public void print_area()


{
area_rect=a*b;
System.out.println("The area of rectangle is:"+area_rect);
}
}

Triangle.java:
package pack1;
class Triangle extends Shape
{

16
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

public double area_tri;

public void print_area()


{
area_tri=0.5*a*b;
System.out.println("The area of rectangle is:"+area_tri);
}
}

Circle.java
package pack1;
class Circle extends Shape
{
public int area_cir;

public void print_area()


{
area_cir=3.14*a*a;
System.out.println("The area of rectangle is:"+area_cir);
}
}

Demo.java(save in pack2)
package pack2;
import pack1.*;
public class Demo
{
public static void main(String arg[])
{
Shape s;
s=new Rectangle();
s. print_area();
s=new Triangle();
s.print_area();
s=new Circle();
s.print_area();
}}
Output:
Javac pack1/*.java pack2/Demo.java
Java Demo
The area of rectangle is:12
The area of triangle is:6
The area of circle is:28

RESULT:

17
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No: 7 Java program to implement user defined exception


Date:

Aim:
To write a JAVA program to implement user defined exception.

Algorithm:
1: Start the program.
2: Create a class called as MyException and extend Exception class.
4. Create a constructor and receive the value from main class
5: In MainException class create user defined exception and throw our own exception
6: Print the exception message.
7: Stop the program.

Program:
Package Exceptionhandling;
class MyException extends Exception{
String str1;

MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}

class MainException{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
} }}

Output:
Starting of try block
Catch Block
MyException Occurred: This is My error Message.

RESULT:

18
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex no 8: To find the maximum value from the given type of elements using a generic
function.
Date:
AIM:
Write a java program to find the maximum value from the given type of elements using a
generic function.
ALGORITHM:
1. Start
2. Create a arraylist in integer type
3. Using scanner get the collection numbers from the user.
4. Get the digits using add() inside the for loop
5. Assign the first digit to the variable max using get()
6. Iterate the loop till to get maximum value
7. Stop.

PROGRAM
package exp3;
import java.util.ArrayList;
import java.util.Scanner;
public class LargestInArrayList
{
public static void main(String[] args)
{
int n;
ArrayList<Integer> L = new ArrayList<Integer>();
int max;
Scanner in = new Scanner(System.in); System.out.println("Enter Size of Array List");
n = in.nextInt();
System.out.println("Enter elements in Array List");
for (int i = 0; i < n; i++)
{L.add(in.nextInt());}
max = L.get(0);
for (int i = 0; i < L.size(); i++)
{ if (L.get(i) > max) {
max = L.get(i);
}}
System.out.println("Max Element: " + max); in.close(); }}
OUTPUT:
Enter Size of Array List 5
Enter elements in Array List 2
6
3
8
1
Max Element: 8
RESULT:

19
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex No:9 String handling Functions


Date:
AIM:
To write a program in Java for String handling which performs the following: i) Checks the
capacity of StringBuffer objects. ii) Reverses the contents of a string given on console and
converts the resultant string in upper case. iii) Reads a string from console and appends it to the
resultant string of ii.

ALGORITHM:
Step 1:Start the Program.
Step 2:Get an input string from the user.
Step 3: Check the capacity of the StringBuffer object.
Step 4:Perform operations to reverse the contents of a string given on console and convert the
resultant string in upper case.
Step 5: Read a string from console and append it to the output string. Step 6:Stop the Program.

PROGRAM:
import java.io.*;
class StringHandler
{
public static void main(String s[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1,s2,s3,s4,s5;
int i,l; s2=" ";
System.out.println("\nEnter the string : \t\t\t");
System.out.println("\n=======================\t");
s1=br.readLine();
System.out.println("\nEntered string is : \t\t\t "+s1);
System.out.println("\nlength of the string is : \t\t "+s1.length());
StringBuffer sb=new StringBuffer(s1);
System.out.println("\nCapacity of string buffer : \t\t "+sb.capacity());
l=s1.length();
if(l==0)
System.out.println("\nString is empty cannot be reversed");
else
{
for(i=l-1;i>=0;i--)
{
s2=s2+s1.charAt(i);
}
System.out.println("\nThe reversed string is : \t\t"+s2);
s3=s2.toUpperCase();
System.out.println("\nUpper case of reverse string is : \t"+s3);
System.out.println("\nEnter a new string : \t");

20
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

System.out.println("\n=======================\t");
s4=br.readLine();
System.out.println("\nThe entered new string is : \t\t "+s4);
StringBuffer sb1=new StringBuffer(s4);
s5=sb1.append(s3).toString();
System.out.println("\nThe appended string is : \t\t "+s5);
}
}
}

OUTPUT:
Enter the string :======================= TODAY IS A HAPPY DAY
Entered string is : TODAY IS A HAPPY DAYlength of the string is : 20
Capacity of string buffer : 36
The reversed string is : YAD YPPAH A SI YADOT
Upper case of reverse string is : YAD YPPAH A SI YADOT
Enter a new string :======================= TODAY IS A GREAT EVENING
The entered new string is : TODAY IS A GREAT EVENING
The appended string is : TODAY IS A GREAT EVENING YAD YPPAH A SI YADOT

RESULT:

21
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex No: 10 String operation using ArrayList


Date:
AIM
To write a program to perform string operation using ArrayList.Write function for the following
:a.Append-add at end ,b. Insert-add at particular index,c. Search,d. List all string starts with
given letter

ALGORITHM
Step 1:Start the program
Step 2:Initialize the arraylist along with the relevant datatype.
Step 3:Perform append operation for the arraylist.
Step 4:Perform insert operation for the arraylist
Step 5:Perform search operation for the arraylist.
Step 6:Stop the program.

PROGRAM
package stringoperation;
import java.util.Scanner;
import java.util.ArrayList;
class stropr {
private static ArrayList<String> var = new ArrayList<>();
private static Scanner scan = new Scanner(System.in);
private static void append() {
System.out.print("Enter the string to append: ");
String str = scan.next();
var.add(str);
System.out.println("Appended successfully!!!!!!");
}
private static void add() {
{
System.out.print("Enter the String to add: ");
String str = scan.next();
System.out.print("Enter the index of the string: ");
int i = scan.nextInt();
var.add(i,str);
System.out.println("Added successfuly!!!!!!");
}
}
private static void search() {
System.out.print("Enter the string to search for: ");
String str = scan.next();
int no = var.indexOf(str);
System.out.println("Found in index " + no);
}
private static void find()
{ System.out.print("Enter the first letter: ");

22
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

String ch = scan.next();
//System.out.print(ch);
for(String a : var) {
//System.out.print(" " + a.substring(0,1));
if(a.substring(0,ch.length()).equals(ch))
System.out.println(a);
}
}
private static void display()
{ for(String a : var)
System.out.println(a);
}
public static void main(String[] args)
{
int ch;
try
{
do {
System.out.println("\n\n1.Append\n2.add\n3.search\n4.find\n5.display\n6.exit");
System.out.print("Enter your choice: ");
ch = scan.nextInt();
switch(ch) {
case 1:
append();
break;

case 2:
add();
break;

case 3:
search();
break;

case 4:
find();
break;

case 5:
display();
break;

case 6:
System.exit(0);
break;

23
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

}
}while(true);
}

default:
System.out.println("Invalid Input"); break;

catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit


Enter your choice: 2
Enter the String to add: mani Enter the index of the string: 0 Added successfuly!!!!!!

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit


Enter your choice: 2

Enter the String to add: itstaff Enter the index of the string: 1 Added successfuly!!!!!!

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit


Enter your choice: 2
Enter the String to add: java Enter the index of the string: 2 Added successfuly!!!!!!

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit


Enter your choice: 1
Enter the string to append: teaching Appended successfully!!!!!!

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit

24
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Enter your choice: 5 mani


itstaff java teaching

MAIN MENU

1.Append 2.add 3.search 4.find 5.display

6.exit
Enter your choice: 3
Enter the string to search for: mani Found in index 0

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit


Enter your choice: 4 Enter the first letter: i itstaff

MAIN MENU

1.Append 2.add 3.search 4.find 5.display 6.exit

RESULT:

25
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:11 Java Program Using File Concept


Date:
AIM:
Write a JAVA program that reads the name from the user, displays information about
whether the file exists, whether the file is readable or writable, the type of file and length of the
file in bytes

ALGORITHM:
1. Start
2. Using scanner class get user’s file name
3. Pass the file name to the file class object F1.
4. F1.getname() used to get the name of the file.
5. F1.getpath() used to get tha path of the file.
6. F1.exists() used to find the file exists or not.
7. F1.canRead() used to find the file is in readable mode or not.
8. F1. Length() used to find the length of the file.
9. Stop.

PROGRAM
import java.util.Scanner;
import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String s=input.nextLine();
File f1=new File(s);
System.out.println("File Name:"+f1.getName());
System.out.println("Path:"+f1.getPath());
System.out.println("Abs Path:"+f1.getAbsolutePath());
//System.out.println("Parent:"+f1.getParent());
System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));
System.out.println("Is file:"+f1.isFile());
//System.out.println("Is Directory:"+f1.isDirectory());
System.out.println("Is Readable:"+f1.canRead());
System.out.println("IS Writable:"+f1.canWrite());
//System.out.println("Is Absolute:"+f1.isAbsolute());
//System.out.println("File Last Modified:"+f1.lastModified());
System.out.println("File Size:"+f1.length()+"bytes");
System.out.println("Is Hidden:"+f1.isHidden());
}
}

26
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

OUTPUT

a.txt
File Name:a.txt
Path:a.txt
Abs Path:C:\Users\MANIKANDAN\Documents\NetBeansProjects\Javalab\a.txt
This file is:Exists
Is file:true
Is Readable:true
IS Writable:false
File Size:13bytes
Is Hidden:false

RESULT:

27
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:12 Java Program for Multithreaded implementations


Date:

AIM
To create java program for multithreaded implementations.

ALGORITHM:
1. Start
2. Create thread by extending thread class
a. Implement run method for the following.
b. First thread displays “Good Morning” every one second, the second thread
displays “Hello” every two seconds and the third thread displays “Welcome”
every three seconds..
3. Start thread in the main class constructor.
4. Stop
PROGRAM
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{}

28
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{}
}
}
class Main
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
OUTPUT

good morning
good morning
hello
good morning
welcome
good morning
hello
good morning
welcome
hello
good morning
good morning
hello
good morning

29
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

welcome
good morning
hello
good morning
good morning
hello
welcome
good morning

RESULT:

30
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:13 GUI Window operations in java


Date:

AIM:
To perform Window operations in java with various components.

ALGORITHM
1. Start
2. To create a window when we press M or m the window displays Good Morning,
3. To create a window when we press A or a the window displays Good After Noon
4. To create a window when we press E or e the window displays Good Evening
5. To create a window when we press N or n the window displays Good Night
6. Stop

PROGRAM:

import java.awt.*;
import java.util.*;
public class Testawt{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Character: ");
char ch = sc.next().charAt(0);
Frame fm=new Frame();
Label lb = new Label();
if(ch=='M'|| ch=='m')
{
lb.setText("GoodMorning);
}
else if(ch=='A'|| ch=='a')
{
lb.setText("Good Afternoon");
}
else if(ch=='E'|| ch=='e')
{
lb.setText("Good Evening");
}
else if(ch=='N'|| ch=='n')
{
lb.setText("Good Night");
}
fm.add(lb);
fm.setSize(300, 300);
fm.setVisible(true);
}

31
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

}
OUTPUT:
Enter a Character: m

RESULT:

32
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:14 Create a GUI program in java


Date:

AIM:
To Create a GUI program in java with various components.

ALGORITHM
1. Start
2. A frame with Flow layout.
3. Add the following components on to the frame.
i. Two Text Field
ii. A button with the label display
4. Allow the user to enter data into the JTextField
5. When the button is clicked paint the frame by displaying the data entered in the
JTextField
6. Allow the user to properly close the frame
7. Stop

PROGRAM:

import java.awt.event.*;
import javax.swing.*;
class Swing1 extends JFrame implements ActionListener {
// JTextField
static JTextField t,q;
// JFrame
static JFrame f;
// JButton
static JButton b;
// label to display text
static JLabel l;
// default constructor
Swing1()
{
}
// main class

33
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

public static void main(String[] args)


{
// create a new frame to store text field and button
f = new JFrame("textfield");
// create a label to display text
l = new JLabel("nothing entered");
// create a new button
b = new JButton("Display");
// create a object of the text class
Swing1 te = new Swing1();
// addActionListener to button
b.addActionListener(te);
// create a object of JTextField with 16 columns and a given initial text
t = new JTextField("enter the text", 16);
q=new JTextField("Sentence Matching", 16);
// create a panel to add buttons and textfield
JPanel p = new JPanel();
// add buttons and textfield to panel
p.add(t);
p.add(b);
p.add(l);
p.add(q);
// add panel to frame
f.add(p);
// set the size of frame
f.setSize(300, 300);
f.show();
}

34
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

// if the button is pressed


public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("Display")) {
// set the text of the label to the text of the field
l.setText(t.getText());
// set the text of field to blank
t.setText(" ");
}
}
}
Output:

RESULT:

35
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

Ex.No:15 Design and Develop the GUI application with database connectivity of your
choice
Date:
AIM:
To design and develop the GUI application with database connectivity of your choice.
Algorithm:

1. Create a database and table in mysql


2. Use swing components create a student registration form
3. Add libraries with mysql connector jar iles
4. Establish connectivity
5. Insert values
6. Show the result

PROGRAM:

Database Setup (MySQL):


SQL Code:
CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
department VARCHAR(100)
);

2. Java Code with GUI + JDBC:


Make sure you have the MySQL JDBC driver (mysql-connector-j.jar) in your classpath.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class StudentRegistrationForm extends JFrame {


JTextField nameField, emailField, deptField;
JButton submitButton;

public StudentRegistrationForm() {
setTitle("Student Registration");
setLayout(new GridLayout(4, 2, 10, 10));

// Form Labels and Fields


add(new JLabel("Name:"));

36
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

nameField = new JTextField();


add(nameField);

add(new JLabel("Email:"));
emailField = new JTextField();
add(emailField);

add(new JLabel("Department:"));
deptField = new JTextField();
add(deptField);

// Submit Button
submitButton = new JButton("Register");
add(submitButton);

submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
insertData();
}
});

setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

void insertData() {
String name = nameField.getText();
String email = emailField.getText();
String dept = deptField.getText();

try {
// Connect to DB
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb", "root", "yourpassword");

// Prepare SQL
String query = "INSERT INTO students (name, email, department) VALUES (?, ?, ?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, name);
pst.setString(2, email);
pst.setString(3, dept);

// Execute
int i = pst.executeUpdate();
if (i > 0) {

37
IT1308-Java programming Laboratory Department of CSE (Cyber Security) 2025-2026

JOptionPane.showMessageDialog(this, "Student Registered Successfully!");


nameField.setText("");
emailField.setText("");
deptField.setText("");
}

con.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}

public static void main(String[] args) {


new StudentRegistrationForm();
}
}

OUTPUT:

RESULT:

38

You might also like