0% found this document useful (0 votes)
5 views32 pages

Java Lab Cycle (1)

The document contains a series of Java programming exercises covering various concepts such as harmonic series calculation, string manipulation, online shopping simulation, vector duplicate identification, multithreading, exception handling, list shuffling, arithmetic operations in packages, applet creation for a calculator, text search, applet event sequences, method overriding, and list manipulation. Each exercise includes code snippets and sample outputs to demonstrate functionality. The exercises are intended for educational purposes at JMJ College for Women in Tenali.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views32 pages

Java Lab Cycle (1)

The document contains a series of Java programming exercises covering various concepts such as harmonic series calculation, string manipulation, online shopping simulation, vector duplicate identification, multithreading, exception handling, list shuffling, arithmetic operations in packages, applet creation for a calculator, text search, applet event sequences, method overriding, and list manipulation. Each exercise includes code snippets and sample outputs to demonstrate functionality. The exercises are intended for educational purposes at JMJ College for Women in Tenali.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

OOPS USING JAVA J A31

1. Write a java program to determine the sum of the following harmonic series for a
given value of ‘n’.
1+1/2+1/3+. . . +1/n
import java.io.*;
class ShowSum
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter n value:");
int n=Integer.parseInt(br.readLine());
float sum=1;
for(int i=1;i<=n; i++)
sum = sum+(float)1/i;
System.out.println ("Sum="+sum);
}
}
Output:
Enter n value: 5
Sum=3.2833333

JMJ COLLEGE FOR WOMEN(A), TENALI Page 1


OOPS USING JAVA J A31

