You are on page 1of 42

# MCSL 025 Java lab manual solved

Session 1: Data types, variables and operators Exercise 1: Write a program in Java to implement the formula (Area = Height Width) to find the area of a rectangle. Where Height and Width are the rectangles height and width.
//java program to find area of rectangle class AreaOfRectangle { public static void main(String args[]) { double h=12.0,w=5.0; double area=(h*w); System.out.println("The area of a rectangle is" +area); } }

Exercise 2: Write a program in Java to find the result of following expression (Assume a = 10, b = 5) i) (a < < 2) + (b > > 2) ii) (a) | | (b > 0) iii) (a + b 100) / 10 iv) a & b
//Java program to show arthemetic, logic & relational operations class expessionresult { public static void main(String args[]) { int a=10, b=5; System.out.println("the result of expression 1 is:"+((a < < 2) + (b > > 2))); System.out.println("the result of expression 2 is:"+((a) | | (b > 0))); System.out.println(("the result of expression 3 is:"+(a + b *100) / 10)); System.out.println("the result of expression 4 is:"+(a & b)); } }

Exercise 3: Write a program in Java to explain the use of break and continue statements.
1

//Java program to explain break and continue statements class BreakContinue { public static void main(String args[]) { int i=0; System.out.println("This is to illustrate break statement"); while(i<100) { if(i==10) break; System.out.println("i:"+i); i++; } System.out.println("Loop complete"); System.out.println("This is to illustrate continue statement");outer: for(i=0;i<10;i++) { for(int j=0;j<10;j++) { if (j>i) { System.out.println(); continue outer; } System.out.println(" "+(i*j)); } } System.out.println(); } }

Exercise 4: Write a program in Java to find the average of marks you obtained in your 10+2 class.
//Java program to find average marks class Avg { public static void main (String args[]){ int i, j, marks, total, sumofmarks=0, sumoftotal=0; System.out.println("enter marks of i's year:"); for(i=0;i<8;i++) { System.out.println("enter marks obainted for subject" +i) integer.parse(marks); sumofmarks=sumofmarks+marks; System.out.println("enter total marks for subject" +i) integer.parse(total); sumoftotal=sumoftotal+total; } 2

System.out.println("enter marks of 2nd year:"); for(j=0;j<8;j++) { System.out.println("enter marks obainted for subject" +j) integer.parse(marks); sumofmarks=sumofmarks+marks; System.out.println("enter total marks for subject" +j) integer.parse(total); sumoftotal=sumoftotal+total; } int avg=sumofmarks/sumoftotal * 100; System.out.println("The average of four subjects:"+avg); }

Session 2: Statements and array Exercise1: Write a program in Java to find AB where A is a matrix of 33 and B is a matrix of 34. Take the values in matrixes A and B from the user.
//Java program to find multiplication of matrices import java.io.*; public class Matrixmultiplication { public static int readInt() throws IOException { BufferedReader b =new BufferedReader(new InputStreamReader(System.in)); int i=Integer.parseInt(b.readLine()); return i; } public static void main(String args[]) throws IOException { int m1[][]=new int[2][3]; int m2[][]=new int[3][2]; int m3[][]=new int[2][2]; System.out.println("Enter the 6 numbers"); for(int i=0;i<2;i++) for(int j=0;j<3;j++) m1[i][j]=readInt(); for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { System.out.print("\t "+m1[i][j]); } System.out.println(); } 3

System.out.println("Enter the 6 numbers"); for(int i=0;i<3;i++) for(int j=0;j<2;j++) m2[i][j]=readInt(); for(int i=0;i<3;i++){ for(int j=0;j<2;j++){ System.out.print("\t "+m2[i][j]); } System.out.println(); } for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { m3[i][j]=0; for(int k=0;k<3;k++) m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j]; } } System.out.println("The product of two matrices is:"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { System.out.print("\t "+m3[i][j]); } System.out.println(); } } }

Exercise 2: Write a program in Java to compute the sum of the digits of a given integer. Remember, your integer should not be less than the five digits. (e.g., if input is 23451 then sum of the digits of 23451will be 15)
//Java program to find sum of digits of integer iimport java.io.*; class Sumdigits { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str; int num,rem; int sum=0; System.out.println("Enter a 5 digit number"); str=br.readLine(); 4

