JAVA PROGRAMMING Lab Manual
JAVA PROGRAMMING Lab Manual
JAVA PROGRAMMING
LAB MANUAL
INDEX
Lab-Assignment – 1 String
Lab-Assignment – 2 Loop
Lab-Assignment – 4 Arithmetic
Lab-Assignment – 5 Method
Lab-Assignment – 6 Recursion
Lab-Assignment – 8 Copy
Lab-Assignment – 10 Exception
Lab-Assignment – 12 Inheritance
Lab-Assignment – 13 Interface
Lab-Assignment – 14 Visibility/Error
Lab-Assignment – 15 Thread
Lab-Assignment – 16 File
Lab-Assignment – 17 Graphics
Lab-Assignment – 1 String
In a file name (say a.java) type following program. The file can be compiled by
command javac a.java. To run the program give command java kapil.
import java.io.*;
import java.lang.*;
class kapil
{ public static void main(String args[])
{ String a,b;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();
b=a.substring(2,5);
System.out.println(b);
}
catch(IOException e) { System.out.println(e); }
}
}
The program outputs sub string between positions 2 and 5 (including 2 but excluding
5). The first character is at 0th position. e.g. input qwertyuiuo output ert.
b=a.substring(4);System.out.println(b);
The program outputs string on and after 4th position. input qwertyuiuo output tyuiuo
String a,b,c; a=o.readLine();b=o.readLine();
c=a+b; System.out.println(c);
The program takes two strings and joins them.
1. Write program to remove 2nd letter. Let the input string is pwsxtpbcderxrtxgt then
output is pwxtpbcderxrtxgt.
2. Write program to add 0th letter in the beginning. In above case ppwsxtpbcderxrtxgt
3. Write program to exchange first two letters. In above case wpsxtpbcderxrtxgt.
4. Write program to exchange 4th and 10th letter. In above case pwsxrpbcdetxrtxgt.
5. Write program to insert ‘t’ between 1st and 2nd letter. In above case
pwtsxtpbcderxrtxgt. [Hint: a+”t”+b].
a=o.readLine();
i=a.indexOf('x');
System.out.println(i);
At what location 'x' is present. If more than one occurrence of 'x' is there then the
location of first 'x' is returned. If 'x' is absent then 1 is returned. e.g. input wedxtyhxu
output 3
6. Write a program, which reads a string and finds string after the first x. Let the
input string is pwsxtpbcderxrtxgt then output is tpbcderxrtxgt.
7. Write program to replace first x by y. In above case pwsytpbcderxrtxgt.
8. Write program to output the location of second x. In above case 11.
9. Write program to print the string between 1st and 2nd x. In above case tpbcder.
10. Write program to find string before 2nd x. In above case pwsxtpbcder.
11. Write program to delete the string between 1st and 2nd x. In above case pwsxxrtxgt.
12. Program to exchange the string between 1st and 2nd x, with the string before 1st x.
In above case tpbcderxpwsxrtxgt
13. Write program to exchange neighbors of first x. In above case pwtxspbcderxrtxgt.
char b;a=o.readLine();b=a.charAt(2);
System.out.println(b);
Program outputs character at location 2. e.g. input qwertyuiuo output e
14. Write program to find 2nd location of 0th letter. Input pwerpty output 4.
15. Write program, which will delete 1st y immediately after 1st x. If input string is
pgyeryuyixaysdyexer then output is pgyeryuyixasdyexer.
16. Write program to exchange neighbors of first occurrence of left neighbors of first
‘x’. e.g. input abcdefxgh output abcdxfegh. input abfcdefxgh output acfbdefxgh.
17. Write program to replace first occurrence of right neighbor of 2 nd x by left
neighbor of 1st x. Input imgpxugxutkl output imgpxpgxutkl. Input bcxdefxgh
output bcxdefxch.
18. Write program, which reads a string. Let x and y be respectively left and right
neighbors of the second occurrence of the 0 th letter. Find the substring between
first occurrence of y and (first occurrence of x after first occurrence of y). e.g.
input patkgfmpkst output kgfm. Input pastgksfsptse output tgks. Input raklfrgmcfd
output gmcf. Input ywetyykjhtl output ywet.
a=o.readLine();b=o.readLine();
i=a.compareTo(b);System.out.println(i);
Input two strings. Output is 0 if both are same. If second string is (lexicographically)
bigger then a negative number is outputted. If first string is bigger then some positive
number is outputted.
Use of “if” is permitted in following programs.
19. Read two strings. Print lexicographically bigger string first and smaller later.
20. Read two string. Print 1 if first string is bigger, 2 if second string is bigger, 0 if
both are same.
21. Read three strings. Print 1 if first string is biggest, 2 if second string is biggest, 3 if
3rd string is biggest, 0 if all are same, -1 if 1 st and 2nd string are biggest, -2 if 2nd
and 3rd string are biggest, -3 if 1st and 3rd string are biggest.
a=o.readLine();a=a.trim();
i=a.indexOf(' ');b=a.substring(0,i);
System.out.println(b);
Print first word. Trim removes blank spaces at the beginning and at the end. If it is not
used then the problem will arise if blanks are given at the beginning. The program
will not work if string has only one word. If string is ram Prasad dey then output is
ram.
22. Print second word. In above case Prasad.
23. Delete second word. In above case ram dey.
24. Exchange first and second word. In above case Prasad ram dey.
25. Exchange first letters of first two words. In above case Pam rrasad dey.
26. Exchange last letters of first two words. In above case rad Prasam dey.
27. Find the location of first ‘a’ in second word. In above case 6.
28. Find location of first letter of first word in second word. In above case 5.
Lab-Assignment – 2 Loop
a=o.readLine();
for (i=1;i<=4;i++){
j=a.indexOf('x');
b=a.substring(0,j);
a=a.substring(j+1);
System.out.println(b);}
Prints first 4 substrings before x input qwexrx123xtyxasdfx output qwe, r, 123, ty
a=o.readLine();t="";
for (i=1;i<=4;i++){
j=a.indexOf('x');
b=a.substring(0,j);t=t+b;
a=a.substring(j+1);
}
System.out.println(t+a);
Delete first 4 x's
1. Write program to print the string after 4th x. Let input string be pwsxtxaxxrxd then
output is rxd.
2. Write program, which will find the string letters between 3 th and 4th x. In above
case output is null string.
3. Write program, which finds the letter after 4th x. In above case r.
4. Write program, which finds the letter before 3rd x. In above case a.
a=o.readLine();count=0;
while (a.indexOf('x')!=-1){
i=a.indexOf('x');
a=a.substring(i+1);
count++;
}
Find Number of x's
5. Write program, which will find the string after last x. In above case d.
6. Write program, which finds letters after every x. In above case taxrd.
7. Write program, which deletes last x. In above case pwsxtxaxxrd.
8. Write program, which will find location of all x’s. Let input string be
pwsxtxaxxrxd the output is 3 5 7 8 10.
9. Write program, which will remove all x’s. In above case output pwstard.
10. Write program, which will replace every x by y. In above case output
pwsytyayyryd.
11. Write program, which will insert y after every x. In above case
pwsxytxyaxyxyrxyd
12. Write program, which will find the location of last ‘x’. In above case 10.
13. Write program, which will find the length of string. Do not use length method.
a=o.readLine();
for (i=1;(a.length()!=0);i++){
b=a.substring(0,1);
a=a.substring(1);
System.out.println(b); }
Print every characters of the string in separate line.
a=o.readLine();loc=0;
do{
i=a.indexOf('x');
loc=loc+(i+1);
a=a.substring(i+1);
} while(a.indexOf('y')!=0);
System.out.println(loc-1);
}
Find location of first xy. Input yerxryyttxysdfxu output 9.
14. Write program, which finds the number of non-consecutive x’s. In above case 3.
15. Write program, which will find the location of sub string xy. If more than one xy
is present then location of first xy will be printed. If no xy is present then –1 is
printed. e.g. input wyqxaexytrxixyty output 6.
16. Write a program, which will remove x’s which are at the start of the string. Input
string xxxwexrxxsxx output wexrxxsxx.
17. Write program to remove x’s which are at the end. In above case output
xxxwexrxxs.
18. Write program, which delete 1st y immediately before 1st x. If input string is
pgyeryuyixasdyexer then output is pgyeryuixasdyexer.
19. Write program, which will find the location of first x. Do not use indexOf.
20. Write program, which will insert x in between consecutive letters. e.g. input srwe
output sxrxwxe.
21. Write program, which will reverse a string.
22. Write program, which will reverse sub string between consecutive x’s. e.g. input
wexcapxxzmtxabx output wexpacxxtmzxbax.
23. Read a string of words. Delete unnecessary blanks. Input I am bad output I am
bad.
24. Read a string of words. Output all words at even location. Input ram hari gopal
ravi anil ramesh output hari ravi ramesh.
25. Exchange consecutive words of string (assume string has even number of words).
For above input output is hari ram ravi gopal ramesh anil.
26. Find lexicographically biggest word. For above case ravi.
27. Output all those words, which are smaller than raja. For above case hari gopal
anil.
28. Output words of the string in sorted order [Output: anil gopal hari ram ramesh
ravi]
29. Find the last word beginning with ‘r’.
30. Reverse every word. For above input mar irah lapog ivar lina hsemar.
31. Find wordwise reverse. For above input ramesh anil ravi gopal hari ram.
Write a program which will read a string (Let string is qwert) and print following
pictures
32. qwert 33. qwert 34. qwertwertertrtt
wert qwer 35. qwweeerrrrttttt
ert qwe
rt qw
t q
Lab-Assignment – 4 Arithmetic
int k;String a;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();k=Integer.parseInt(a);
if (k%2==0) System.out.println(a+" is even");
else System.out.println(a+" is odd");
}
Program reads a number and finds whether it is even or odd. The program does not
work if blanks are left in the beginning or at the end. Hence a=a.trim() should be used.
It removes blanks at the beginning and at the end.
int i;float x,y,k,l;String a,b;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();a=a.trim();
i=a.indexOf(" ");b=a.substring(0,i);x=Float.parseFloat(b);
b=a.substring(i+1);y=Float.parseFloat(b.trim());
k=x+y;l=x*y;System.out.println(k+" "+l);
}
Program reads two numbers and outputs their sum and product. Both numbers are
given in same line.
1. Read a string of digits. Let n be its first digit. Find the number formed by next n
digits. Output double of the number. Input 4773962 output 7739*2=15478.
2. Write program, which reads two numbers. It prints the bigger number first and
smaller later.
3. Write program, which reads a complex number and outputs its modulus. Input
4+3i output 5. [Hint: p=(float)Math.sqrt(q) will find square root of q]
4. Write program, which reads a vector and outputs its magnitude. Input 3i+4j+12k
output 13.
5. Read two vectors and print their dot product. Input 5i+8j+0k and 6i3j+2k output
6.
6. Write program, which behaves in the following manner: Input 12+10 output 22.
Input 12-10 output 2.
7. Read a string. It contains a word and two numbers. The word is one of the
followings: add, sub, mul, and div. The program outputs the sum of given
numbers, if the word is add. If word is sub the program outputs difference and so
on. e.g. input mul 12 19 output 228.
8. Write program, which reads a string. Its first number is either 1 or 2. If it is 1 then
square of second number is returned. If it is 2 then product of 2 nd and 3rd number is
returned. Input 1 12 output 144. Input 2 5 12 output 60.
9. Read a float number and output its double. Do not use parseFloat. Assume
fraction part has exactly two digits. Input 12.34 output 24.68. Input 862.97 output
1725.94.
10. Read a string. It has 2 or 3 numbers. If it has two numbers then output their
product. If it has three numbers then output their sum.
11. Write a program, which reads a number n and prints a string with n x’s. There will
be only one print statement. Input 6 output xxxxxx.
12. Read a string of numbers and find 5th number. Input 6 2 6 4 17 8 9 18 output 17.
13. Read a string of 5 numbers and find their sum. Input 6 403 2 5 7 output 423.
14. Read a string of numbers and find first even number. Input 61 3 6 43 17 8 9 18
output 6.
15. Read a string of numbers and find their sum. Input 6 3 2 5 7 output 23. Input 2 5 3
output 10. The number of numbers in the string is unknown.
16. Write program, which deletes all even numbers from the string. Input 12 17 19 6
17 output 17 19 17. [Caution: all numbers should come in same line]
17. Read a complex number and print it in simplified form. Input 7i+12i+9+4i-8i+13
output 22+15i.
18. Read a string. The first word is a number (say k). The program finds k th word in
remaining string. e.g. input 3 Ram Hari Gopal Om Ravi output Gopal.
19. Write program, which reads an expression and finds its value. Input
(((6+3)*8)(4*3)) output 60.
20. Write a program, which reads number n and n strings. The program outputs the
string, which has the longest length.
21. Write program, which reads a complex number and outputs its modulus. Input
4+3i output 5. Input 4 output 4. Input 3i output 3. Input 4-3i output 5.
22. Read two complex numbers and find their sum. Input 5-7i and 3 output 8-7i.
23. Write program, which will delete maximum number from the string. Assume all
numbers are distinct. Try to do it using only one for loop.
24. Write program for deleting maximum number, when numbers are not distinct. If
maximum number occurs more than once then first occurrence is deleted. Input 12
17 6 13 17 6 17 9 output 12 6 13 17 6 17 9.
25. Write program, which will delete all occurrences of maximum number.
26. The program reads two strings of numbers. In both the numbers are in increasing
order. The program outputs all numbers in increasing order. e.g. if input strings
are 6 9 14 20 22 25 and 11 12 15 16 21 then output is 6 9 11 12 14 15 16 20 21 22
25.
27. Do above problem to find kth word from last. Use only one for.
1. Read a string of numbers. Let these are x 0, x1, x2, … , xn-1. Without using array
find the value of (x0 – (x1 – (x2 ……….. – (xn-4 – (xn-3 – (xn-2 – xn-1))) … )))
Lab-Assignment – 5 Method
import java.io.*;
import java.lang.*;
class f
{ public static String rdstring()
{ String a=””;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();
}
catch(IOException e) {}
return a;
}
public static int second(String a,char e)
{ String b;int p,q;
p=a.indexOf(e);
b=a.substring(p+1);
q=b.indexOf(e);
return(p+q+1);
}
public static String del(String a,int k)
{ String b,c;
b=a.substring(0,k)+a.substring(k+1);
return b;
}
public static String delsec(String a,char e)
{ int p;
p=second(a,e);
return del(a,p);
}
}
class kapil
{ public static void main( String args[])
{ String a,k;int g,m;
a=f.rdstring();m=Integer.parseInt(f.rdstring());
g=f.second(a,’x’);System.out.println(g);
k=f.del(a,m);System.out.println(k);
System.out.println(f.delsec(a,’y’));
}
}
Lab-Assignment – 6 Recursion
import java.io.*;
import java.lang.*;
class f
{ public static String rdstring()
{ String a=””;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();
}
catch(IOException e) {}
return a;
}
public static int loc(String a,char e,int k)
{ String b;int i,j;
if (k==1) return a.indexOf(e);
else{ i=a.indexOf(e);b=a.substring(i+1);
j=loc(b,e,k-1);return(j+i+1); }
}
public static String del(String a,int k)
{ String b,c,d;int i,j;
if (k==0) return a;
else{ i=a.indexOf('x');b=a.substring(i+1);c=a.substring(0,i);
d=del(b,k-1);return(c+d); }
}
}
class kapil
{ public static void main( String args[])
{ String a,k;int g;
a=f.rdstring();g=Integer.parseInt(f.rdstring());
System.out.println(f.loc(a,'x',g));
System.out.println(f.del(a,g));
}
}
The method loc finds the location of kth e in string a. The method del deletes first k
x's.
Define following methods without using any loop.
1. Define method int count(String a, char e). It returns the number of e’s in the string
‘a’. count(“wrtkcrygm”,’r’) will return 2.
2. Define a method String delfirst(String a). It deletes first ‘x’ in string x. Using it
define method to delete (A) first k x’s. (B) all x’s. In them indexOf should not be
used.
3. Define method to return short form. short(“Ram Prasad Kumar Dey”) returns
“R.P.K.Dey”. short(“shyam singh”) returns s.singh.
4. Define method, which returns the string of those words, which has at least one ‘x’.
abc(“ram haxi pxxy wertm xrt”) will return “haxi pxxy xrt”.
5. Define method, which returns the string of second letter of those words whose
first letter is ‘x’. ghi(“xram mhaxi tpxxy xxwertm xgrt”) will return “rxg”.
6. Modify the method “loc” (given in example). It returns -1 if string does not have k
e’s.
7. Define method String subset(String a, String b). It returns “yes” if every letter of
first string is present in second string. It returns “no” otherwise.
8. Define method String present(String a, String b). It returns string of those words
of string ‘a’ whose every letter is present in ‘b’. present(“ram is a good
boy”,”tsoaigkdm”) will return “isagood”. [Hint: use subset].
9. Define method common. It returns “yes” both strings have got some common
letter. common(“hari”,”ram”) returns “yes”. common(“hari”,”som”) returns “no”.
10. Define method to remove duplicates. rd(“hariram”) returns “harim” (or “hiram”).
11. Define method, which returns the location of last ‘x’. If the string does has any ‘x’
then -1 is returned.
12. Define method to delete the last ‘x’. Assume that string has at least one ‘x’.
13. Define method to delete second last ‘x’. Assume that string has at least two x’s.
14. Define method to find the location of kth last x. If the string does not have k x’s
then -1 is returned. kthlast(“ramxttxharixxkapilxravi”,4) will return 6.
15. Define method to find the location of k th last x from last. If the string does not
have k x’s then -1 is returned. kthlast(“ramxttxharixxkapilxravi”,4) will return 17.
16. Define method to find the number of letters after last ‘x’. Assume that string
has at least one ‘x’. [Hint: To find the length of string a.length() may be used
Lab-Assignment – 7 Object
In the definition of followings the use of getx, gety, geta, etc should be minimum.
Care should be taken to choose the class in the definition of following methods.
12. Define faa. If point p is (x,y) then q=point.faa(p) will make q as (x+y,x*y,xy).
13. Define fab. If point p is (x,y) then q=abc.fab(p) will make q as (x+y,x*y,xy).
14. Define faa using fab. In its definition +, * and should not be used.
15. Define fab using faa. In its definition +, * and should not be used.
16. Define fac. If q is (x,y,z) then p=q.fac() will make p as (x+y,y*z).
17. Define fad. If q is (x,y,z) then p.fad(q) will make p as (x+y,y*z).
18. Define fac and fad with the help of each other (without using +, * and ).
19. In class xyz, define methods f, g and h so that following main program outputs
(x,y) (x+y,2x) and (10(x+y)+1,30x+1). In method g only * and in h only + should
be used. No other arithematic operatror should be used in them.
main( ){ xyz a,b; a=new xyz(x,y); a.pt();b=xyz.h(a.f().g());a.pt();b.pt();}
20. Do above problem when in g only *5 and in h only +1 is used.
21. Do above problem without using new in method f.
22. Do above problem without using new in method g.
Lab-Assignment – 8 Copy
import java.io.*;
import java.lang.*;
class complex
{ private float r,i;
public void pt() { System.out.println(r+"+"+i+"i"); }
public void st(float x,float y){ r=x; i=y; }
public complex cpy(){return this;}
public void cqy(complex k) { r=k.r;i=k.i; }
public complex cry()
{ complex c;float x,y;c=new complex();
x=r; y=i;c.st(x,y); or c.cqy(this);
return(c); }
public void aaa(complex a, int b, complex c)
{ a=this;b=12;c.r=r*9; }
}
class hari
{ public static void main( String args[])
{ complex t,s,r,a,b;int k,m;
a=new complex();b=new complex();a.st(5,2);b=a;b.st(7,9);a.pt();
b.pt();
Let us differentiate between copy and assignment. In assignment only pointer is
copied. Hence when b is changed, a is also changed. It does not happen (see below)
when copy is done. The copy can be defined by many ways. The following shows
difference.
Replace b=a by b=a.cpy( ) etc.
Statement a B
b=a 7+9i 7+9i
b=a.cpy( ) 7+9i 7+9i
b.cqy(a) 5+2i 7+9i
b=a.cry( ) 5+2i 7+9i
r=new complex();t=new complex();
s=r;r.st(9,3);t.st(5,7);s=t;s.st(1,2);s.pt();t.pt();r.pt();
Replace s=t by s=t.cpy() etc.
Statement s t r
s=t 1+2i 1+2i 9+3i
s=t.cpy( ) 1+2i 1+2i 9+3i
s.cqy(t) 1+2i 5+7i 1+2i
s=t.cry( ) 1+2i 5+7i 9+3i
s.st(2,3);t.st(2,3);if (s==t) m=0; else m=1;
System.out.println(m);
Even when complex numbers s and t are both 2+3i their comparison shows unequal. It
is because s and t are pointing at different locations. Hence the value of m is 1.
s.st(2,3);t.st(4,5);r.st(6,7);k=231;s.aaa(t,k,r);
s.pt();t.pt();r.pt(); System.out.println(k);
Call to method aaa helps to understand that parameter passing is call by value. t and k
remain unchanged while r is modified. k remains unchanged because b (int) is inbuilt
object. Its value (not pointer) is passed. t remains unchanged because only pointer of
‘a’ is modified. r is changed because contents of object are modified.
}
}
10. In a separate file define class point (in 2 dimensional space, components x and y).
Now define a method to find mid point. p.mid(q) will find p as mid point of p and
q. Define suitable method to print point.
11. In the same file define another class line. It has 3 components a, b and c.
ax+by+c=0 is equation of a line. Define method to find equation of a line.
g.eq(p,q) will find the equation of the line (g) passing through p and q. Define
suitable method to print the equation of line. Let P=(2,3) and Q=(4,7) then line is
2x-y-1=0. Hence a=2 b=1 and c=1. The line may be printed as 2x+-1y+-1=0.
12. Define intersection. p.intersection(g,h) finds the point of intersection of the line g
and h. Input 2x+3y-26=0 and 4x+7y-54=0 output (10,2).
13. Define intersection. p.intersection(a,b,c,d) finds the point of intersection of line
joining points a and b with the line joining points c and d. Use above method. Let
input points be (4,6), (-2,10), (10,2) and (3,6) then the point of intersection is
(10,2).
14. Define distance. k=line.distsance(p,l) finds the distance of the point ‘p’ from the
line ‘l’. e.g. input point (2,3) and line 8x+6y-12=0 distance =
(8*2+6*3-12)/(82+62)1/2 = 2.2.
15. In the same file define another class circle. It has two components c and r. c(point)
is centre of the circle. r(float) is radius of the circle. Define a method to print the
equation of the circle. Let there is a circle (x) whose radius is 7 and centre is (2,3)
then x.print() will print x2+y2-4x-6y-36=0. [It may be printed as x 2+y2+-4x+-6y+-
36=0]
16. Define a method form. a.form(g,h,k) will form a circle whose equation is
x2+y2+gx+hy+k=0. a.form(-4,-6,-36) will make centre and radius of circle ‘a’ as
(2,3) and 7 respectively. Define a method to print the circle. a.pt() will print centre
and radius of the circle ‘a’.
17. Define a method chord. a.chord(b) will return the chord length. Here ‘a’ is a circle
and ‘b’ is a line. If a circle has centre (1,2) and radius 5 and the line is
5x+12y+10z=0 then chord length is 8. [Method: find d=line.distance(c,b) and use
(r2-d2)1/2.]
Ordinary Recursion
public void pt() public void pt()
{ node I; { if(next!=null)
i=this; { System.out.print(data+”
while(i!=null) “);
next.pt();
{ System.out.print(i.data+” “); }
i=i.next; else
}
System.out.println(“ System.out.println(data+” end”);
end”); }
}
public void insertafter(int public void insertafter(int
x,int y) x,int y)
{ node I,j; { if(data==x)
i=this; next=new node(y,next);
while(i.data!=x) else
i=i.next; next.insertafter(x,y);
j=new node(); }
j.data=y;
j.next=i.next;
i.next=j;
}
public void deleteafter(int public void delafter(int x)
x) { if(data==x)
{ node I; next=next.next;
i=this; else
while(i.data!=x) next.delafter(x);
i=i.next; }
i.next=i.next.next;
} public node del(int x)
public node del(int x) { node k;
{ node I; if(next.data==x)
if(data==x) { next=next.next;
return(next); return(this);
else }
{ i=this; else if(data==x)
while(i.next.data! return(next);
=x) else
i=i.next; { k=next.del(x);
i.next=i.next.next; return(this);
return(this); }
} }
}
Lab-Assignment – 10 Exception
import java.io.*;
import java.lang.*;
class xyz
{ public static void main (String args[])
{ String a,b;char c; a=”abc”;
try{ b=a.substring(2,5); System.out.println(b);
c=a.charAt(9);System.out.println(c);
} catch (Exception t){ System.out.println(“The exception is”+t);
}
System.out.println(“Hari”);
}
}
The above program outputs “Hari” irrespective of input string ‘a’. When input is abc or
abcdef then the exception is java.lang.StringIndexOutOfBounds. In case of “abc” no
additional output is produced. In case of “abcdef” output “cde” is produced. When input
is abcedfghijkl then there is no exception. When try-catch is removed then program
terminates when input is abc or abcedf. In case of “abc” no output is produced. In case of
“abcdef” output “cde” is produced. Because of try-catch the impact of exception is felt
only within the block. The normal execution is carried out after that.
class xyz
{
public static void main (String args[])
{ int a,b,c,d,e,f;a=25;b=4;c=0;d=3;
e=a/b;System.out.println(e);
e=a/c;System.out.println(e);
e=a/d;System.out.println(e);
System.out.println(“Hari”);
}
}
The above program terminates after outputting 6.
Class xyz
{
public static void main (String args[])
{ int a,b,c,d,e,f;a=25;b=4;c=0;d=3;
try{
e=a/b;System.out.println(e);
e=a/c;System.out.println(e);
e=a/d;System.out.println(e);
}
catch (ArithmeticException t){System.out.println(“mistake”);}
System.out.println(“Hari”);
}
}
The above program outputs 6 mistake hari
Class xyz
{
public static void main (String args[])
{ int a,b,c,d,e,f;
a=25;b=4;c=0;d=3;
try{e=a/b;System.out.println(e);}
catch (ArithmeticException t){System.out.println(“Error”);}
try{e=a/c;System.out.println(e);}
catch (ArithmeticException t){System.out.println(“Error”);}
try{e=a/d;System.out.println(e);}
catch (ArithmeticException t){System.out.println(“Error”);}
}
}
The above program outputs 6 error and 8.
Class xyz
{ private static int read1()
{ int i=2,j;String a;
try{
DataInputStream o=new DataInputStream(System.in);
a=o.readLine();i=Integer.parseInt(a);}
catch (Exception t){ System.out.println(“Not a number”+t); }
return i;
}
public static void main (String args[])
{ int i,a,f[]={8,12,34,16};
a=xyz.read1();
try
{ System.out.println(f[a]);
i=25/0;
}
catch (Exception t){ System.out.println(“stop”+t);}
/*catch (ArrayIndexOutOfBoundsException t)
{System.out.println(“Illegal Memory reference”+t);}
catch (ArithmeticException t)
{System.out.println(“Wrong Division”+t);}*/
}
}
input 2 Output 34 stop java.lang.ArithmeticException: / by zero
Class xyz
{
public static void main (String args[])
{ int a,b,c,d,e,f; a=25;b=4;c=0;d=3;
try{
e=a/b;System.out.println(e);
e=a/c;System.out.println(e);
e=a/d;System.out.println(e);
}
finally{System.out.println(“Continue”);}
e=a/d;System.out.println(e);
}
}
The above program outputs 6 Continue.
When c=0 is replaced by c=10 then output is 6 2 8 Continue 8.
When “finally” is replaced by “catch(Exception t)” then output is 6 Continue 8 when c is
0.
When “finally” is replaced by “catch(Exception t)” then output is 6 2 8 8 when c is 10.
“Finally” means in case of exception the program will execute the corresponding
statement. The program will terminate after that. In case of “catch exception” the
program continues after that. When exception does not occur then the statement in
finally is executed. But statement is catch exception is not executed.
class kapil
{ public static void main( String args[])
{ int i;float x,y,k,l;String a=””,b;
try
{ DataInputStream o=new DataInputStream(System.in);
a=o.readLine();a=a.trim();
}catch(IOException e){ }
i=a.indexOf(“ “);b=a.substring(0,i);
try{x=Float.parseFloat(b);}catch(Exception e){x=5;}
b=a.substring(i+1);y=Float.parseFloat(b.trim());
k=x+y;l=x*y;System.out.println(k+” “+l);
}
}
Program reads two numbers and outputs their sum and product. If first number is wrong
then it is taken as 5.
k=Integer.parseInt(a);k=k%2;
try{p=”ram”;p=p.substring(k+3);
System.out.println(a+” is an even number”);
}catch(Exception m){System.out.println(a+” is an odd number”);}
Program reads a number and finds whether it is even or odd.
1. Read a string. If it is a number then output its double otherwise output 0. Input 12
output 24. Input 3.9 output 7.8. Input “12 14” output 0. Input ram output 0.
2. Read a number. If it a integer then output its double. If it is a float then output its
triple. Do not use indexOf or if.
3. Read a string. If it is a number then output “AC”. Otherwise output “BC”. You
should use only 3 print statements. Every print statement should print only one letter.
4. Modify above program: in case of number output ABC. Otherwise output “B”. [Hint:
use finally]
5. Read a string. It has 1 or 2 numbers. If it has one number the output its square. If it
has two numbers then output their sum. Do not use if.
6. Read a string. It has 2 or 3 numbers. If it has two numbers then output their product.
If it has three numbers then output their sum. Do not use if.
7. Read a string of two (distinct) integers. Output bigger integer. Do not use “if”.
8. Read a string of two (distinct) numbers (floats). Output bigger number. Do not use
“if”.
9. Read a string of two numbers. Output 1 if first number is bigger. Output 2 if second
number is bigger. Output 0 if they are equal. Do not use “if”.
10. Read a string. If it is a number then output 0. Otherwise let ‘p’ be the 0 th letter. If p is
not an integer then output 1. If p is an integer and size of the string is less than p+1
then output 2. Otherwise if string becomes integer after deleting p th letter then output
3. Otherwise output 4. 157 → 0 r23er → 1 5123a → 2 332a67 → 3 2r7
→ 4 33abc45 → 4.
11. Read a number and output its double. Do not use parseFloat. Assume fraction part
has at most one digits. Input 12.3 output 24.6. Input 218 output 436. Do not use if.
12. Read a string of two numbers (words) and output their sum. If first word is not a
number then it is taken as 5. If second word is not a number then it is taken as 7.
Input 12 34 output 46. Input ram 30 output 35. However if both are not numbers then
output is 100. Do not use if.
13. Write program, to find number of integers in a string. Input rat 12 3.0 34 om output
2.
14. Write program, which reads a string of digits and finds how many digits are more
than 5. Input 2145835769 output 3. Do not use if. Use only
ArrayIndexOutOfBoundsException.
15. Write program, which reads a string of digits and finds how many digits are equal to
5. Input 2145835769 output 2. Do not use if. Use only
ArrayIndexOutOfBoundsException.
16. Write program, which reads a string. It finds how many of them are integers and how
many of them are floats. E.g. Input “2 ram 4 10.3 20 4.78 20 3” output 5,7.
Write following program without using length method, “if” and any loop except
while(1==1).
17. Write program, which reads a string and find its length.
18. Write program, which finds number of words in a string.
19. Given a string of integers, find program to find how many of them are more than 15.
Lab-Assignment – 12 Inheritance
import java.io.*;
import java.lang.*;
class d2vectors {
float i,j;
public d2vectors(float i1,float j1){
i=i1;
j=j1;
}
public float slope(){return (j/i); }
public float magsqr(){return (i*i+j*j);}
public void dble(){i=2*i;j=2*j;}
public void pt(){System.out.println(i+"i+"+j+"j");}
public float geti(){return (i);}
public float getj(){return (j);}
}
class xyz{
public static void main(String ar[])
{
d2vectors a,c;double t;
d3vectors b,d;
b=new d3vectors(6,8,7);
c=new d2vectors(6,7);
t=c.magsqr();System.out.println(t);
t=b.magsqr();System.out.println(t);
t=b.slope();System.out.println(t);
t=b.direction();System.out.println(t);
c.pt();b.pt();
b.dble();b.pt();
b.ttt();b.pt();
}
}
1. Define class stack { private String x[]; int sp; ….put take top print empty size …}
2. Define class queue extends stack{ int front; … take top print empty size ….} Do not
define “put”
3. Define class queue extends stack{ …. put….} Do not define other operations
Lab-Assignment – 13 Interface
import java.io.*;
import java.lang.*;
interface picture {
float area ();
}
class rectangle implements picture
{ float p,q;
public rectangle(float a, float b){p=a;q=b;}
public float area (){ return p*q;}
}
class circle implements picture
{ float r;
public circle(float a){r=a;}
public float area () {return (float)3.14*r*r;}
}
class xyz
{ public static void main( String args[])
{ picture p;float a,b;int i;String s,t,u,v;
try{
DataInputStream o=new DataInputStream(System.in);
s=o.readLine();s=s+" 10 ";
i=s.indexOf(' ');
t=s.substring(0,i);
v=s.substring(i+1);
i=v.indexOf(' ');
u=v.substring(0,i);
s=v.substring(i+1);
i=s.indexOf(' ');
s=s.substring(0,i);
a=Float.parseFloat(u.trim());
b=Float.parseFloat(s);
if (t.compareTo("circle")==0)
p=new circle(a);
else
// if (t.compareTo("rectangle")==0)
p=new rectangle(a,b);
a=p.area();
System.out.println("area="+a);
}
catch (IOException e){ System.out.println(e);}
}
}
Give input circle 4 and rectangle 3 7
1. Define class stack { private String x[]; int sp; ….put take top print empty size …}
2. In same file Define class queue { private x[]; int sp; ….put take top print empty
size …}
3. Write main program which reads a word. If it is “stack” then remaining
operations are according to stack. If it is “queue” then remaining operations are
according to queue.
import java.io.*;
import java.lang.*;
class abc
{ int a;public int b;private int c; int d;
public void set(int p, int q,int r,int s) {a=p;b=q;c=r;d=s;}
protected void pt(){System.out.println(a+" "+b+" "+c+" "+d);}
}
class pqr
{ public static void main(String args[])
{ abc x;
x=new abc();
x.set(2,3,4,5);
x.pt();
System.out.println(x.a+" "+x.b+" "+/*x.c+*/" "+x.d);
//error x.c is not visible
}
}
class xyz extends abc
{ public static void main(String args[])
{ abc x;
x=new abc();
x.set(2,3,4,5);
x.pt();
System.out.println(x.a+" "+x.b+" "+/*x.c+*/" "+x.d);
//error x.c is not visible
}
}
Errors
1. Uninitilized variable
import java.io.*;
import java.lang.*;
class xyz
{ public static void main(String args[])
{ int i,a=4;
if (a>3) i=5;
System.out.println(i);
}
}
Replace a>3 by 4>3 and 2>3 seperately.
Lab-Assignment – 15 Thread
Lab-Assignment – 16 File
import java.io.*;
class hari
{
public static void main(String arguments[])
{
String temp="",fileName="st";
try{
FileReader fr= new FileReader(fileName); open a new file
stream
BufferedReader br= new BufferedReader(fr); wrap it in a
buffer
while((temp=br.readLine())!=null)
System.out.println("> "+temp);
fr.close();
}
catch(Exception e)
{ System.out.println("Error is "+e); }
}
}
The above program reads from file whose name is "st"
1. Write program, which reads 10 numbers from a file and outputs their sum.
2. Write program, which reads a file name (from key board) and in that file writes
ABCD..Z.
3. Write program, which reads a string. The string has a word and a number. Let the
string be “abc 7”. In file abc1 1,2,3,..,10 is written. In file abc2 2,4,6,..,20 is written.
…… In file abc7 7,14,21,..,70 is written. Assume that the number of the string is
less than 7.
4. Define method read(x,y). Here x is a string and y is a number. It returns y th letter
(char) of the file whose name is x. Assume that file x has only one string. Let
contents of a file “abc” are “hariisgood”. The method call t=read(“abc”,6) will make
t=’g’. Call read(“abc”,0) will return h.
5. Define method write(x,y,z). Here x is a string, y is a number and z is a char. It
modifies yth letter of the file (name x) as z. Assume that the file x has only one string.
In the context of above file the system call write(“abc”,4,’m’) will modify the file
contents as “harimsgood”.
6. Define methods move(x), read(), write(y). Here x is a number and y is a letter. All
the methods are in the context of a file whose name is “abc”. The method move(x)
will move the file pointer at xth location. The read() will return the letter pointed by
the file pointer. The method write(y) will write the letter y at position pointed by the
file pointer. Let the contents of file “abc” are “hariisgood” then
move(5);t=read();move(7);write(t) will make the file contents as “hariisgsood”
Lab-Assignment – 17 Graphics
import java.awt.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import java.applet.*;
public class gr extends Applet
{ public void init()
{ setBackground(Color.white);
setForeground(Color.red);
}
public void paint(Graphics g)
{ g.drawRect(10,100,50,70);
g.fillOval(10,100,50,70);
g.drawString("Kapil",50,7);
g.drawLine(100,20,400,70);
g.setColor(Color.blue);
g.drawOval(100,200,50,10);
}
}
In a file whose name is gr.java type this program. Compile it by command javac
gr.java. In a file a.html type following.
<html>
<applet code="gr.java" height=300 width=700>
</applet>
</html>
Now give command appletviewer a.html
g.drawRect(10,100,50,70) draws a rectangle whose north west corner is (10,100) and
sides are 50 and 70.
g.drawOval(10,100,50,70) draws a ellipse inside a rectangle whose north west corner is
(10,100) and sides are 50 and 70.
g.drawLine(100,20,400,70) draws a line joining (100,20) and (400,70).
a. Mouse
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class muse extends Applet implements MouseListener, MouseMotionListener
{ int p,q;
public void init( ){ addMouseListener(this);addMouseMotionListener(this); }
public void mouseClicked(MouseEvent k) { p=k.getX( );q=k.getY( );}
public void mouseEntered(MouseEvent k) {}
public void mouseExited(MouseEvent m) { repaint( ); }
public void mousePressed(MouseEvent n) {}
public void mouseReleased(MouseEvent k){}
public void mouseDragged(MouseEvent p){}
public void mouseMoved(MouseEvent e){}
public void paint(Graphics f){ f.drawOval(p,q,10,10); }
}
When mouse is moved out of applet a circle is displayed. It is at location of last mouse click
int p,q,k;
public void mouseClicked(MouseEvent g) { p=g.getX( );q=g.getY( );k=1;repaint( );}
public void mousePressed(MouseEvent n) { p=n.getX( );q=n.getY( );k=2;repaint( ); }
public void paint(Graphics f)
{ int i; if (k==1) f.drawOval(p,q,10,10); if (k==2) f.drawOval(p,q,100,100); }
When mouse is clicked a small circle is drawn. When it is pressed a big circle is drawn
1. When mouse is clicked a circle (radius 70) is displayed. The center is the place of click.
2. Circle when mouse pressed. Rectangle when mouse released.
3. Circle when mouse released at the place where the mouse was pressed.
4. Line when mouse is released. The end points are places of mouse press and release.
5. Rectangle when mouse is released. The end points are places of mouse press and release.
Assume that location of mouse release is east south of the place of mouse press.
6. Do above problem, when no such assumption is made.
7. Circle when mouse is released. Centre is the place of mouse pressed. The radius is the
distance between mouse pressed and mouse released.
8. Circle when mouse clicked. (A) The location is the place where the mouse was
previously clicked. (B) The location where mouse was clicked two steps back.
9. Line is drawn from the place of mouse pressed to mouse dragged.
10. Line is drawn from the place of mouse pressed to mouse released.
11. All such lines are displayed.
12. Initially a large number of rectangles are displayed. Their north west corners are (5,10i)
i=1..30. Their length and breath are 100 and 8 respectively. When mouse is clicked
inside a rectangle then it disappears.
13. Initially a large number of circles (radius 20) are displayed. Their centers are (5,40i)
i=1..15. When mouse is clicked inside a circle then it disappears.
14. Initially a large number of circles (radius 20) are drawn. Their centers are (0,0),(50,0),
(100,0), ... (500,0),(0,70),(50,70),..(500,70),(100,140),..(500,140),..,(500,700). When
mouse is clicked then nearest circle is removed.
15. Do above problem when a circle disappears when mouse is clicked inside it.
b. Keyboard
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class key extends Applet implements KeyListener
{ String msg= “”;
public void init()
{ addKeyListener(this);requestFocus();}
public void keyPressed(KeyEvent ke)
{ int key=ke.getKeyCode();
if ((key>30)&&(key<122)) msg=msg+(char)key;
switch(key)
{
case KeyEvent.VK_F1:msg=msg.substring(1);break;
case KeyEvent.VK_F2:msg=msg.substring(0,msg.length()-2);break;
case KeyEvent.VK_F3:repaint();break;
case KeyEvent.VK_PAGE_DOWN:msg +=”<pgDn>”;break;
case KeyEvent.VK_PAGE_UP:msg +=”<pgUp>”;break;
case KeyEvent.VK_LEFT:msg +=”<Left Arrow>”;break;
case KeyEvent.VK_RIGHT:msg +=”<right arrow>”;break;
case KeyEvent.VK_ENTER:msg +=’,’;break;
}
}
public void keyReleased(KeyEvent ke)
{System.out.println(msg+ke.getKeyCode());}
public void keyTyped(KeyEvent ke){}
public void paint(Graphics g)
{ String a,b,c;int I,j;
g.drawString(msg,50,10); a=”ttttt”+msg;i=a.length();
if (a.charAt(i-2)==’C’) g.drawOval(50,60,10,20);
}
}
1. Modify above program so that old string vanishes when ENTER is typed.
2. Modify above program so that output is updated after typing every letter.
3. When circle is typed then a circle is drawn.
4. When “circle 10” is typed then a circle of radius 10 is drawn.
5. When “circle 30 40 10” is typed then a circle of centre (30,40) and radius 10 is drawn.
6. When “circle red” is typed then a circle of red color is drawn.
7. When circle is typed then circle is drawn. When rectangle is typed then rectangle is
drawn. And so on. Also specify their parameters.
8. When F1 is pressed a circle is drawn. When F2 is pressed a rectangle is displayed.