2. Write a program to perform the following operations on strings through interactive input.
a) Sort given strings in alphabetical order.
b) Check whether one string is sub string of another string or not.
c) Convert the strings to uppercase.
import java.io.*;
class StringTest
{
public static void main(String args[]) throws Exception
{
int i, j, n, x;
String temp,s1,s2;
String s[]=new String[10];
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
do
{
System.out.println("\n 1.Sorting\n 2.Substring\n 3.Uppercase");
System.out.println("\n 1.Enter your choice:");
x=Integer.parseInt(br.readLine());
} while(x<1||x>3);
if(x==1||x==3)
{
System.out.println("How many Strings:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter strings:\n");
for(i=0;i<n;i++)
s[i]=br.readLine();
}
if(x==1)
{
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(s[i].compareTo(s[j])>0)

JMJ COLLEGE FOR WOMEN(A), TENALI Page 2


OOPS USING JAVA J A31

{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
System.out.println("After Sorting:");
for(i=0;i<n;i++)
System.out.print(s[i]+"\t");
}
else if(x==2)
{
System.out.println("Enter main string:");
s1=br.readLine();
System.out.println("Enter sub string:");
s2=br.readLine();
if(s1.indexOf(s2)!=-1)
System.out.println(s2 +" is sub string of"+ s1);
else
System.out.println(s2 +" is not a sub string of "+ s1);
}
else
{
System.out.println("Strings in Uppercase");
for(i=0;i<n;i++)
System.out.print("\t"+s[i].toUpperCase());
}
}
}

JMJ COLLEGE FOR WOMEN(A), TENALI Page 3


OOPS USING JAVA J A31

Output:
1.Sorting
2.Substring
3.Uppercase
Enter your choice:1
How many Strings:3
Enter strings:
mango
apple
banana
After Sorting:
apple banana mango

JMJ COLLEGE FOR WOMEN(A), TENALI Page 4


OOPS USING JAVA J A31

3. Write a program to simulate online shopping.


import java.io.*;
class Shopping
{
public static void main(String args[]) throws Exception
{
int i=0,x,op,sum=0,m;
String con=" ";
int a[]=new int[10];
int n[]=new int[10];
String s[]={"Self Confidence -book(Rs.200)","My Experiments with truth(Rs. 100)",
"Java Apoorva book(Rs. 150)","Java Complete Reference(Rs. 300)"};
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
do
{
System.out.println("Select Items from the list:\n");
System.out.println(" 1.Self Confidence -book\tRs.200");
System.out.println(" 2.My Experiments with truth\tRs.100");
System.out.println(" 3.Java Apoorva book\tRs.150");
System.out.println(" 4.Java Complete Reference\tRs.300");
System.out.println("\nSelect the Item number:");
x=Integer.parseInt(br.readLine());
if(x<1 || x>4) continue;
a[i]=x;
System.out.println("Enter quantity:");
n[i]=Integer.parseInt(br.readLine());
i++;
System.out.println("Add more Items?(y,n):");
con=br.readLine();
} while(con.equals("y"));
m=i; // number of items
System.out.println("\n 1. Check out \n 2. Cancel the order \n");

JMJ COLLEGE FOR WOMEN(A), TENALI Page 5


OOPS USING JAVA J A31

System.out.println("Enter option:");
op=Integer.parseInt(br.readLine());
if(op==1)
{
System.out.println("==========================================");
System.out.println("\nItem\tQuantity");
System.out.println("==========================================");
for(i=0;i<m;i++)
{
if(a[i]==1)
sum=sum+n[i]*200;
else if(a[i]==2)
sum=sum+n[i]*100;
else if(a[i]==3)
sum=sum+n[i]*150;
else if(a[i]==4)
sum=sum+n[i]*300;
System.out.println("\n"+s[a[i]]+"\t"+n[i]);
}
System.out.println("==========================================");
System.out.println("\nTotal Bill:"+sum);
System.out.println("==========================================");
}
}
}

JMJ COLLEGE FOR WOMEN(A), TENALI Page 6


OOPS USING JAVA J A31

Output:
Select Items from the list:
1.Self Confidence -book Rs.200
2.My Experiments with truth Rs.100
3.Java Apoorva book Rs.150
4.Java Complete Reference Rs.300
Select the Item number:1
Enter quantity: 2
Add more Items?(y,n):y
Select Items from the list:
1.Self Confidence -book Rs.200
2.My Experiments with truth Rs.100
3.Java Apoorva book Rs.150
4.Java Complete Reference Rs.300
Select the Item number:3
Enter quantity:2
Add more Items?(y,n):n
1. Check out
2. Cancel the order
Enter option:1
=============================================
Item Quantity
=============================================
My Experiments with truth(Rs. 200) 2
Java Apoorva book(Rs. 150) 2
=============================================
Total Bill:700
=============================================

JMJ COLLEGE FOR WOMEN(A), TENALI Page 7


OOPS USING JAVA J A31

4. Write a program to identify a duplicate value in a vector.


import java.io.*;
import java.util.*;
class VectorTest
{
public static void main(String args[]) throws Exception
{
int i,j,n;
Vector v1=new Vector(10);
Vector v2=new Vector(10);
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("How many Strings:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter strings:\n");
for(i=0;i<n;i++)
v1.add(br.readLine());
System.out.println("Vector Elements:\n"+v1);
for(i=0;i<v1.size();i++)
for(j=i+1;j<v1.size();j++)
if(v1.elementAt(i).equals(v1.elementAt(j)))
v2.add(v1.elementAt(j));
System.out.println("\nDuplicate Elements:\n"+v2);
}
}

JMJ COLLEGE FOR WOMEN(A), TENALI Page 8


OOPS USING JAVA J A31

Output:
How many Strings:5
Enter strings:
cat
rat
mat
cat
mat
Vector Elements:
[cat, rat, mat, cat, mat]
Duplicate Elements:
[cat, mat]

JMJ COLLEGE FOR WOMEN(A), TENALI Page 9


OOPS USING JAVA J A31

5. Create two threads such that one of the thread print even no’s and another prints odd no’s up
to a given range.
class MyThread extends Thread
{
int initval, finalval;
MyThread(int iv,int fv)
{
initval=iv;
finalval=fv;
start();
}
public void run()
{
for(int i=initval;i<=finalval;i+=2)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
class ThreadTest
{
public static void main(String args[])
{
MyThread t1=new MyThread(1,6);
MyThread t2=new MyThread(2,6);
}
}

JMJ COLLEGE FOR WOMEN(A), TENALI Page 10


OOPS USING JAVA J A31

Output:
1
2
3
4
5
6

JMJ COLLEGE FOR WOMEN(A), TENALI Page 11


OOPS USING JAVA J A31

6. Define an exception called “Marks Out Of Bound” Exception, that is thrown


if the entered marks are greater than 100.

import java.io.*;
class MarksOutOfBounds extends Exception
{
public void showError()
{
System.out.println("Invalid Marks");
}
}
class ErrorTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int m=0;
try
{
System.out.println("Enter Marks:");
m=Integer.parseInt(br.readLine());
if(m>100)
throw new MarksOutOfBounds();
System.out.println("Your Marks:"+m);
}
catch(MarksOutOfBounds e)
{
e.showError();
}
}
}
Output: Enter Marks:120
Invalid Marks

JMJ COLLEGE FOR WOMEN(A), TENALI Page 12


OOPS USING JAVA J A31

7. Write a JAVA program to shuffle the list elements using all the possible permutations.
class ShuffleString
{
public static void main(String args[])
{
char s[]={'a','b','c'};
int i,j,k,n=s.length;
/* number of for loops should match with number of character i.e here ‘3’ */
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(i!=j && j!=k && i!=k)
System.out.println(s[i]+","+s[j]+","+s[k]);
}
}
/* Output: */
abc
acb
bac
bca
cab
cba

JMJ COLLEGE FOR WOMEN(A), TENALI Page 13


OOPS USING JAVA J A31

8. Create a package called “Arithmetic” that contains methods to deal with all arithmetic
operations. Also, write a program to use the package.
Note: First create a directory by name “Arithmetic” and move to that directory, create the following file
and compile the file in the same directory.
package arithmetic;
public class MyMath
{
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
}
}
Note: Move to parent directory, write the following file and execute it.
import arithmetic.*;
class Test
{
public static void main(String args[])

JMJ COLLEGE FOR WOMEN(A), TENALI Page 14


OOPS USING JAVA J A31

{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
Output:
13
3
40
1.6
3

JMJ COLLEGE FOR WOMEN(A), TENALI Page 15


OOPS USING JAVA J A31

9. Write an Applet program to design a simple calculator.


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Calc extends Applet implements ActionListener
{
String cmd[]={"+","-","*","/","=","C"};
int pv=0;
String op="";
Button b[]=new Button[16];
TextField t1=new TextField(10);
public void init()
{
setLayout(new BorderLayout());
add(t1,"North");
t1.setText("0");
Panel p=new Panel();
p.setLayout(new GridLayout(4,4));
for(int i=0;i<16;i++)
{
if(i<10)
b[i]=new Button(String.valueOf(i));
else
b[i]=new Button(cmd[i%10]);
b[i].setFont(new Font("Arial",Font.BOLD,25));
p.add(b[i]);
add(p,"Center");
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent ae)
{
int res=0;

JMJ COLLEGE FOR WOMEN(A), TENALI Page 16


OOPS USING JAVA J A31

String cap=ae.getActionCommand();
int cv=Integer.parseInt(t1.getText());
if(cap.equals("C"))
{
t1.setText("0");
pv=0;
cv=0;
res=0;
op="";
}
else if(cap.equals("="))
{
res=0;
if(op=="+")
res=pv+cv;
else if(op=="-")
res=pv-cv;
else if(op=="*")
res=pv*cv;
else if(op=="/")
res=pv/cv;
t1.setText(String.valueOf(res));
}
else if(cap.equals("+")||cap.equals("-")||
cap.equals("*")||cap.equals("/"))
{
pv=cv;
op=cap;
t1.setText("0");
}
else
{
int v=cv*10+Integer.parseInt(cap);

JMJ COLLEGE FOR WOMEN(A), TENALI Page 17


OOPS USING JAVA J A31

t1.setText(String.valueOf(v));
}
}
}
Output:

JMJ COLLEGE FOR WOMEN(A), TENALI Page 18


OOPS USING JAVA J A31

10.Write a program to read a text and count all the occurrences of a given word. Also, display their
positions.

import java.io.*;
class TextSearch
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int i=0,count=0;
String text="",s="";
System.out.println("Enter Text:(press ENTER twice to stop)\n");
s=br.readLine();
while(s.length()!=0)
{
text+=s;
s=br.readLine();
}
System.out.println("Enter search word:");
s=br.readLine();
while(true)
{
i=text.indexOf(s,i);
if(i==-1) break;
System.out.println("Word found at position:"+i);
count++;
i+=s.length();
}
System.out.println("Number of occurrences of given word:"+count);
}
}

JMJ COLLEGE FOR WOMEN(A), TENALI Page 19


OOPS USING JAVA J A31

Output:
Enter Text:(press ENTER twice to stop)
Hello hi , hi again
hi nice to see you
Enter search word:hi
Word found at position:6
Word found at position:11
Word found at position:19
Number of occurrences of given word:3

JMJ COLLEGE FOR WOMEN(A), TENALI Page 20


OOPS USING JAVA J A31

11.Write an applet illustrating sequence of events in an applet.


import java.applet.*;
import java.awt.*;
public class A1 extends Applet
{
String s="";
public void init()
{
s+=" Init,";
}
public void start()
{
s+=" Start,";
}
public void paint(Graphics g)
{
s+=" Paint";
g.drawString(s,10,100);
}
public void stop()
{
System.out.println("Stop");
}
public void destroy()
{
System.out.println("Destroy");
}
}
Output:
It prints “Init Start Paint” in the applet and then
Stop
Destroy
On the console screen

JMJ COLLEGE FOR WOMEN(A), TENALI Page 21


OOPS USING JAVA J A31

12. Illustrate the method overriding in JAVA.


class Alpha
{
public void show()
{
System.out.println("Hello from Parent Class");
}
}
class Beta extends Alpha
{
public void show() //overriding
{
System.out.println("Hello from Child Class");
}
}
class Test
{
public static void main(String as[])
{
Beta b1=new Beta();
b1.show();
}
}
Output:
Hello from Child Class

JMJ COLLEGE FOR WOMEN(A), TENALI Page 22


OOPS USING JAVA J A31

13. Write a program to fill elements into a list. Also, copy them in reverse order into another list.
import java.io.*;
import java.util.*;
class ListTest
{
public static void main(String as[]) throws Exception
{
int i,j,n;
ArrayList l1=new ArrayList();
ArrayList l2=new ArrayList();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("How many Strings:");
n=Integer.parseInt(br.readLine());
System.out.println("Enter strings:\n");
for(i=0;i<n;i++)
l1.add(br.readLine());
System.out.println("List Elements:\n"+l1);
for(i=n-1;i>=0;i--)
l2.add(l1.get(i));
System.out.println("List Elements Reversed:\n"+l2);
}
}
Output:
How many Strings:4
Enter strings:
cat
rat
bat
List Elements:
[cat, rat, bat]
List Elements Reversed:
[bat, rat, cat]

JMJ COLLEGE FOR WOMEN(A), TENALI Page 23


OOPS USING JAVA J A31

14. Write an interactive program to accept name of a person and validate it.
If the name contains any numeric value throw an exception “InvalidName”.
import java.io.*;
class InvalidName extends Exception
{
public void showError()
{
System.out.println("Error:Name contains digits");
}
}
class NameTest
{
public static void main(String args[]) throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String name;
int i;
try
{
System.out.println("Enter Name:");
name=br.readLine();
for(i=0;i<name.length();i++)
{
char ch=name.charAt(i);
if(Character.isDigit(ch))
throw new InvalidName();
}
System.out.println("Your Name:"+name);
}
catch(InvalidName e)
{
e.showError();

JMJ COLLEGE FOR WOMEN(A), TENALI Page 24


OOPS USING JAVA J A31

}
}
}
/* Output: */
Enter Name:Ravi12
Error:Name contains digits