## num=Integer.parseInt(str); while(num>0){ rem=num%10; sum=sum+rem; num=num/10; } System.out.println("The sum of the digits"+sum); } }

Session 3: Class and Objects Exercise 1: Write a program in Java with class Rectangle with the data fields width, length, area and colour. The length, width and area are of double type and colour is of string type .The methods are set_ length () , set_width (), set_ colour(), and find_ area (). Create two object of Rectangle and compare their area and colour. If area andcolor both are the same for the objects then display Matching Rectangles, otherwise display Non matching Rectangle.
//Java program to create objects of a class class Rect { double width,length,area; String colour; void set_length(double x) { length=x; } void set_width(double y) { width=y; } String set_colour(String z) { colour=z; return colour; } double find_area() { area=length*width; System.out.println("Area of rectangle="+area); return area; } } class Rectangle 5

{ public static void main(String args[]) { double area1, area2; String st1,st2; Rect r1=new Rect(); Rect r2=new Rect(); r1.set_length(5.0); r1.set_width(6.0); st1=r1.set_colour("blue"); area1=r1.find_area(); r2.set_length(5.0); r2.set_width(6.0); st2=r2.set_colour("green"); area2=r2.find_area(); if ((area1==area2) && st1.equals(st2)) { System.out.println("Matching rectangles"); } else { System.out.println("Non matching rectangles"); } }

Exercise 2: Create a class Account with two overloaded constructors. The first constructor is used for initializing, the name of account holder, the account number and the initial amount in the account. The second constructor is used for initializing the name of the account holder, the account number, the addresses, the type of account and the current balance. The Account class is having methods Deposit (), Withdraw (), and Get_Balance(). Make the necessary assumption for data members and return types of the methods. Create objects of Account class and use them Exercise 3: Write a program in Java to create a stack class of variable size with push() and pop () methods. Create two objects of stack with 10 data items in both. Compare the top elements of both stack and print the comparison result.>

Session 4: Inheritance and polymorphism Exercise 1: Write a Java program to show that private member of a super class cannot be accessed from derived classes.
/Java program to show private member of super class //create a super class class A { 6

int i; private int j; void setij(int x,int y) { i=x; j=y; } } //sub class class B extends A { int total; void sum() { total=i+j; } }

Exercise 2: Write a program in Java to create a Player class. Inherit the classes Cricket _Player, Football _Player and Hockey_ Player from Player class.
//Java program to show inheritance //class foot ball paler and class cricket player inerited from player class class Player { String name; Player(String nm) { name=nm; } } class Cricket_player extends Player { Cricket_player(String nm) { super(nm); } void play() { System.out.println("play cricket:"+name); } } class Football_player extends Player { Football_player(String nm) { 7

super(nm); } void play() { System.out.println("play Football:"+name); } } class Hockey_player extends Player { Hockey_player(String nm) { super(nm); } void play() { System.out.println("play hockey:"+name); } } class Player1 { public static void main(String args[]) { Cricket_player c=new Cricket_player("sachin tendulkar"); Football_player f=new Football_player("peley"); Hockey_player h=new Hockey_player("Helen mary"); c.play(); f.play(); h.play(); } }

Exercise 3: Write a class Worker and derive classes DailyWorker and SalariedWorker from it. Every worker has a name and a salary rate. Write method ComPay (int hours) to compute the week pay of every worker. A Daily Worker is paid on the basis of the number of days s/he works. The Salaried Worker gets paid the wage for 40 hours a week no matter what the actual hours are. Test this program to calculate the pay of workers. You are expected to use the concept of polymorphism to write this program.
//Java program to show polymorphism abstract class worker { String name; double sal_rate; worker(String nm,double sr); { name=nm; 8

sal_rate=sr; } abstract void compay() } class Daily_worker extends worker { int days_worked; Daily_worker(String nm,double sr,int dw) { super(nm,sr); days_worked=dw; } void compay() { double pay=(days_worked*sal_rate) System.out.println("\t Name:"+name+ "\tsalary per day"+sal_rate+"\tpay per week"+pay); } } class Salaried_worker extends worker { Daily_worker(String nm,double sr) { super(nm,sr); } void compay() { double pay=(40*sal_rate) System.out.println("\t Name:"+name+ "\tsalary per hour"+sal_rate+"\tpay per week"+pay); } }

