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

Java Lab Manual (1)

The document outlines a series of Java programming laboratory exercises for the academic year 2022-2023, including applications for generating electricity bills, employee pay slips, word frequency counts, and abstract class implementations. Each exercise includes an aim, algorithm, program code, and sample outputs. The focus is on practical applications of Java programming concepts in various scenarios.

Uploaded by

arunprasadm8
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 views41 pages

Java Lab Manual (1)

The document outlines a series of Java programming laboratory exercises for the academic year 2022-2023, including applications for generating electricity bills, employee pay slips, word frequency counts, and abstract class implementations. Each exercise includes an aim, algorithm, program code, and sample outputs. The focus is on practical applications of Java programming concepts in various scenarios.

Uploaded by

arunprasadm8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

IT1308-Java programming Laboratory Department of IT 2022-2023

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+200*2.50+(units-300)*4
3.4 if the units are greater than 501,then billpay=100*1.00+200 *2.50+(units-501)*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*1.00+200*2.50+(units-300)*6
4.4 if the units are greater than 501,then billpay=100*1.00+200 *2.50+(units-501)*7.
5:Print the electricity bill.
6:Stop the program.

PROGRAM
package EBbill;
import java.util.Scanner;
class EBILL
{
static int consumerno,pmr,cmr,type;
static String consumername;
//pmr = Previous month reading cmr = Current month reading type = type of connection(i.e
domestic or commercial)

public static void details()


{
EBILL e = new EBILL();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the consumer no ::: ");
consumerno = scan.nextInt();
System.out.print("\nEnter the consumer name ::: ");
consumername = scan.next();
System.out.print("\nEnter the previos month reading ::: ");
pmr = scan.nextInt();
System.out.print("\n Enter the current month reading ::: ");
cmr = scan.nextInt();
}
public static void domestic()

1
IT1308-Java programming Laboratory Department of IT 2022-2023

{
double total = 0;
System.out.print("\n\nYou are a Domestic user");
if(cmr <= 100)
{
System.out.print("\n\nYour Electricity Bill ::: "+cmr);
return;
}
if(cmr>100)
{
cmr = cmr -100;
total = total + 100 * 1;
if(cmr>100)
{
cmr = cmr -100;
total = total + (100 * 2.5) ;
if(cmr>300)
{
cmr = cmr - 300;
total = total + 300 * 4;
total = total + cmr * 6;
}
else
{
total = total + cmr * 4;
}
}
else
{
total = total + cmr * 2.5;
}
}
System.out.print("\nYour Electricity Bill ::: "+total+" Rupees");
}
public static void commercial()
{
double total = 0;
System.out.print("\nYou are a Commercial user ");
if(cmr <= 100)
{
System.out.print("\nYour Electricity Bill ::: "+cmr*2);
return;
}
if(cmr>100)
{
cmr = cmr -100;
total = total + 100 * 2;

2
IT1308-Java programming Laboratory Department of IT 2022-2023

if(cmr>100)
{
cmr = cmr -100;
total = total + (100 * 4.5) ;
if(cmr>300)
{
cmr = cmr - 300;
total = total + 300 * 6;
total = total + cmr * 7;
}
else
{
total = total + cmr * 6;
}
}
else
{
total = total + cmr * 4.5;
}
}
System.out.print("\nYour Electricity Bill ::: "+total+" Rupees");
}
public static void main(String args[])
{
int ch,c;
int r = 1;
Scanner scan = new Scanner(System.in);
while(r == 1)
{
System.out.print("\n\n Electricity bill generation");
System.out.print("\n Please enter your choice");
System.out.print("\n1.Generate electricity bill\n2.exit ::: ");
c = scan.nextInt();
switch(c)
{
case 1:
details();
System.out.print("\nSelect your EB connection");
System.out.print("\n1.Domestic\n2.Commercial ::: ");
ch = scan.nextInt();

if(ch == 1)
{
domestic();
}
else if(ch == 2)
{

3
IT1308-Java programming Laboratory Department of IT 2022-2023

commercial();
}
else
{
System.out.print("Enter the correct details");
}
break;
case 2:
r = 0;
break;
default:
System.out.print("Enter the correct choice");
}
} }}

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:

4
IT1308-Java programming Laboratory Department of IT 2022-2023

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:
package emp;
class Employee
{
Double mobno;
String name, address,eid,mailid;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
name = get.nextLine();
System.out.println("Enter the ID of the Employee:");
eid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter mail id of the Employee:");
mailid = get.nextLine();
System.out.println("Enter the mobile no:");
mobno= get.nextDouble ();
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("EmployeeID: "+eid);

System.out.println("Address: "+address);
System.out.println("MailID: "+mailid);

5
IT1308-Java programming Laboratory Department of IT 2022-2023

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


}
}
class programmer extends Employee
{
double bp,rate,net;
String des;
programmer()
{
System.out.println("Enter basic pay:");
bp= get.nextFloat();
}
void calculatepayprog()
{
rate = bp+(0.97*bp)+(0.01*bp)+(0.12*bp)+(.001*bp);
net=rate-(0.12*bp);
}
void display()
{
System.out.println("=============================="+"\n"+"Programmer
Details"+"\n"+"=============================="+"\n");
super.display();
System.out.println("Gross Salary: "+rate);
System.out.println("Net Salary: "+net);
}
}
class assistantprofessor extends Employee
{
double bp1,rate1,net1;
String des1;
assistantprofessor()
{
//System.out.println("Enter Designation:");
//des1 = get.nextLine();
System.out.println("Enter basic pay:");
bp1= get.nextFloat();
}
void calculatepay1()
{
rate1 = bp1+(0.97*bp1)+(0.01*bp1)+(0.12*bp1)+(.001*bp1);
net1=rate1-(0.12*bp1);
}

void display()
{
System.out.println("=============================="+"\n"+"Assistant Professor
Details"+"\n"+"=============================="+"\n");

6
IT1308-Java programming Laboratory Department of IT 2022-2023

super.display();
System.out.println("Gross Salary: "+rate1);
System.out.println("Net Salary "+net1);
}
}
class associateprofessor extends Employee
{
double bp2,rate2,net2;
String des2;
associateprofessor()
{
System.out.println("Enter basic pay:");
bp2= get.nextFloat();
}
void calculatepay2()
{
rate2 = bp2+(0.97*bp2)+(0.01*bp2)+(0.12*bp2)+(.001*bp2);
net2=rate2-(0.12*bp2);
}
void display()
{
System.out.println("=============================="+"\n"+"Associate Professor
Details"+"\n"+"=============================="+"\n");
super.display();
System.out.println("Gross Salary: "+rate2);
System.out.println("Net Salary "+net2);
}}
class professor extends Employee
{
double bp3,rate3,net3;
String des3;
professor()
{
//System.out.println("Enter Designation:");
//des1 = get.nextLine();
System.out.println("Enter basic pay:");
bp3= get.nextFloat();
}
void calculatepay3()
{
rate3 = bp3+(0.97*bp3)+(0.01*bp3)+(0.12*bp3)+(.001*bp3);
net3=rate3-(0.12*bp3);
}
void display()
{
System.out.println("=============================="+"\n"+"Professor
Details"+"\n"+"=============================="+"\n");

7
IT1308-Java programming Laboratory Department of IT 2022-2023

super.display();
System.out.println("Gross Salary: "+rate3);
System.out.println("Net Salary "+net3);
}}
class salary
{
public static void main(String args[])
{
System.out.println("================================"+"\n"+"Enter Programmer
Details"+"\n"+"================================"+"\n");
programmer ob1 = new programmer();

ob1.calculatepayprog();
ob1.display();
System.out.println("================================"+"\n"+"Enter Assistant
Professor Details"+"\n"+"================================"+"\n");
assistantprofessor ob = new assistantprofessor();
ob.calculatepay1();
ob.display();
System.out.println("================================"+"\n"+"Enter Associate
Professor Details"+"\n"+"================================"+"\n");
associateprofessor ob2 = new associateprofessor();
ob2.calculatepay2();
ob2.display();
System.out.println("================================"+"\n"+"Enter Professor
Details"+"\n"+"================================"+"\n");
professor ob3 = new professor();
ob3.calculatepay3();
ob3.display();
}}

OUTPUT:
================================
Enter Programmer Details
================================
Enter Name of the Employee:
james
Enter the ID of the Employee:
e23
Enter Address of the Employee:
lake view avenue
Enter mail id of the Employee:
[email protected]
Enter the mobile no:
23456123
Enter basic pay:
4567

8
IT1308-Java programming Laboratory Department of IT 2022-2023

==============================
Programmer Details
==============================
Employee Name: james
EmployeeID: e23
Address: lake view avenue
MailID: [email protected]
Mobile No: 23456123
Gross Salary: 9595.267
Net Salary: 9047.226999999999
================================
Enter Assistant Professor Details
================================
Enter Name of the Employee:
arun
Enter the ID of the Employee:
e34
Enter Address of the Employee:
vivekananda street
Enter mail id of the Employee:
[email protected]
Enter the mobile no:
1235678
Enter basic pay:
2345
==============================
Assistant Professor Details
==============================
Employee Name: arun
EmployeeID: e34
Address: vivekananda street
MailID: [email protected]
Mobile No: 1235678
Gross Salary: 4926.844999999999
Net Salary 4645.445
================================
Enter Associate Professor Details
================================
Enter Name of the Employee:
Alex
Enter the ID of the Employee:
e45
Enter Address of the Employee:
ground avnue
Enter mail id of the Employee:
[email protected]
Enter the mobile no:

9
IT1308-Java programming Laboratory Department of IT 2022-2023

76543678
Enter basic pay:
2341
==============================
Associate Professor Details
==============================
Employee Name: Alex
EmployeeID: e45
Address: ground avnue
MailID: [email protected]
Mobile No: 76543678
Gross Salary: 4918.441000000001
Net Salary 4637.521000000001
================================
Enter Professor Details
================================
Enter Name of the Employee:
Justina
Enter the ID of the Employee:
23
Enter Address of the Employee:
springfield,sunnyvale
Enter mail id of the Employee:
[email protected]
Enter the mobile no:
987634521
Enter basic pay:
3451
==============================
Professor Details
==============================
Employee Name: Justina
EmployeeID: 23
Address: springfield,sunnyvale
MailID: [email protected]
Mobile No: 987634521
Gross Salary: 7250.5509999999995
Net Salary 6836.431

RESULT:

10
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex.3 write a java program to make frequency count of words in a given text

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.io.*;
class FrequencyCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String: ");
String s=br.readLine();
System.out.println("Enter substring: ");
String sub=br.readLine();
int ind,count=0;
for(int i=0; i+sub.length()<=s.length(); i++)
{
ind=s.indexOf(sub,i);
if(ind>=0)
{
count++;
i=ind;
ind=-1;
}}
System.out.println("Occurence of '"+sub+"' in String is "+count);
}}

Output:
Enter the String:
programming9.com covers wide range of programs and tutorials.
Enter substring:
program
Occurence of 'program' in String is 2

RESULT:

11
IT1308-Java programming Laboratory Department of IT 2022-2023

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 int area_tri;

public void print_area()


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

12
IT1308-Java programming Laboratory Department of IT 2022-2023

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);
}
}
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:

13
IT1308-Java programming Laboratory Department of IT 2022-2023

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 elementtop) 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");

14
IT1308-Java programming Laboratory Department of IT 2022-2023

} }
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:

15
IT1308-Java programming Laboratory Department of IT 2022-2023

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:

16
IT1308-Java programming Laboratory Department of IT 2022-2023

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


Date:

AIM
To write java program for creating abstract class implementation.

ALGORITHIM
7. Start
8. Create shape abstract class with print area as member function to print triangle,
rectangle and circle area.
9. 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
10. Create main class to get user input base, height and radius for rectangle, triangle and
circle.
11. Create rectangle, triangle, and circle objects to call respective defined function and pass
user inputs.
12. Stop

PROGRAM
package pack1;
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 int area_tri;

public void print_area()


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

17
IT1308-Java programming Laboratory Department of IT 2022-2023

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);
}
}

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:
The area of rectangle is:12
The area of triangle is:6
The area of circle is:28

RESULT:

18
IT1308-Java programming Laboratory Department of IT 2022-2023

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.
3.create a constructor and receive the value from main class
3:In MainException class create user defined exception and throw our own exception
4:Print the exception message.
5: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:

19
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex no 8: To find the maximum value from the given type of elements using a generic
function.

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:

20
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex No 9 String handling Functions

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");

21
IT1308-Java programming Laboratory Department of IT 2022-2023

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 : 20Capacity 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 EVENINGThe appended string is :
TODAY IS A GREAT EVENING YAD YPPAH A SI YADOT

RESULT:

22
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex No 10 String operation using ArrayList


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: ");
String ch = scan.next();

23
IT1308-Java programming Laboratory Department of IT 2022-2023

//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;

24
IT1308-Java programming Laboratory Department of IT 2022-2023

}
}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


Enter your choice: 5 mani

25
IT1308-Java programming Laboratory Department of IT 2022-2023

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

26
IT1308-Java programming Laboratory Department of IT 2022-2023

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());
}
}

27
IT1308-Java programming Laboratory Department of IT 2022-2023

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:

28
IT1308-Java programming Laboratory Department of IT 2022-2023

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)
{}

29
IT1308-Java programming Laboratory Department of IT 2022-2023

}
}
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

30
IT1308-Java programming Laboratory Department of IT 2022-2023

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