JMJ COLLEGE FOR WOMEN(A), TENALI Page 25


OOPS USING JAVA J A31

15. Write an applet program to insert the text at the specified position.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TextInsert extends Applet implements ActionListener
{
TextArea ta=new TextArea("Welcome to text insert \n application"+ "place the cursor to insert text and
enter \n"+ "the text to insert in text box then click \n"+ "insert button",10,20);
TextField t1=new TextField(10);
TextField t2=new TextField(10);
Button b1=new Button("Insert");
public void init()
{
add(ta);
add(new Label("position"));
add(t1);
add(new Label("string"));
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ta.insertText(t2.getText(),Integer.parseInt(t1.getText()));
}
}
output:

JMJ COLLEGE FOR WOMEN(A), TENALI Page 26


OOPS USING JAVA J A31

16. Prompt for the cost price and selling price of an article and display the profit
(or) loss percentage.
import java.io.*;
class Sales
{
public static void main(String args[]) throws Exception
{
double sp,cp,perc;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter Cost price of an article:");
cp=Double.parseDouble(br.readLine());
System.out.println("Enter Cost price of an article:");
sp=Double.parseDouble(br.readLine());
perc=((sp-cp)/cp)*100;
if(perc<0)
System.out.println("Loss percentage="+perc+"%");
else if(perc>0)
System.out.println("Gian percentage="+perc+"%");
else
System.out.println("No Profitm, No Loss");
}
}
Output:
Enter Cost price of an article:200
Enter Cost price of an article:250
Gian percentage=25.0%

JMJ COLLEGE FOR WOMEN(A), TENALI Page 27


OOPS USING JAVA J A31

17. Create an anonymous array in JAVA.


class AnonymousArray
{
public static void main(String args[])
{
System.out.println(“Length of array is “ + findLength(new int[]{1,2,3}));
}
public static int findLength(int[] array)
{
return array.length;
}
}
Output:
Length of array is 3

JMJ COLLEGE FOR WOMEN(A), TENALI Page 28


OOPS USING JAVA J A31

18. Create a font animation application that changes the colors of text as and when prompted.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class FontAnim extends Applet implements ActionListener
{
Button b1=new Button("Change Color");
int r=0,g=0,b=0;
public void init()
{
add(b1);
b1.addActionListener(this);
setFont(new Font("Arial",Font.BOLD,30));
}
public void actionPerformed(ActionEvent ae)
{
r=(int)(Math.random()*255);
g=(int)(Math.random()*255);
b=(int)(Math.random()*255);
repaint();
}
public void paint(Graphics gr)
{
gr.setColor(new Color(r,g,b));
gr.drawString("APOORVA",20,200);
}
}
output:

JMJ COLLEGE FOR WOMEN(A), TENALI Page 29


OOPS USING JAVA J A31

19. Write an interactive program to wish the user at different hours of the day.
import java.util.*;
class TimeTest
{
public static void main(String args[]) throws Exception
{
Date d=new Date();
int h=d.getHours();
if(h<12)
System.out.println("Good Morning");
else if(h<16)
System.out.println("Good Afternoon");
else if(h<20)
System.out.println("Good Evening");
else
System.out.println("Time to sleep, Good night");
}
}

Output:
Good Afternoon.

JMJ COLLEGE FOR WOMEN(A), TENALI Page 30


OOPS USING JAVA J A31

20. Simulate the library information system i.e. maintain the list of books and borrower’s details.
import java.io.*;
class Library
{
public static void main(String args[]) throws Exception
{
int i=0,x,m;
String con="";
int a[]=new int[10];
String name[]=new String[10];
String s[]={"Self Confidence ","My Experiments with truth",
"Java Apoorva book","Java Complete Reference"};
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
do
{
System.out.println("Select Books from the list:\n");
System.out.println(" 1.Self Confidence -book");
System.out.println(" 2.My Experiments with truth");
System.out.println(" 3.Java Apoorva book");
System.out.println(" 4.Java Complete Reference");
System.out.println("\nSelect the book number:");
x=Integer.parseInt(br.readLine());
if(x<1 || x>4) continue;
a[i]=x;
System.out.println("Enter your name:");
name[i]=br.readLine();
i++;
System.out.println("Continue?(y,n):");
con=br.readLine();
}while(con.equals("y"));
m=i; // number of borrowers
System.out.println("==========================================");

JMJ COLLEGE FOR WOMEN(A), TENALI Page 31


OOPS USING JAVA J A31

System. out.println("\nName \t Book borrowed");


System.out.println("=========================================");
for(i=0;i<m;i++)</m;i++)
{
System.out.println(name[i]+"\t"+s[a[i]]);
} System.out.println("==========================================");
}
}
Output:
Select Books from the list:
1.Self Confidence -book
2.My Experiments with truth
3.Java Apoorva book
4.Java Complete Reference
Select the book number:2
Enter your name:Ravi
Continue?(y,n):y
Select Books from the list:
1.Self Confidence -book
2.My Experiments with truth
3.Java Apoorva book
4.Java Complete Reference
Select the book number:3
Enter your name:Kiran
Continue?(y,n):n

JMJ COLLEGE FOR WOMEN(A), TENALI Page 32

You might also like