Exercise 4: Consider the trunk calls of a telephone exchange. A trunk call can be ordinary, urgent or lightning. The charges depend on the duration and the type of the call. Writ a program using the concept of polymorphism in Java to calculate the charges.
//Java program to show implementation of interface import java.io.*; interface student { void disp_grade(); void disp_attendance(); 9

## pg.disp(); ug_stud ug=new ug_stud(); ug.read(); ug.disp(); } }

Session 5: Package and Interface Exercise 1: Write a program to make a package Balance in which has Account class with Display_Balance method in it. Import Balance package in another program to access Display_Balance method of Account class. //Java program to import package to access method in it class AccessPackMethod { public static void main(String ar[]) { try { balance.account a=new balance.account(); a.read(); a.disp(); } catch(Exception e) { System.out.println(e); } } } package balance; import java.io.*; public class account { long acc,bal; String name; public void read()throws Exception { DataInputStream in=new DataInputStream(System.in); System.out.println("Enter the name :"); name=in.readLine(); System.out.println("Enter the account number:"); acc=Long.parseLong(in.readLine()); System.out.println("Enter the account balance:"); bal=Long.parseLong(in.readLine());}public void disp()
12

{ System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("--- Account Details ---"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("Name :"+name); System.out.println("Account number :"+acc); System.out.println("Balance :"+bal); } } Exercise 2: Write a program in Java to show the usefulness of Interfaces as a place to keep constant value of the program.
//Java program to show usefulness of interfaces interface area { static final float pi=3.142f; float compute(float x,float y); } class rectangle implements area { public float compute(float x,float y) { return(x*y);} } class circle implements area { public float compute(float x,float y) { return(pi*x*x);} } class Iterfaceusefulness { public static void main(String args[]) { rectangle rect=new rectangle(); circle cr=new circle(); area ar; ar=rect; System.out.println("Area of the rectangle= "+ar.compute(10,20)); 13

## ar=cr; System.out.println("Area of the circle= "+ar.compute(10,0)); } }

Exercise 3: Create an Interface having two methods division and modules. Create a class, which overrides these methods.

System.out.println(" MARK LIST OF UG STUDENTS"); System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.out.println("Register No :"+reg); System.out.println("Name:"+name); System.out.println("Mark1 :"+m1); System.out.println("Mark2 :"+m2); System.out.println("Mark3 :"+m3); disp_grade(); disp_attendance(); } } class studentInterface { public static void main(String args[])throws Exception { pg_stud pg=new pg_stud(); pg.read(); pg.disp(); ug_stud ug=new ug_stud(); ug.read(); ug.disp(); } }

Exercise 4: Write a program in Java which implements interface Student which has two methods Display_Grade and Atrendance for PG_Students and UG_Students (PG_Students and UG_Students are two different classes for Post Graduate and Under Graduate students respectively).
//Java program to show implementation of interface import java.io.*; interface student { void disp_grade(); void disp_attendance(); } class pg_stud implements student { String name,grade; int reg,m1,m2,m3,att; void read()throws Exception { DataInputStream in= new DataInputStream(System.in); System.out.println("enter the register no : "); reg=Integer.parseInt(in.readLine()); System.out.println("enter the name : "); name=in.readLine(); System.out.println("enter attendance : "); 16

Session 6: Exception Handling Exercise 1: Write a program in Java to display the names and roll numbers of students. Initialize respective array variables for
18

10 students. Handle ArrayIndexOutOfBoundsExeption, so that any such problem doesnt cause illegal termination of program.

int no=0; student s=new student(); try { DataInputStream in= new DataInputStream(System.in); System.out.println("enter the number of students : ");no=Integer.parseInt(in.readLine()); for(int i=0;i<no;i++); s.read(); }catch(ArrayIndexOutOfBoundsException e) { System.out.println("the maximum students should be ten\n");no=10;} catch(Exception e) { System.out.println(e); } for(int i=0;i<no;i++); s.disp(); } }

Exercise 2: Write a Java program to enable the user to handle any chance of divide by zero exception.
//Java program to show DivideByZero excepion public class DivideByzero {. public static void main(String args[]) { int b=100,res=0; int a[]={0,1,2,5,0,25,0,50,0}; for (int i=0;i<9;i++) { try { res=res+(b/a[i]); System.out.println(" "+res); } catch (ArithmeticException e) { a[i]=1; } } } }