RESULT:

31
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex.No:13 GUI Window operations in java

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.applet.*;
import java.awt.event.*;

public class ProgB6 extends Applet implements KeyListener

String msg="Press M or A or E or N";

int X=10,Y=20;

Font f1;

public void init()

f1= new Font("Georgia",Font.BOLD, 22);

addKeyListener(this);

public void keyPressed(KeyEvent ke)

int key=ke.getKeyCode();

switch(key)

32
IT1308-Java programming Laboratory Department of IT 2022-2023

case KeyEvent.VK_M: msg="Good Morning!";

break;

case KeyEvent.VK_A: msg="Good Afternoon!";

break;

case KeyEvent.VK_E: msg="Good Evening!";

break;

case KeyEvent.VK_N: msg="Good Night!";

break;

repaint();

public void keyReleased(KeyEvent ke)

//showStatus("Key UP");

public void keyTyped(KeyEvent ke)

repaint();

public void paint(Graphics g)

33
IT1308-Java programming Laboratory Department of IT 2022-2023

g.setFont(f1);

g.setColor(Color.blue);

g.drawString(msg,X,Y);

OUTPUT:

RESULT:

34
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex.No:14 Create a GUI program in java

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
public static void main(String[] args)
{
// create a new frame to store text field and button

35
IT1308-Java programming Laboratory Department of IT 2022-2023

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();
}
// 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

36
IT1308-Java programming Laboratory Department of IT 2022-2023

l.setText(t.getText());
// set the text of field to blank
t.setText(" ");
}
}
}

Output:

RESULT:

37
IT1308-Java programming Laboratory Department of IT 2022-2023

Ex.No:15. Design and Develop the GUI application with database connectivity of your
choice

AIM:
To design and develop the GUI application with database connectivity of your choice.

PROGRAM:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class UserLogin extends JFrame {

private static final long serialVersionUID = 1L;


private JTextField textField;
private JPasswordField passwordField;
private JButton btnNewButton;
private JLabel label;
private JPanel contentPane;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserLogin frame = new UserLogin();
frame.setVisible(true);
} catch (Exception e) {

38
IT1308-Java programming Laboratory Department of IT 2022-2023

e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public UserLogin() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 190, 1014, 597);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel lblNewLabel = new JLabel("Login");


lblNewLabel.setForeground(Color.BLACK);
lblNewLabel.setFont(new Font("Times New Roman", Font.PLAIN, 46));
lblNewLabel.setBounds(423, 13, 273, 93);
contentPane.add(lblNewLabel);

textField = new JTextField();


textField.setFont(new Font("Tahoma", Font.PLAIN, 32));
textField.setBounds(481, 170, 281, 68);
contentPane.add(textField);
textField.setColumns(10);

passwordField = new JPasswordField();


passwordField.setFont(new Font("Tahoma", Font.PLAIN, 32));
passwordField.setBounds(481, 286, 281, 68);
contentPane.add(passwordField);

JLabel lblUsername = new JLabel("Username");


lblUsername.setBackground(Color.BLACK);
lblUsername.setForeground(Color.BLACK);
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 31));
lblUsername.setBounds(250, 166, 193, 52);
contentPane.add(lblUsername);

JLabel lblPassword = new JLabel("Password");


lblPassword.setForeground(Color.BLACK);
lblPassword.setBackground(Color.CYAN);
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 31));

39
IT1308-Java programming Laboratory Department of IT 2022-2023

lblPassword.setBounds(250, 286, 193, 52);


contentPane.add(lblPassword);

btnNewButton = new JButton("Login");


btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 26));
btnNewButton.setBounds(545, 392, 162, 73);
btnNewButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


String userName = textField.getText();
String password = passwordField.getText();
try {
Connection connection = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/swing_demo",
"root", "root");

PreparedStatement st = (PreparedStatement) connection


.prepareStatement("Select name, password from student where name=? and
password=?");

st.setString(1, userName);
st.setString(2, password);
ResultSet rs = st.executeQuery();
if (rs.next()) {
dispose();
UserHome ah = new UserHome(userName);
ah.setTitle("Welcome");
ah.setVisible(true);
JOptionPane.showMessageDialog(btnNewButton, "You have successfully logged
in");
} else {
JOptionPane.showMessageDialog(btnNewButton, "Wrong Username &
Password");
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
});

contentPane.add(btnNewButton);

label = new JLabel("");


label.setBounds(0, 0, 1008, 562);
contentPane.add(label);
}}

40
IT1308-Java programming Laboratory Department of IT 2022-2023

OUTPUT:

RESULT:

41

You might also like