20

## exception if operand is non-numeric in calculating modules. (Use command line arguments).

//Java program to show NumberFormat excepion public class EXceptionnonnumeric { public static void main(String args[]) { int sum=0; int invalid=0; for(int i=0;i<args.length;i++) { try { sum+=Integer.parseInt(args[i]); } catch(NumberFormatException e) { invalid++; } } System.out.println("Total number of arguments:"+args.length); System.out.println("Invalid numbers:"+invalid); System.out.println("Sum:"+sum); }

Exercise 4: On a single track two vehicles are running. As vehicles are going in same direction there is no problem. If the vehicles are running in different direction there is a chance of collision. To avoid collisions write a Java program using exception handling. You are free to make necessary assumptions.
//Java program to avoid vehicle collision import java.io.*; class collision extends Exception { collision(String s) { super(s); } } class TwoVehicles { 21

public static void main(String ar[]) { String t1=null,t2=null; try { DataInputStream in= new DataInputStream(System.in); System.out.println("enter the direction of vehicle1:(left/right):"); t1=in.readLine(); System.out.println("enter the direction of vehicle2:(left/right):"); t2=in.readLine(); if(!t1.equals(t2)) throw new collision("truck2 has to go on "+ t1 +" direction"); } catch(collision e) { System.out.println(e); t2=t1; System.out.println("the collision has been avoided by redirection truck2"); } catch(Exception e) { System.out.println(e); } System.out.println("direction of truck1 :"+t1); System.out.println("direction of truck2 :"+t2); } }

Session 7: Multithreading Exercise 1: Write a Java program to create five threads with different priorities. Send two threads of the highest priority to sleep state. Check the aliveness of the threads and mark which thread is long lasting.

T4.setPriority(5); T5.setPriority(8); T1.sleep(1500); if (T1.isAlive()) System.out.println("Thread 1 is alive"); else System.out.println("Thread 1 is not alive"); T2.start(); if (T2.isAlive()) System.out.println("Thread 2 is alive"); else System.out.println("Thread 2 is not alive"); T3.sleep(1000); if (T3.isAlive()) System.out.println("Thread 3 is alive"); else System.out.println("Thread 3 is not alive"); T4.start(); if (T4.isAlive()) System.out.println("Thread 4 is alive"); else System.out.println("Thread 4 is not alive"); T5.start(); if (T5.isAlive()) System.out.println("Thread 5 is alive"); else System.out.println("Thread 5 is not alive"); } }

Exercise 2: Write a program to launch 10 threads. Each thread increments a counter variable. Run the program with synchronization.
//Java program to launch multiple threads and count them class ThreadSyncronisation { public static void main(String arg[])throws Exception {data d1=new data(); data d2=new data(); data d3=new data(); data d4=new data(); data d5=new data(); data d6=new data(); data d7=new data(); data d8=new data(); data d9=new data(); data d10=new data(); System.out.println(d10.count); } 23

} class item { static int count=0; } class data extends item implements Runnable { item d=this; Thread t; data() { t=new Thread(this); t.start(); } public void run() { d=syn.increment(d); } } class syn { synchronized static item increment(item i) { i.count++; return(i); } }

Exercise 3: Write a program for generating 2 threads, one for printing even numbers and the other for printing odd numbers.
//Java program to generate two threads one for counting even numbers & other for counting odd numbers class even extends Thread { Thread t=null; even() {t=new Thread(this); start(); } public void run() {try{for(int i=2;i<50;i+=2) System.out.print(i+" "); Thread.sleep(100); } catch(Exception e) {System.out.println("thread interepted");} } } 24

class odd extends Thread { Thread t=null; odd() { t=new Thread(this); start(); } public void run() {try{for(int i=1;i<50;i+=2) System.out.print(i+" "); Thread.sleep(100); } catch(Exception e) {System.out.println("thread interepted");} } } class ThreadEvenOdd { public static void main(String arg[]) { even e=new even(); odd o=new odd(); } }

Exercise 4: Write a Java program using thread synchronization in multithreading (You can take some objects visible on screen for real time effect).
//Java program to show thread synchronization import java.io.*; class read { static String get(String x) { String n=null; try { DataInputStream in = new DataInputStream(System.in); System.out.println(x); n=in.readLine(); System.out.flush(); } catch(Exception e) { System.out.println("i/o stream error"); } return(n); 25

}} class s07_04 { public static void main(String arg[]) { try { stud s1=new stud(); stud s2=new stud(); } catch(Exception e) { System.out.println("i/o stream error"); }}} class st { String name; int code,m1,m2,m3,tt; float avg; } class stud extends st implements Runnable { st data=this; Thread t; stud() { t=new Thread(this); t.start(); } public void run() { try { data=sy.r(data); t.sleep(100); data=sy.sum(data); t.sleep(100); sy.p(data); t.sleep(100); } catch(Exception e) { System.out.println("interrupted"); }}} class sy { synchronized static st r(st e) { System.out.println("sychronized fountion read() "); e.name=read.get("enter the name:"); e.code=Integer.parseInt(read.get("enter the regno:")); e.m1=Integer.parseInt(read.get("enter mark1:")); 26

e.m2=Integer.parseInt(read.get("enter mark2:")); e.m3=Integer.parseInt(read.get("enter mark3:")); return(e); } synchronized static void p(st x) { System.out.println("no :"+x.code);System.out.println("name :"+x.name);System.out.println("mark1 :"+x.m1);System.out.println("mark2 :"+x.m2);System.out.println("mark3 :"+x.m3);System.out.println("avg :"+x.avg);System.out.println("total :"+x.tt);}synchronized static st sum(st z) { System.out.println("synchronized sum() ");z.tt=z.m1+z.m2+z.m3; z.avg=(z.tt)/3; return(z); }}

Session 8: Reading, Writing and String handling in Java Exercise 1: Writ a program in Java to create a String object. Initialize this object with your name. Find the length of your name using the appropriate String method. Find whether the character a is in your name or not; if yes find the number of times a appears in your name. Print locations of occurrences of a .Try the same for different String objects.
// Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good. import java.applet.*; import java.awt.*; import java.awt.event.*; public class s09_01 extends Applet implements ActionListener { public void init() { label1 = new Label(); label2 = new Label(); label3 = new Label(); t1 = new TextField(); t2 = new TextField(); t3 = new TextField(); b1 = new Button(); setLayout(null); setBackground(new Color(0, 153, 102)); label1.setAlignment(Label.RIGHT); label1.setText("Name"); add(label1); 27

label1.setBounds(140, 60, 50, 20); label2.setAlignment(Label.RIGHT); label2.setText("Address"); add(label2); label2.setBounds(140, 90, 50, 20); label3.setAlignment(Label.RIGHT); label3.setText("Total length"); add(label3); label3.setBounds(130, 120, 60, 20); add(t1); t1.setBounds(200, 60, 100, 20); add(t2); t2.setBounds(200, 90, 100, 20); add(t3); t3.setBounds(200, 120, 100, 20); b1.setBackground(new Color(255, 204, 153)); b1.setLabel("Total"); b1.addActionListener(this); add(b1); b1.setBounds(150, 180, 80, 24); } public void actionPerformed(ActionEvent ae) { int a=t1.getText().length(); a+=t2.getText().length(); t3.setText(Integer.toString(a)); }Label label1; Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1; } <html> <body> <applet code="s09_01.class" width=400 height=400> </applet> </body> </html>

Exercise 2: 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.
//Java program read string from console and display uppercase in console class ReadWriteConsole 28

{ public static void main(String a[]) throws IOException { DataInputStream in=new DataInputStream(System.in); System.out.println("Enter file Statement:"); String s1=in.readLine(); System.out.println(s1.toUpperCase()); } }

Exercise 3: Write a program for searching strings for the first occurrence of a character or substring and for the last occurrence of a character or substring.
//Java program find first and last occurance of character substring in string import java.io.*; class FirstLastOccuranceChar { public static void main(String[]args) throws Exception { int len1,len2,last=0; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter the string:"); String s1=in.readLine(); System.out.println("Enter searching string:"); String s2=in.readLine(); len1=s1.length();len2=s2.length(); for(int i=0;i<=(len1-len2);i++) { if(s1.substring(i,len2+i).equals(s2)) { if(last==0) System.out.println("first occurance is at position:"+(i+1)); last=i+1; }} if(last!=0) System.out.println("last occurance is at position :"+last); else System.out.println("the string is not found"); }}

Exercise 4: Write a program in Java to read a statement from console, convert it into upper case and again print on console.
//Java program read string from console and display uppercase in console class ReadWriteConsole { public static void main(String a[]) throws IOException 29

## { DataInputStream in=new DataInputStream(System.in); System.out.println("Enter file Statement:"); String s1=in.readLine(); System.out.println(s1.toUpperCase()); } }

Exercise 5: Write a program in Java, which takes the name of a file from user, read the contents of the file and display it on the console.
//Java program to find file name from console and display contents on console class ReadWriteConsole { public static void main(String a[]) throws IOException { DataInputStream in=new DataInputStream(System.in); System.out.println("Enter file Statement:"); String s1=in.readLine(); FileInputStream fis=null; try{ fis=new FileInputStream(s1); byte ch; while((ch=(byte)fis.read())!=-1) { System.out.print((char)ch); } } catch(IOException e) { System.out.println("interrupted");} finally { try { fis.close();} catch(IOException e) { System.out.println("error in closing");} } } } }

## Exercise 6: Write a Java program to copy a file into another file.

30

//Java program to copy a fle to another file class FileCopy { public static void main(String a[]) throws IOException { int d=0; FileInputStream fi=null; FileOutputStream fo=null; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter file name:"); String s1=in.readLine(); System.out.println("Enter new file name:"); String s2=in.readLine(); try { fi=new FileInputStream(s1); fo=new FileOutputStream(s2); System.out.println("Copying file"); while((d=fi.read())!=-1) fo.write((byte)d); System.out.println("File copyied"); } catch(IOException e){System.out.println(e);} }}

Session 9: Applets and its applications Exercise 1: Write a Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good.
// Java Applet program which reads your name and address in different text fields and when a button named find is pressed the sum of the length of characters in name and address is displayed in another text field. Use appropriate colors, layout to make your applet look good. import java.applet.*; import java.awt.*; import java.awt.event.*; public class s09_01 extends Applet implements ActionListener { public void init() { label1 = new Label(); label2 = new Label(); label3 = new Label(); 31

t1 = new TextField(); t2 = new TextField(); t3 = new TextField(); b1 = new Button(); setLayout(null); setBackground(new Color(0, 153, 102)); label1.setAlignment(Label.RIGHT); label1.setText("Name"); add(label1); label1.setBounds(140, 60, 50, 20); label2.setAlignment(Label.RIGHT); label2.setText("Address"); add(label2); label2.setBounds(140, 90, 50, 20); label3.setAlignment(Label.RIGHT); label3.setText("Total length"); add(label3); label3.setBounds(130, 120, 60, 20); add(t1); t1.setBounds(200, 60, 100, 20); add(t2); t2.setBounds(200, 90, 100, 20); add(t3); t3.setBounds(200, 120, 100, 20); b1.setBackground(new Color(255, 204, 153)); b1.setLabel("Total"); b1.addActionListener(this); add(b1); b1.setBounds(150, 180, 80, 24); } public void actionPerformed(ActionEvent ae) { int a=t1.getText().length(); a+=t2.getText().length(); t3.setText(Integer.toString(a)); }Label label1; Label label2; Label label3; TextField t1; TextField t2; TextField t3; Button b1; } <html> <body> <applet code="s09_01.class" width=400 height=400> </applet> </body> </html>

Exercise 2: Create an applet which displays a rectangle/string with specified colour & coordinate passed as parameter from the HTML file.
32

// Java Applet to display rectangle or string in specified color import java.applet.*; import java.awt.*; import java.awt.event.*; public class Applet2 extends Applet implements ActionListener { public void init() {setLayout(null); setBackground(new Color(0,10,100)); } public void paint(Graphics p) {String t=null; int x,y,w,h,r,g,b; t=getParameter("xx"); x=Integer.parseInt(t); t=getParameter("yy"); y=Integer.parseInt(t); t=getParameter("ww"); w=Integer.parseInt(t); t=getParameter("hh"); h=Integer.parseInt(t); t=getParameter("rr"); r=Integer.parseInt(t); t=getParameter("gg"); g=Integer.parseInt(t); t=getParameter("bb"); b=Integer.parseInt(t); p.setColor(new Color(r,g,b)); p.fillRect(x,y,w,h); } } <html> <body> <applet code="s09_02.class" width=400 height=400> <param name="xx" value="25"> <param name="yy" value="25"> <param name="ww" value="150"> <param name="hh" value="150"> <param name="rr" value="0"> <param name="gg" value="150"> <param name="bb" value="100"> </applet> </body> </html>

Exercise 3: Create an applet which will display the calendar of a given date.
//Java applet to read text and display calander of a given date 33

import java.util.*; import java.awt.*; import java.applet.*; public class DisplayCalander extends Applet { GregorianCalendar cal=new GregorianCalendar(); String s,s1,s2,s3,s4; int a=0,b=0,c=0,d=0; public void start(){s=getParameter("fg"); s1=getParameter("as"); s2=getParameter("as1"); s3=getParameter("as2"); s4=getParameter("as3"); a=Integer.parseInt(s1); b=Integer.parseInt(s2); c=Integer.parseInt(s3); d=Integer.parseInt(s4); } public void init() { } public void paint(Graphics g) { if(s.equals("red"))g.setColor(Color.red);g.drawRect(a,b,c,d); g.drawString("Color = "+"",25,25); g.drawString("Calendar is"+cal.DATE+"/"+cal.MONTH+"/"+cal.YEAR,34,36); } } <html> <body> <applet code="DisplayCalander.class" width=400 height=400> </applet> </body> </html>

## Exercise 4: Write a program to store students detail using Card Layout.

Exercise 5: Write a Java Applet program, which provides a text area with horizontal and vertical scrollbars. Type some lines of text in the text area and use scrollbars for movements in the text area. Read a word in a text field and find whether the word is in the content of the text area or not.

34

Session 10: Networking and other advanced feature and JAVA Exercise 1: Write a Java program to find the numeric address of the following web sites i. www.ignou.ac.in ii. www.indiatimes.com iii. www.rediff.com iv. www.apple.com In addition to this, find the Internet Address of your local host.
//Java program to find numeric network address for sites import java.net.*; class findnetworkaddress { public static void main(String ar[])throws Exception { InetAddress a=InetAddress.getLocalHost(); System.out.println("The Local Host IP:"+a); a=InetAddress.getByName("www.ignou.ac.in"); System.out.println("The IP of www.ignou.ac.in :"+a); a=InetAddress.getByName("www.indiatimes.com"); System.out.println("The IP of www.indiatimes.com :"+a); a=InetAddress.getByName("www.apple.com"); System.out.println("The IP of www.apple.com :"+a); InetAddress s[]=InetAddress.getAllByName("www.rediff.com"); for(int i=0;i<s.length;i++) System.out.println("The IP of www.rediff.com :"+s[i]); } }

Exercise 2: Create an applet which takes name and age as parameters and display the message <name> is <age> year old.. Print the URL of the class file.

//Java program to accept name age and display message and url of class import java.applet.*; import java.awt.*; import java.awt.event.*; public class NameAgeApplet extends Applet { public void init() 35

{ Font f=new Font("adobe-courier",Font.PLAIN,18); setFont(f); setLayout(null); setForeground(Color.green); setBackground(new Color(200,0,200)); } public void paint(Graphics g) {String n,a,msg; n=getParameter("name"); a=getParameter("age"); msg=n+" is "+a+" year old. "; g.drawString(msg,25,25); } }

Exercise 3: Write a program to test Socket functionality for appropriate hostname and port number. //Java program to test socket functionality for host name port number public class SocketfunctionalityTest { public static final short TIME_PORT = 13; public static void main(String[] args) throws IOException { String hostName = args.length == 0 ? "localhost" : args[0]; System.out.println(); try { // -------------------------------------// Open a socket // -------------------------------------Socket serverSocket = new Socket(hostName, TIME_PORT); System.out.println("-------------------------"); System.out.println("Server Socket Information"); System.out.println("-------------------------"); System.out.println("serverSocket : " + serverSocket); System.out.println("Keep Alive : " + serverSocket.getKeepAlive()); System.out.println("Receive Buffer Size : " + serverSocket.getReceiveBufferSize()); System.out.println("Send Buffer Size : " + serverSocket.getSendBufferSize()); System.out.println("Is Socket Bound? : " + serverSocket.isBound()); System.out.println("Is Socket Connected? : " + serverSocket.isConnected()); System.out.println("Is Socket Closed? : " + serverSocket.isClosed());
36

37