You are on page 1of 61

INDEX

S. N o 1 Programs 1 a) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions. 1 b) The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. 2 a) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer. Page no.

3 4 5

6 7 8 9

10 11 12

13

14 15

16

2 b) Write a Java program to multiply two given matrices. 2 c) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (Use StringTokenizer class of java.util) 3. Write a java program to find both the Largest and Smallest number in a list of Integers 4 Write a Java program that implements the Sieve of Eratosthenes to find prime numbers 5. Write a java program to sort a list of names in ascending order 6. Write a Java program to implement the matrix ADT using a class. The operations supported by this ADT are: a) Reading a matrix. c) Addition of matrices. b) Printing a matrix. d) Subtraction of matrices. e) Multiplication of matrices. 7 Write a java program to solve Tower's of Hanoi problem 8 Write a java program that uses a recursive to compute ncr Note: n and r values are given 9 Write a java program to perform the following operations a) Concatenation of two strings b) Comparision of two strings 10 Implement the complex number ADT in Java using a class. The complex ADT is used to represent complex numbers of the form c=a+ib, where a and b are real numbers. The operations supported by this ADT are: a) Reading a complex number. d) Subtraction of complex numbers. b) Writing a complex number. e) Multiplication of complex numbers. c) Addition of Complex numbers.f) Division of complex numbers. 11 Write a Java program that makes frequency count of letters in a given text. 12 Write a Java program that uses functions to perform the following operations : a) Inserting a sub-string in to the given main string from a given position. b) Deleting n characters from a given position in a given string. 13 a) Write a Java program that checks whether a given string is a

17 18

19

20

21

22 24

25

26

27

palindrome or not. Ex: MADAM is a palindrome. 13 b) Write a Java program to make frequency count of words in a given text. 15 .a) Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. c) Write a Java program that displays the number of characters, lines and words in a text file. d) Write a Java program to change a specific character in a file. Note: Filename , number of the byte in the file to be changed and the new character are specified on the command line. 16. Write a Java program that: i) Implements stack ADT. ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression. 17. a) Develop an applet in Java that displays a simple message. b) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named Compute is clicked 18. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result 19. Write a Java program for handling mouse events 20. a) Write a Java program that creates three threads. First thread displays Good Morning every one second, the second thread displays Hello every two seconds and the third thread displays Welcome every three seconds. b) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication 21. Write a Java program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box 22. Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net 23. a) Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts. 2

28

30

31 32

33

34

b) Write a Java program that allows the user to draw lines, rectangles and ovals 24. a) Write a Java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures 24. b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java program to display the table using Jtable component 25. Write a Java program that illustrates the following a) Creation of simple package. b) Accessing a package 26. Write Java programs that illustrates the following a) Handling predefined exceptions b) Handling user defined exceptions 27. Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods: a) Linear search b) Binary search 33. Write Java programs for implementing the following sorting methods: a) Bubble sort b) Selection sort c) Insertion sort d) Quick sort

/* 1 a) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions. */ import java.util.Scanner; public class QuadraticDemo { public static void main(String args[]) { Scanner in=new Scanner(System.in); double a,b,c,root1,root2; System.out.println("\nGive a value"); a=in.nextDouble(); System.out.println("\nGive b value"); b=in.nextDouble(); System.out.println("\nGive c value"); c=in.nextDouble(); if((b*b-4*a*c)==0) { System.out.println("\n ROOTS ARE EQUAL"); root1=-b/(2*a); System.out.println("\n root "+root1); } if((b*b-4*a*c) > 0) { root1=-b+Math.sqrt(b*b-4*a*c)/(2*a); root2=-b-Math.sqrt(b*b-4*a*c)/(2*a); System.out.println("\nROOTS ARE REAL:\n"); System.out.println("\n root1 "+root1+"\n root2 "+root2); } else System.out.println("\n Imaginary Roots."+" There are no real solution"); } } // End of Class Output: Give a value 3 Give b value 4 Give c value 4

2 Imaginary Roots. There are no real solution Give a value 3 Give b value 6 Give c value 2 ROOTS ARE REAL: root1 -5.422649730810374 root2 -6.577350269189626 /* 1:
b) The Fibonacci sequence is defined by the following rule: The fist two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non recursivefunctions to print the nth value in the Fibonacci sequence.. */

import java.util.Scanner; class FeboDemo { static void febo(int n) { int f1,f2,f3; f1=f2=1; f3=0; for(int i=1;i<=n;i++) { f3=f1+f2; f1=f2; f2=f3; } System.out.printf("%dth value of febonacco sequence is %d",n,f3); } static int feboRec(int n) { if (n <= 2) { return 1; } else return (feboRec(n-2) + feboRec(n-1)); } public static void main(String[] args)

{ int t=0; Scanner in=new Scanner(System.in); System.out.println("Enter n Value\n"); int n=in.nextInt(); System.out.println("n value without recursive\n"); febo(n); System.out.println("\n n value with recursive\n"); if(n!=2) n=n+2; t=feboRec(n); System.out.printf("\n %d th value of febonacco sequence is %d",n-2,t); } }// end of class Output: Enter n Value 5 n value without recursive 5th value of febonacco sequence is 13 n value with recursive 5 th value of febonacco sequence is 13 /* 2 : a) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer. */ import javax.swing.*; import java.util.Scanner; public class PrimNumbers { public static void main(String args[]) { //String n1; int n,c=0,i,j; Scanner in=new Scanner(System.in); System.out.println("Enter n Value"); n=in.nextInt(); outer: for(i=2;i<=n;i++) { for(j=2;j<=i/2;j++) { if(i%j==0) continue outer; } System.out.print(" "+i); }

} }// end of class Output: Enter n Value 29 2 3 5 7 11 13 17 19 23 29 import java.util.Scanner; public class MatrxMult { public static void main(String args[]) { Scanner in=new Scanner(System.in); int i,j,k; int a[][]=new int[3][3]; int b[][]=new int[3][3]; int c[][]=new int[3][3]; System.out.println("Enter elements of First Matrix"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.printf("\nEnter elements of row :%d column:%d\t",i,j); a[i][j]=in.nextInt(); } } System.out.println("Enter elements of Second Matrix"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { System.out.printf("\nEnter elements of row :%d column:%d\t",i,j); b[i][j]= in.nextInt(); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { c[i][j]=0; for(k=0;k<3;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } System.out.println("resultant matrix is"); for(i=0;i<3;i++) { for(j=0;j<3;j++)

{ System.out.print(" "+c[i][j]); } System.out.print("\n"); } } }//End of class MatrixMult Output: Enter elements of First Matrix Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row :0 column:0 :0 column:1 :0 column:2 :1 column:0 :1 column:1 :1 column:2 :2 column:0 :2 column:1 :2 column:2 3 2 9 2 1 6 2 3 6

Enter elements of Second Matrix Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row resultant matrix is 3 2 9 2 1 6 2 3 6 :0 column:0 0 :0 column:1 1 :0 column:2 :1 column:0 1 :1 column:1 :1 column:2 1 :2 column:0 :2 column:1 1 :2 column:2

1 0 1 0

import java.util.Scanner; import java.util.StringTokenizer; import java.io.*; public class LabPro2c { public static void main(String args[]) throws IOException { int sum=0; Scanner in=new Scanner(System.in); System.out.println("Enter the Line"); String line=in.nextLine(); System.out.println("Enter the delemeter");

String k=in.next(); StringTokenizer wd=new StringTokenizer(line,k); while(wd.hasMoreTokens()) sum=sum+Integer.parseInt(wd.nextToken()); System.out.printf("sum is :%d",sum); } }//End of Class LabPro2c Output: Enter the Line 1,2,3,4,5 Enter the delemeter , sum is 15 /* 3. Write a java program to find both the Largest and Smallest number in a list of Integers*/ import java.util.Scanner; class MaxMinInList { public static void main(String args[]) { int a[]=new int[5]; int max,min; Scanner in=new Scanner(System.in); for(int i=0;i<a.length;i++) { System.out.println("Enter Integers"); a[i]=in.nextInt(); } max=min=a[0]; for(int i=1;i<a.length;i++) { if(max < a[i]) max=a[i]; else if(min > a[i]) min=a[i]; } System.out.printf("Max number in the list is :%d\nMin number in the List is : %d",max,min); } }//End of Class MaxMinInList Output: Enter Integers 23 Enter Integers

12 Enter Integers 45 Enter Integers 6 Max number in the list is :45 Min number in the List is : 6 /*4 Write a Java program that implements the Sieve of Eratosthenes to find prime numbers*/ import java.util.Scanner; public class PrimeSieve { public static void main(String args[]) { //String n1; int n,c=0,i,j; Scanner in=new Scanner(System.in); System.out.println("This Programe works for n<=100"); System.out.println("Enter n Value"); n=in.nextInt(); outer: for(i=2;i<=n;i++) { if((i==2)||(i==3)||(i==5)||(i==7)) System.out.print(" "+i); if((i%2==0)||(i%3==0)||(i%5==0)||(i%7==0)) continue outer; System.out.print(" "+i); } } }//End of Class PrimeSieve Output: Enter n Value 99 2 3 5 7 71 73 79 11 83 13 89 17 97 19 23 29 31 37 41 43 47 53 59 61 67

/*5. Write a java program to sort a list of names in ascending order*/ import java.util.Scanner; class SortNamesAscend { static String names[]=new String[5]; static void readNames()

10

{ int i=0; Scanner in=new Scanner(System.in); do{ System.out.println("Enter Names "); names[i]=in.next(); i++; if(i>4) System.err.println("Too many names type no"); }while(i<=4); } static void sort() { for(int i=0;i<names.length-1;i++) { if(names[i].compareTo(names[i+1])>0) { String temp; temp=names[i]; names[i]=names[i+1]; names[i+1]=temp; } } } static void display() { for(int i=0;i<names.length;i++) System.out.println(names[i]); } public static void main(String args[]) { readNames(); System.out.println("List of names before sorting"); display(); sort(); System.out.println("List of names after sorting"); display(); java.util.Arrays.sort(names); System.out.println("List of names sorting util Array sort method"); display(); } }// end of class SortNamesAscend Output: List of names before sorting satya syam

11

raju gopal santhsh List of names after sorting satya raju gopal santhsh syam List of names sorting util Array sort method gopal raju santhsh satya syam /*6. Write a Java program to implement the matrix ADT using a class. The operations supported by this ADT are: a) Reading a matrix. c) Addition of matrices. b) Printing a matrix. d) Subtraction of matrices. e) Multiplication of matrices.*/ final public class Matrix { private final int M; private final int N; private final double[][] data; public Matrix(int m,int n) { this.M=m; this.N=n; data = new double[M][N]; } public Matrix(double[][] data) { M = data.length; N = data[0].length; this.data = new double[M][N]; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) this.data[i][j] = data[i][j]; } public Matrix plus(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N){ System.out.println("Illegal matrix dimensions.\n Matrix addition is not posible"); return B; } else{

12

Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] + B.data[i][j]; return C; } } public Matrix subtract(Matrix B) { Matrix A = this; if (B.M != A.M || B.N != A.N) { System.out.println("Illegal matrix dimensions.\n Matrix Subtraction is not posible"); return B; } else{ Matrix C = new Matrix(M, N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) C.data[i][j] = A.data[i][j] - B.data[i][j]; return C; } } public void show() { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) System.out.printf("%6.2f ", data[i][j]); System.out.println(); } } public Matrix mult(Matrix B) { Matrix A = this; if (A.N != B.M) System.err.println("Illegal matrix dimensions.\nMatrix multiplication is not posible"); Matrix C = new Matrix(A.M, B.N); for (int i = 0; i < C.M; i++) for (int j = 0; j < C.N; j++) for (int k = 0; k < A.N; k++) C.data[i][j] += (A.data[i][k] * B.data[k][j]); return C; } public static Matrix getMatrix(){ java.util.Scanner in=new java.util.Scanner(System.in); int i,j,k; System.out.println("Enter row and column of Matrix"); int r=in.nextInt(); int c=in.nextInt(); System.out.println("Enter elements of Matrix"); Matrix x=new Matrix(r,c);

13

for(i=0;i<x.M;i++) { for(j=0;j<x.N;j++) { System.out.printf("\nEnter elements of row :%d column:%d\t",i,j); x.data[i][j]=in.nextDouble(); } } return x; } public static void main(String[] args) { double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} }; Matrix m1 = new Matrix(d); Matrix m2 = getMatrix(); System.out.println("The two matrixs are"); m1.show(); System.out.println(); m2.show(); System.out.println("Addition of two matrix"); // matrix addition m1.plus(m2).show(); System.out.println("Subtraction of two matrix"); // matrix subtraction m1.subtract(m2).show(); System.out.println("Multiplication of two matrix"); // matrix multiplication m1.mult(m2).show(); } }//end of class Output: Enter row and column of Matrix 3 3 Enter elements of Matrix 0.00 1.00 1.00 1.00 0.00 1.00 1.00 1.00 0.00 Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row Enter elements of row The two matrixs are :0 column:0 :0 column:1 :0 column:2 :1 column:0 :1 column:1 :1 column:2 :2 column:0 :2 column:1 :2 column:2

14

1.00 2.00 3.00 4.00 5.00 6.00 9.00 1.00 3.00 0.00 1.00 1.00 1.00 0.00 1.00 1.00 1.00 0.00 Addition of two matrix 1.00 3.00 4.00 5.00 5.00 7.00 10.00 2.00 3.00 Subtraction of two matrix 1.00 1.00 2.00 3.00 5.00 5.00 8.00 0.00 3.00 Multiplication of two matrix 5.00 4.00 3.00 11.00 10.00 9.00 4.00 12.00 10.00 /*7 Write a java program to solve Tower's of Hanoi problem */ import java.io.*; public class TowersOfHanoi { static int moves = 0; static int totalDisks = 0; public static void main(String[] args) throws java.io.IOException { int disks; char fromPole = 'A'; char withPole = 'B'; char toPole = 'C'; disks = getNumber("\nHow many disks are there on the tower? "); totalDisks = disks; if(totalDisks > 10){ System.out.println("Working..."); } FileOutputStream fos = new FileOutputStream("TowersOfHanoiSolution.txt"); PrintStream ps = new PrintStream(fos); solveHanoi(disks, fromPole, toPole, withPole, ps); ps.close(); System.out.println(); System.out.println("\nAmount of moves: " + moves + "\n"); } static void solveHanoi(int disks, char fromPole, char toPole, char withPole, PrintStream ps) {

15

if (disks >= 1) { solveHanoi(disks-1, fromPole, withPole, toPole, ps); moveDisk(fromPole, toPole, ps); solveHanoi(disks-1, withPole, toPole, fromPole, ps); } } static void moveDisk(char fromPole, char toPole, PrintStream ps) { moves++; if(totalDisks <= 10){ System.out.print("Move from " + fromPole + " to " + toPole + ". "); ps.print("Move from " + fromPole + " to " + toPole + ". "); if (moves%4 == 0){ System.out.println(); ps.println(); } } else { ps.print("Move from " + fromPole + " to " + toPole + ". "); if (moves%4 == 0){ ps.println(); } } } static int getNumber(String question) throws java.io.IOException { String theNumber; int number = 0; BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); System.out.print(question); theNumber = in.readLine(); System.out.println(); number = Integer.parseInt(theNumber); return number; } }//end of the class Output: How many disks are there on the tower? 3 Move from A to C. Move from A to B. Move from C to B. Move from A to C. Move from B to A. Move from B to C. Move from A to C. Amount of moves: 7

16

/* 8 Write a java program that uses a recursive to compute ncr Note: n and r values are given*/ import java.util.Scanner; class RecNcr { static int recNcr(int n, int r) { if (n==r) return 1; if(r==1) return n; if(r==0) return 1; return recNcr(n-1,r)+recNcr(n-1,r-1); } public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Enter n and r values"); int n=in.nextInt(); int r=in.nextInt(); int v=recNcr(n,r); System.out.printf("%dc%d value is :%d",n,r,v); } }// end of class Output: Enter n and r values 4 1 4c1 value is :4 /*9 Write a java program to perform the following operations a) Concatenation of two strings b) Comparision of two strings*/ class StrConcatCompar { static String strConcat(String s1, String s2) { return s1+s2; } static int strCompar(String s1,String s2) { return s1.compareTo(s2); } public static void main(String[] args) { java.util.Scanner in=new java.util.Scanner(System.in); System.out.println("Enter Strings"); String s1=in.next();

17

String s2=in.next(); String s=strConcat(s1,s2); System.out.printf("Concatienation of two Strings :%s\n",s); int value=strCompar(s1,s2); if(value==0) System.out.println("The two Strings are equal"); if(value>0) System.out.printf("The String %s is grater than String %s",s1,s2); if(value<0) System.out.printf("The String %s is smaller than String %s",s1,s2); } }//end of class Output: Concatienation of two Strings :samplelabmanual The String sample is grater than String labmanual /*10 Implement the complex number ADT in Java using a class. The complex ADT is used to represent complex numbers of the form c=a+ib, where a and b are real numbers. The operations supported by this ADT are: a) Reading a complex number. d) Subtraction of complex numbers. b) Writing a complex number. e) Multiplication of complex numbers. c) Addition of Complex numbers.f) Division of complex numbers.*/ class Complex { double a; //Real number double ib; //immaginary number Complex(double a, double b) { this.a=a; this.ib=b; } public static Complex getComplex() { java.util.Scanner in=new java.util.Scanner(System.in); System.out.println("Enter two Real numbers"); double r1=in.nextDouble(); double r2=in.nextDouble(); Complex c=new Complex(r1,r2); return c; } public void plus(Complex c2) { Complex c1=this; Complex c=new Complex(0.0,0.0); c.a=c1.a+c2.a;

18

c.ib=c1.ib+c2.ib; c.show('+'); } public void subt(Complex c2) { Complex c1=this; Complex c=new Complex(0.0,0.0); c.a=c1.a-c2.a; c.ib=c1.ib-c2.ib; c.show('-'); } public void mult(Complex c2) { Complex c1=this; Complex c=new Complex(0.0,0.0); c.a=c1.a*c2.a+(-1)*(c1.ib*c2.ib); c.ib=c1.a*c2.ib+c1.ib*c2.a; c.show('*'); } public void div(Complex c2) { Complex c1=this; double d=c2.a*c2.a+c2.ib*c2.ib; Complex c=new Complex(0.0,0.0); c.a=(c1.a*c2.a+c1.ib*c2.ib)/d; c.ib=(c1.a*c2.ib-c1.ib*c2.a)/d; c.show('/'); } public void show(char op) { switch (op) { case '+': System.out.printf("Addition of Complex numbers:%6.2f%c%6.2f",this.a,op,this.ib); break; case '-': System.out.printf("Subtraction of Complex numbers:%6.2f +%6.2f",this.a,this.ib); break; case '*': System.out.printf("Multiplication of Complex numbers:%6.2f +%6.2f",this.a,this.ib); break; case '/': System.out.printf("Division of Complex numbers: %6.2f +%6.2f",this.a,this.ib); break; }

19

} public static void main(String[] args) { java.util.Scanner in=new java.util.Scanner(System.in); System.out.println("Operation Supported by this Complex ADT"); System.out.print("\n\t\t1.Addition\n\t\t2.Subtraction\n\t\t3.Multiplication\n\t\t4.Divisio n"); System.out.println("\nEnter your choice"); int x=in.nextInt(); Complex c1=getComplex(); Complex c2=getComplex(); switch (x) { case 1: c1.plus(c2); break; case 2: c1.subt(c2); break; case 3: c1.mult(c2); break; case 4: c1.div(c2); break; default: System.err.println("\nEnter Correct Choice"); } } }// End of Class Output: Operation Supported by this Complex ADT 1.Addition 2.Subtraction 3.Multiplication 4.Division Enter your choice 2 Enter two Real numbers 23.6 12.9 Enter two Real numbers 11.9 4.6 Subtraction of Complex numbers: 11.70 + 8.30 /*11 Write a Java program that makes frequency count of letters in a given text.*/

20

class LetterFrequecy { public static void main(String[] args) { char[] alphbet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; int[] freq=new int[26]; //initialize to freq to zero for(int i=0;i<26;i++) freq[i]=0; java.util.Scanner in=new java.util.Scanner(System.in); System.out.println("Enter Text"); String text=in.nextLine(); for(int i=0;i<text.length();i++) { for(int j=0;j<26;j++) { if(text.charAt(i)==alphbet[j]) freq[j]=freq[j]+1; } } // Display information for(int i=0;i<26;i++) { char x=alphbet[i]; if(freq[i]==0) continue; else System.out.printf("number of letter :%c's is :%d\n",x,freq[i]); } } }// End of Class Output: Enter Text This is a sample text to test letter frequency number of letter :a's is :1 number of letter :c's is :1 number of letter :e's is :7 number of letter :f's is :1 number of letter :h's is :1 number of letter :i's is :2 number of letter :l's is :2 number of letter :m's is :1 number of letter :n's is :1 number of letter :o's is :1 number of letter :p's is :1

21

number of letter :q's is :1 number of letter :r's is :2 number of letter :s's is :4 number of letter :t's is :8 number of letter :u's is :1 number of letter :x's is :1 number of letter :y's is :1 /*12 Write a Java program that uses functions to perform the following operations : a) Inserting a sub-string in to the given main string from a given position. b) Deleting n characters from a given position in a given string.*/ import java.util.Scanner; class StringOp { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Enter a text"); String text=in.nextLine(); System.out.println("Enter a String to insert"); String str=in.nextLine(); System.out.println("Enter position to insert"); int p=in.nextInt(); //create an empty StringBuffer Object StringBuffer sb=new StringBuffer(); sb.append(text); System.out.println("Main text before insertion :\n"+sb); sb.insert(p,str); System.out.println("The text after insertion :\n"+sb); System.out.println("Do you want to delete a charector form the text displayed below : type 'yes / no':\n"); String s=in.next(); if(s.equals("yes")) { System.out.println("Enter position to delete"); p=in.nextInt(); System.out.printf("\nEnter length of mesage \nto be delete \nfrom the position %d\n",p); int l=in.nextInt(); System.out.println("After deletion: "+sb.delete(p,l)); } } }//End Of Class Output:

22

/*13 a) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome.*/ import java.util.Scanner; class PolindromeCheck { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Enter String"); String s1=in.next(); StringBuffer sb=new StringBuffer(s1); String revStr=sb.reverse().toString(); if(s1.equals(revStr)) System.out.printf("\n : %s :is Polindrome\n",s1); else System.out.println("The String is not Polindrome"+s1); } }//End of Class Output: /*13 b) Write a Java program to make frequency count of words in a given text.*/ import java.util.*; import java.lang.*; import java.io.*; class WordFreq { public static void main(String[ ] args) throws IOException { DataInputStream dis=new DataInputStream(System.in); String str=dis.readLine(); String temp; boolean mark=true; StringTokenizer st=new StringTokenizer(str); int n=st.countTokens( ); String a[ ]=new String[n]; int i=0,count=0; while(st.hasMoreTokens()) { a[i]=st.nextToken(); i++; } int k=0; String tempBuf[]=new String[n];

23

//elliminating repeated words for(i=0;i<a.length;i++) { temp=a[i]; for(int j=i+1;j<a.length;j++) { if(temp.equals(a[j])) {System.out.println(j); mark=false; break;} } //i++; if(!mark) { tempBuf[k]=a[i]; k++;mark=true; } } for(i=0;i<tempBuf.length;i++) System.out.println(tempBuf[i]+" "+mark); for(i=0;i<a.length;i++) { count=1; temp=a[i]; for(int j=i+1;j<a.length;j++) { if(temp.compareTo(a[j])==0) count++; } System.out.println(a[i]+" : "+count+" Times"); } } }// End of Class Output: /*15 .a) Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. b) Write a Java program that reads a file and displays the file on the screen, with a line number before each line. c) Write a Java program that displays the number of characters, lines and words in a text file. d) Write a Java program to change a specific character in a file. Note: Filename , number of the byte in the file to be changed and the new character are specified on the command line.*/

24

// 15. a) import java.io.File; class FileProp { public static void main(String[] args) { //accepting file name through command line args String fileName=args[0]; //pass the filename to file object File f=new File(fileName); //apply file class methods on file object System.out.println("File Name :"+f.getName()); System.out.println("Path :"+f.getPath()); System.out.println("Absolute Path:"+f.getAbsolutePath()); System.out.println("Parent :"+f.getParent()); System.out.println("Exist :"+f.exists()); if(f.exists()) { System.out.println("is directory :"+f.isDirectory()); System.out.println("is writeable :"+f.canWrite()); System.out.println("is readable :"+f.canRead()); System.out.println("size of the file :"+f.length()); } } }// end of class Output: //15. b) import java.io.FileInputStream; import java.io.IOException; class ReadFile { public static void main(String[] args)throws IOException { //attach the file "args[0]" to FileInputStream To read data FileInputStream fin=new FileInputStream(args[0]); int lineCount=0; boolean isNewLine=false; int ch; System.out.print(lineCount+":"); while((ch=fin.read())!=-1) { System.out.print((char)ch); if(ch=='\n') { ++lineCount; isNewLine=true;

25

System.out.print(lineCount+":"); } } //close the file fin.close(); } }// end of class Output: //15. C) import java.io.FileInputStream; import java.io.IOException; class CountFile { public static void main(String[] args)throws IOException { //attach the file "args[0]" to FileInputStream To read data FileInputStream fin=new FileInputStream(args[0]); int lineCount=1; int charCount=1; int wordCount=1; int ch; while((ch=fin.read())!=-1) { if(ch==' ') ++wordCount; if(ch=='\n') ++lineCount; if(Character.isLetterOrDigit(ch)) ++charCount; } System.out.println("number of words :"+wordCount); System.out.println("number of Characters :"+charCount); System.out.println("number of lines :"+lineCount); //close the file fin.close(); } }// end of class Output:

26

/* 16. Write a Java program that: i) Implements stack ADT. ii) Converts infix expression into Postfix form iii) Evaluates the postfix expression. */ import java.io.IOException; import java.io.DataInputStream; import java.lang.reflect.Array; public class stack<T> { T stack[]; int top; stack() { top=-1; } /*stack(int n) { stack=new char[n];top=-1; }*/ stack(Class<T> cs,int n) { stack=(T[])Array.newInstance(cs,n);top=-1; } int getTop() { return this.top; } T getItem() { if(isEmpty()) System.out.println("stack is underflow"); return stack[top]; } boolean isEmpty() { if(top<0) return (true); else return (false); } boolean isFull() { int size=stack.length; if(top==size-1) return (true); else return (false); } void push(T item) { if(isFull()) System.out.println("stack is full");

27

else stack[++top]=item; } T pop() { if(isEmpty()) { System.out.println("stack is underflow"); return stack[top]; } else return stack[top--]; } void disp() { int size=stack.length; for(int i=top;i>=0;i--) { System.out.print(stack[i]); } System.out.print("\n"); System.out.println(" "+"^"); } } // Write StackOp.java in separate file and run the program import java.io.IOException; import java.io.DataInputStream; class StackOP extends stack<Integer> { public static void main(String args[]) throws IOException,ClassNotFoundException { String ch="y"; DataInputStream in=new DataInputStream(System.in); System.out.println("Enter the stack size"); int n=Integer.parseInt(in.readLine()); Integer s=Integer.valueOf(n); System.out.println(s); Class cs=s.getClass(); stack<Integer> sOb=new stack<Integer>(cs,s); s: do { System.out.println("\t\t 1.Push\n\t\t 2.Pop\n\t\t 3.Exit"); System.out.print("Enter your choice :"); int test=Integer.parseInt(in.readLine()); switch(test) {

28

case 1: System.out.println("Enter Item value"); int th=Integer.parseInt(in.readLine()); Integer item=Integer.valueOf(th); sOb.push(item); System.out.flush(); sOb.disp();break; case 2: Integer t=sOb.pop(); System.out.printf("poped element is : %d\n",t); sOb.disp();break; case 3: System.exit(0); default: System.out.println("Enter right choice"); continue s; } System.out.println("Do you want to continue Press 'y'"); ch=in.readLine(); System.out.flush(); }while(ch.equals("y")); } }// end of the class Output: /* 16) ii) Converts infix expression into Postfix form */ import java.io.*; import java.util.Scanner; class InfixToPostfix extends stack<Character> { public InfixToPostfix(){} int precedence(char ch) { int i=5; switch(ch) { case '(' :i=0;break; case '+' : case '-' :i=1;break; case '*' : case '/' :i=2;break; case '%' :i=3;break; } return(i); } boolean operator(char ch) { if(ch=='/'||ch=='*'||ch=='+'||ch=='-'||ch=='%')

29

return true; else return false; } boolean isAlpha(char ch) { if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9') return true; else return false; } void postfix(String str) { char output[]=new char[str.length()]; char ch; int p=0; int i=0; Character cOb=new Character(str.charAt(i)); Class cs=cOb.getClass(); stack<Character> s=new stack<Character>(cs,str.length()); for(i=0;i<str.length();i++) { ch=str.charAt(i); if(ch=='(') { cOb=Character.valueOf(ch); s.push(cOb); } else if(isAlpha(ch)) { output[p++]=ch; } else if(operator(ch)) { if(s.isEmpty()) s.push('('); if((s.getTop()==0)|| precedence(ch)>precedence(s.getItem().charValue())||(s.getItem().charValue()=='(')) { s.push(Character.valueOf(ch)); } } else if(precedence(ch)<=precedence(s.getItem().charValue())) { cOb=s.pop(); output[p++]=cOb.charValue(); s.push(Character.valueOf(ch)); } else if(ch=='(') {

30

while((ch=s.pop().charValue())!='(') { output[p++]=ch; System.out.println(ch); } } } while(s.getTop()!=0) { cOb=s.pop(); if(cOb.charValue()=='(') continue; output[p++]=cOb.charValue(); } for(int j=0;j<str.length();j++) { System.out.print(output[j]); } } public static void main(String[] args) { String s; Scanner in=new Scanner(System.in); InfixToPostfix b=new InfixToPostfix(); System.out.println("Enter input string"); s=in.nextLine(); System.out.println("Input String:"+s); System.out.println("Output String:"); b.postfix(s); } }// end of class Output: /*17. a) Develop an applet in Java that displays a simple message. b) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named Compute is clicked.*/ //17. a) import java.awt.*; import java.applet.*; /*<center><applet code="DispMsg.class" width=500 height=400 align=MIDDLE> </applet></center>*/ public class DispMsg extends Applet { public void paint(Graphics g) {

31

g.drawString("Welcome to Applet Programming",50,100); } }// end of class

32

Output: //17. b) import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; /*<center><applet code=ComputeApplet.class width=500 height=400 align=MIDDLE> </applet></center>*/ public class ComputeApplet extends JApplet implements ActionListener { TextField t1,t2; JButton b1; Container c; Font f; public void init() { JFrame jf=new JFrame(); c=jf.getContentPane(); c.setLayout(null); jf.setSize(500,400); jf.setTitle("Factorial Demo"); jf.setVisible(true); Label title,number,result; number=new Label("Enter Integer",Label.LEFT); f=new Font("Helvetica",Font.BOLD,23); title=new Label("Caliculating Factorial",Label.CENTER); title.setFont(f); title.setBounds(200,10,500,50); result=new Label("Factorial is",Label.LEFT); t1=new TextField(20); t2=new TextField(20); b1=new JButton("Compute"); b1.setBounds(200,250,100,30); number.setBounds(50,100,100,30); t1.setBounds(200,100,200,30); result.setBounds(50,150,100,45); t2.setBounds(200,150,200,30); c.add(title); c.add(number);c.add(t1); c.add(result);c.add(t2); c.add(b1); //add listeners to button b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand();

33

try { if(str.equals("Compute")) { //retrieve data from textfield String s1=t1.getText(); int num=Integer.parseInt(s1); int result=1; for(int i=1;i<=num;i++) result=result*i; String res=" "+result; t2.setText(res); } }catch(Exception e){} } }// end of class Output: /*18. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.*/ import java.util.StringTokenizer; import java.util.Hashtable; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; import java.applet.Applet; // Converts the Calculator application to run either as an application // or as an applet by creating a "shared" panel -- a panel that will

34

// be shared by the application's Frame and by the Applet. The panel // will be the first component placed on each. All other components are // placed on the shared panel. public class CalculatorE extends Applet { private boolean isApplet = false; private boolean lastKeyWasFunction = true; private double displayHold = 0; private Frame f; private Hashtable theKeys = new Hashtable(); private Label display; private Panel pMain; private String lastFunction = ""; private Toolkit tk = null; private KeyListener keyListener = new KeyListener(); public static void main(String[] args) { CalculatorE calc = new CalculatorE(); calc.isApplet = false; calc.tk = Toolkit.getDefaultToolkit(); calc.f = new Frame("Calculator"); // add Window closer calc.f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } // close anon inner class }); // add Key Listener to frame calc.f.addKeyListener(calc.keyListener); // create panel which will be shared by Frame and Applet calc.pMain = new Panel(); calc.pMain.setLayout(new BorderLayout()); calc.pMain.setBackground(Color.lightGray); calc.pMain.addKeyListener(calc.keyListener); // add shared panel to Frame calc.f.add(calc.pMain, BorderLayout.CENTER); calc.makeGUI(); }

35

public void init() { isApplet = true; setLayout(new BorderLayout()); setBackground(Color.lightGray); this.addKeyListener(keyListener); // create the shared panel pMain = new Panel(); pMain.setLayout(new BorderLayout()); pMain.setBackground(Color.lightGray); pMain.addKeyListener(keyListener); // add the shared panel to the applet add(pMain, BorderLayout.CENTER); makeGUI(); } private void makeGUI() { // add display display = new Label("0", Label.RIGHT); pMain.add(display, BorderLayout.NORTH); Panel numPanel = new Panel(); numPanel.setBackground(pMain.getBackground()); numPanel.addKeyListener(keyListener); numPanel.setLayout(new GridLayout(4, 3)); Panel funcPanel = new Panel(); funcPanel.setBackground(numPanel.getBackground()); funcPanel.addKeyListener(keyListener); funcPanel.setLayout(new GridLayout(4, 2)); // create number buttons if (true) { ButtonListener bl = new ButtonListener(0); for (int i = 0; i < 12; i++) { Button b = new Button("" + i); b.setForeground(Color.blue); b.addActionListener(bl); b.addKeyListener(keyListener); // handle blank and '.' buttons if (i == 10) {

36

b.setLabel("+/-"); } if (i == 11) { b.setLabel("."); } theKeys.put(b.getLabel(), b); } } // create function keys if (true) { ButtonListener bl = new ButtonListener(1); StringTokenizer st = new StringTokenizer("/ C * CE + none - =", " "); while (st.hasMoreTokens()) { Button b = new Button(st.nextToken()); b.setForeground(Color.red); b.addActionListener(bl); b.addKeyListener(keyListener); // disable unneded 'b' key if (b.getLabel().equals("none")) { b.setVisible(false); } // add the key to theKeys array theKeys.put(b.getLabel(), b); // add the key to the function panel funcPanel.add(b); } } // place number buttons on numPanel for (int i = 1; i <= 9; i++) { numPanel.add((Button)theKeys.get("" + i)); } numPanel.add((Button)theKeys.get("+/-")); numPanel.add((Button)theKeys.get("0")); numPanel.add((Button)theKeys.get(".")); pMain.add(numPanel, BorderLayout.CENTER); pMain.add(funcPanel, BorderLayout.EAST); if (!isApplet) { f.pack(); Dimension screensize = tk.getScreenSize(); // set size f.setSize(screensize.width / 5, screensize.height / 4); // center form f.setLocation((screensize.width - f.getWidth()) / 2,

37

(screensize.height - f.getHeight()) / 2); f.setResizable(false); } pMain.setVisible(true); setVisible(true); if (isApplet == false) { f.setVisible(true); } } private double getDisplayValue() { double d = 0.0; String s = display.getText(); try { // Double.parseDouble doesn't work in 1.1v applets d = Double.valueOf(s).doubleValue(); } catch (NumberFormatException e) { d = 0.0; } return d; } private void handleFuncKey(Button b) { String lbl = b.getLabel(); if ("=CCE".indexOf(lbl) > -1) { if (lbl.equals("C")) { displayHold = 0d; lastFunction = ""; display.setText("0"); } if (lbl.equals("CE")) { display.setText("0"); lastKeyWasFunction = true; return; } if (lbl.equals("=")) {} } if (lastFunction.equals("+")) { display.setText("" + (displayHold + getDisplayValue())); } if (lastFunction.equals("-")) { display.setText("" + (displayHold - getDisplayValue())); }

38

if (lastFunction.equals("*")) { display.setText("" + (displayHold * getDisplayValue())); } if (lastFunction.equals("/")) { String r; try { r = "" + (displayHold / getDisplayValue()); } catch (ArithmeticException ae) { r = "divison error"; displayHold = 0d; } display.setText(r); } lastKeyWasFunction = true; lastFunction = lbl; displayHold = getDisplayValue(); } private void handleNumKey(Button b) { String lbl = b.getLabel(); if (lastKeyWasFunction) { display.setText(""); } if (lbl.equals(".") || lbl.equals("+/-")) { if (lbl.equals(".")) { if (display.getText().indexOf(".") == -1) { display.setText(display.getText() + "."); } } else { display.setText("" + getDisplayValue() * -1); } } else { display.setText(display.getText() + lbl); } lastKeyWasFunction = false; }

private class ButtonListener implements ActionListener { // buttonType == 0 : number key listener // buttonType == 1 : function key listener private int listenerType = 0; ButtonListener(int listenerType) {

39

this.listenerType = listenerType; } public void actionPerformed(ActionEvent e) { Button b = (Button)e.getSource(); if (listenerType == 0) { handleNumKey(b); } else { handleFuncKey(b); } } } private class KeyListener extends KeyAdapter { // better to use Keystroke class, but it's not supported in v1.1 private String lastKey = ""; public void keyPressed(KeyEvent e) { Button b = null; String targ = "NUMPAD"; String key = e.getKeyText(e.getKeyCode()); key = key.toUpperCase(); if (key.indexOf(targ) > -1) { key = key.substring(key.indexOf(targ) + 1 + targ.length()); } // handle SHIFTed keys if (lastKey.equals("SHIFT")) { if (key.equals("8")) { key = "*"; } if (key.equals("=")) { key = "+"; } } if (key.equals("ENTER")) { key = "="; } if (key.equals("MINUS")) { key = "-"; } b = (Button)theKeys.get(key);

40

if (b != null) { if ("0123456789.".indexOf(key) > -1) { handleNumKey(b); } else { handleFuncKey(b); } } lastKey = key; } } }// end of class Output: /* 19. Write a Java program for handling mouse events.*/ import java.awt.*; import java.applet.*; /*<applet code="MouseEvents" width=500 height=400></applet>*/ public class MouseEvents extends Applet { int xCor,yCor; String msg; public boolean mouseDown(Event eObj, int x, int y) { xCor=x; yCor=y; msg="Down"; repaint(); return true; } public boolean mouseUp(Event eObj, int x, int y) { xCor=x; yCor=y; msg="Up"; repaint(); return true; } public boolean mouseDrag(Event eObj, int x, int y) { xCor=x; yCor=y; msg="*"; showStatus("Dragging mouse at"+x+" "+y); repaint(); return true;

41

} public boolean mouseMove(Event eObj, int x, int y) { showStatus("Mouse moving at"+x+" "+y); repaint(); return true; } public void paint(Graphics g) { g.drawString(msg,xCor,yCor); } }// end of class Output: /*20. a) Write a Java program that creates three threads. First thread displays Good Morning every one second, the second thread displays Hello every two seconds and the third thread displays Welcome every three seconds. b) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.*/ // 20. a) class Wish implements Runnable { String str; Wish(String s) { this.str=s; } public void run() { for(int i=0;i<=10;i++) { System.out.println(str); try{ Thread.sleep(2000); }catch(InterruptedException ie){ie.printStackTrace();} } } } class WishAndInvite { public static void main(String[] a) { Wish w=new Wish("Good Morning"); Wish i=new Wish("Welcome); Thread t1=new Thread(w);

42

Thread t2=new Thread(i); //start thread t1.start(); t2.start(); } }// end of class Output: //20. b) class Communicate { public static void main(String[] a) { //producer produces some data with consumer consumes Producer p=new Producer(); Consumer c=new Consumer(p); Thread t1=new Thread(p); Thread t2=new Thread(c); t1.start(); t2.start(); } } class Producer extends Thread { StringBuffer sb; boolean dataProvider=false; Producer() { sb=new StringBuffer(); } public void run() { for(int i=1;i<=10;i++) { try{ sb.append(i+":"); Thread.sleep(1000); System.out.println("appending"); }catch(Exception e){} } dataProvider=true; } } class Consumer extends Thread { Producer prod;

43

Consumer(Producer p) { this.prod=p; } public void run() { try{ while(!prod.dataProvider) { Thread.sleep(100); } }catch(Exception e){} System.out.println(prod.sb); } }// end of the class Output: /*21. Write a Java program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box.*/ import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; /*<center><applet code=DivApplet.class width=500 height=400 align=MIDDLE> </applet></center>*/ public class DivApplet extends JApplet implements ActionListener { TextField t1,t2,t3; JButton b1; Container c; Font f; JFrame frame; public void init() { JFrame jf=new JFrame(); frame=new JFrame("Show Message Dialog"); //frame=new JFrame(); c=jf.getContentPane(); c.setLayout(null); jf.setSize(500,400); jf.setTitle("Factorial Demo"); jf.setVisible(true);

44

Label title,num1,num2,result; num1=new Label("Enter Integer",Label.LEFT); num2=new Label("Enter Integer",Label.LEFT); f=new Font("Helvetica",Font.BOLD,23); title=new Label("Division of Num1 and Num2",Label.CENTER); title.setFont(f); title.setBounds(200,10,500,50); result=new Label("Result :",Label.LEFT); t1=new TextField(20); t2=new TextField(20); t3=new TextField(20); b1=new JButton("Divide"); b1.setBounds(200,250,100,30); num1.setBounds(50,100,100,30); t1.setBounds(200,100,200,30); num2.setBounds(50,150,100,45); t2.setBounds(200,150,200,30); result.setBounds(50,200,100,50); t3.setBounds(200,200,200,30); c.add(title); c.add(num1);c.add(t1); c.add(num2);c.add(t2); c.add(result);c.add(t3); c.add(b1); //add listeners to button b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); try { if(str.equals("Divide")) { //retrieve data from textfield boolean err=false; int result=1; try{ String s1=t1.getText(); int num1=Integer.parseInt(s1); String s2=t2.getText(); int num2=Integer.parseInt(s2); result=num1/num2; }catch(NumberFormatException nfe){ err=true; String errMsg="Number Format Excepation"; JOptionPane.showMessageDialog(frame,errMsg); } catch(ArithmeticException arie)

45

{ err=true; String errMsg="Arithmetic Divide By Zero Exception"; JOptionPane.showMessageDialog(frame,errMsg); } String res=" "+result; if(!err) t3.setText(res); else t3.setText("Error"); } }catch(Exception e){} } }// end of Class Output: /*22. Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net)*/ //Server program to receive data and send data to client import java.io.*; import java.net.*; class ServerDataComun { public static void main(String[] args) throws IOException { //Create a server socket ServerSocket ss=new ServerSocket(8888); //connect it to the client Socket s=ss.accept(); System.out.println("Connection established"); //to send data to the client PrintStream ps=new PrintStream(s.getOutputStream()); //to read data comming from the client BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str,str1; while(true) {

46

System.out.println("reading data From Client"); str=br.readLine(); if(str!=null) { try{ System.out.println("Client: "+str+"\n"); int r=Integer.parseInt(str); double area=3.14*Math.pow(r,2); str1="Area of Circle is:"+area; ps.println(str1);//send data to client }catch(NumberFormatException nfe) {System.out.println("error: Number Format Exception");} } else { System.out.println("Connection terminated"); ps.close(); br.close(); ss.close(); s.close(); System.exit(0); } } } }

//client program to receive data and send data to server import java.io.*; import java.net.*; class DataComun { public static void main(String[] args) throws IOException { System.out.println("Hello World!"); //Create a client socket Socket s=new Socket("localhost",8888); //to send data to the server DataOutputStream dos=new DataOutputStream(s.getOutputStream()); //to read data comming from the server BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); //to read data from the keyboard

47

BufferedReader kb=new BufferedReader(new InputStreamReader(System.in)); String str,str1; System.out.println("Type exit to break"); str=kb.readLine(); System.out.println("data read from kb:"+str); while(!(str.equals("exit"))) { try{ System.out.println("Data is Sending to server..."); dos.writeBytes(str+"\n");//send data to server dos.flush(); System.out.println("Data is reading from server..."); str1=br.readLine();//receives from server System.out.println("area of circile is:"+str1); }catch(NumberFormatException nfe) {System.out.println("error: Number Format Exception");} str=kb.readLine(); } dos.close(); br.close(); kb.close(); s.close(); } }// end of the class Output:
/*23. a) Write a Java program that simulates a traffic light.

The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts. b) Write a Java program that allows the user to draw lines, rectangles and ovals.*/ // 23. a) import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class TrafficSignal extends JPanel { Color on; 48

int radius = 75; int border = 10; boolean active; public void setSignal(Color color) { on = color; active = true; } public Dimension getPreferredSize() { int size = (radius+border)*2; return new Dimension( size, size ); } public void paintComponent(Graphics g) { g.setColor( Color.white ); g.fillRect(0,0,getWidth(),getHeight()); if(active) { g.setColor(on); } else { g.setColor(Color.black); } g.fillOval( border,border,2*radius,2*radius ); } } public class TrafficLight extends JPanel implements ActionListener { JButton redButn,yButn,gButn; ActionListener listener; TrafficSignal redLight =new TrafficSignal(); TrafficSignal gLight =new TrafficSignal(); TrafficSignal yLight =new TrafficSignal(); JPanel lights; public static void main(String a[]) { TrafficLight t=new TrafficLight(); t.setGUI(); } public void setGUI() { TrafficLight tl=this; JFrame f = new JFrame("Traffic Light"); lights = new JPanel(new GridLayout(0,3)); tl.redLight.setSignal(Color.black); tl.gLight.setSignal(Color.black); tl.yLight.setSignal(Color.black); lights.add(redLight);

49

lights.add(gLight); lights.add(yLight); tl.redButn=new JButton("Red"); tl.gButn=new JButton("Green"); tl.yButn=new JButton("Yellow"); lights.add(tl.redButn); lights.add(tl.gButn); lights.add(tl.yButn); tl.redButn.addActionListener(this); tl.gButn.addActionListener(this); tl.yButn.addActionListener(this); f.setContentPane(lights); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLocationRelativeTo(null); f.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Green")) { gLight.setSignal(Color.green); redLight.active=false; yLight.active=false; lights.updateUI(); } if (e.getActionCommand().equals("Red")) { redLight.setSignal(Color.red); gLight.active=false; yLight.active=false; lights.updateUI(); } if (e.getActionCommand().equals("Yellow")) { yLight.setSignal(Color.yellow); redLight.active=false; gLight.active=false; lights.updateUI(); } } }// end of class Output: /*24. a) Write a Java program to create an abstract class named Shape that contains an empty method named numberOfSides ( ).Provide three classes named

50

Trapezoid, Triangle and Hexagon such that each one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides ( ) that shows the number of sides in the given geometrical figures.*/ abstract class Shapes { abstract int numberOfSides(); } class Trapezoid extends Shapes { int numberOfSides() { return 5; } } class Traingle extends Shapes { int numberOfSides() { return 3; } } class Hexagon extends Shapes { int numberOfSides() { return 6; } } class SidesMain { public static void main(String[] a) { Trapezoid tr=new Trapezoid(); Traingle t=new Traingle(); Hexagon h=new Hexagon(); System.out.println("Number of Sides in Trapeziod :"+tr.numberOfSides()); System.out.println("Number of Sides in Traingle :"+t.numberOfSides()); System.out.println("Number of Sides in Hexagon :"+h.numberOfSides()); } }// end of class Output: /*24. b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table.

51

The elements are separated by commas. Write a java program to display the table using Jtable component.*/ import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import java.util.StringTokenizer; import java.awt.Dimension; import java.io.*; class TableDemo extends JFrame { public static void main (String[] a)throws IOException,FileNotFoundException { FileReader ifs=null; File f=new File("data.txt"); int nOfr=0; int nOfc=0; int ch=0; String[] header; String[][] data; String dataHeader=" "; String sdata=" "; String delimiter=","; TableDemo table=new TableDemo(); if(f.exists()) { ifs=new FileReader(f); while((ch=ifs.read())!=-1) { char c=(char)ch; if(c=='\n') nOfr++; if(nOfr==0) dataHeader=dataHeader+c; else sdata=sdata+c; } dataHeader.trim(); sdata.trim(); StringTokenizer stz=new StringTokenizer(dataHeader,delimiter); while(stz.hasMoreTokens()) { nOfc++; String t=stz.nextToken(); }

52

StringTokenizer stz1=new StringTokenizer(dataHeader,delimiter); header=new String[nOfc]; int i=0; while(stz1.hasMoreElements()) { if(i<=nOfc) header[i]=stz1.nextToken(); ++i; } StringTokenizer stz2=new StringTokenizer(sdata,delimiter); data=new String[nOfr][nOfc]; //System.out.println(" "+nOfr+" "+nOfc); int j; for(i=0;i<nOfr-1;i++) for(j=0;j<=nOfc-1;j++) data[i][j]=stz2.nextToken(); table.createTableAndShowGUI(data,header); } } private void createTableAndShowGUI(String[][] d,String[] h) { JFrame frame = new JFrame("SimpleTableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTable table = new JTable(d, h); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); JScrollPane pane = new JScrollPane( table ); frame.setContentPane(pane); frame.pack(); frame.setVisible(true); } }// end of class Output: /*25. Write a Java program that illustrates the following a) Creation of simple package. b) Accessing a package.*/ import mypacks.numfinder; import java.io.*; public class packDemo

53

{ public static void main(String args[]) throws IOException { String s="y"; DataInputStream in=new DataInputStream(System.in); do { System.out.println("Enter your number"); int n=Integer.parseInt(in.readLine()); numfinder nObj=new numfinder(n); nObj.even(); System.out.println("Do you want to check other number"); s=in.readLine(); }while(s.equals("y")); } } //Write a numfinder.java program under mypacks folder package mypacks class NumFinder { int num; NumFinder(int n) { this.num=n; } public void even() { int t=num%2; if(t==0) System.out.println("The number is even"); } public void odd() { int t=num%2; if(t!=0) System.out.println("The number is odd"); } public void prime() { outer: for(i=2;i<=num;i++) { for(j=2;j<=i/2;j++) { if(i%j==0) continue outer; } System.out.print(" "+i); }

54

} }// end of class Output: /*26. Write Java programs that illustrates the following a) Handling predefined exceptions b) Handling user defined exceptions*/ import java.io.*; class myexc extends Exception { public myexc(String msg) { super(msg); } } class ExcDemo { public static void main(String args[]) { String ch="y"; String name; double sa; DataInputStream in=new DataInputStream(System.in); cl1: do { try { System.out.println("Enter name"); name=in.readLine(); for(int i=0;i<name.length();i++) { try{ if(!Character.isLetter(name.charAt(i))&&!Character.isSpaceChar(name.charAt(i))) throw new myexc("Invalid name");} catch(Exception e){System.out.println(e.getMessage());continue cl1;} } System.out.println("Enter salary"); sa=Double.valueOf(in.readLine()).doubleValue(); } catch(NumberFormatException e) { System.out.println("Invalid value you enterd"); continue cl1; } catch(IOException e) { System.out.println("Invalid value you enterd");

55

continue cl1; } System.out.println("name"+name+" "+"Salary"+sa); try{ System.out.println("do you want check again"); ch=in.readLine();} catch(IOException e) { System.out.println(e.getMessage()); continue cl1; } }while(ch.equals("y")); } }// end of class Output: /*27. Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods: a) Linear search b) Binary search*/ import java.util.Scanner; class Search { //int[] item; public void linearSearch(int[] b,int n) { boolean test=false; for(int i=0;i<b.length-1;i++) { if(n==b[i]) {System.out.println("Number found : "+n+" Linear search position :"+i); test=true; break;} } if(!test) System.out.println("Number not found :"+n); } public void binarySearch(int[] b,int n) { int lb=0; int ub=b.length; int m=(lb+ub)/2; boolean test=false; while(lb<ub) { if(n==b[m])

56

{ System.out.printf("\nNumber found :%d at position : %d",n,m); test=true;break; } else { if(n>b[m]) lb=m+1; else if(n<b[m]) ub=m-1; } m=(lb+ub)/2; } if(!test) System.out.println("\nNumber not found :"+n); } static void sort(int[] b) { for(int i=0;i<b.length-1;i++) { for(int j=i+1;j<=b.length-1;j++) if(b[i]>b[j]) { int temp; temp=b[i]; b[i]=b[j]; b[j]=temp; } } } public void disp(int[] b) { for(int i=0;i<b.length;i++) System.out.print("\t"+b[i]); } } class SearchDemo { public static void main(String[] args) { Scanner in=new Scanner(System.in); int a[]={11,12,4,2,7,5}; System.out.println("Enter value to found"); int n=in.nextInt(); Search sm=new Search();

57

sm.linearSearch(a,n); Search.sort(a); // Element after sort sm.disp(a); sm.binarySearch(a,n); } }// end of class Output: /*33. Write Java programs for implementing the following sorting methods: a) Bubble sort b) Selection sort c) Insertion sort d) Quick sort*/ import java.util.Scanner; class Sort { public void bubbleSort(int[] x) { int tmp,j,pass; boolean f=true; int n=x.length; for(pass=0;pass<n&&f==true;pass++) { f=false; for(j=0;j<n-pass-1;j++) if (x[j]>x[j+1]) { f=true; tmp=x[j]; x[j]=x[j+1]; x[j+1]=tmp; } } } public void selectionSort(int[] x) { int n=x.length; int min=0; int pass,k; for(pass=0;pass<n;pass++) { min=pass; for(int j=pass+1;j<n;j++) {

58

if(x[min]>x[j]) min=j;//update min } if(min!=pass) { //swap elements k=x[pass]; x[pass]=x[min]; x[min]=k; } } } public void insertionSort(int[] x) { int i,k,y; for(k=1;k<x.length;k++) { y=x[k]; for(i=k-1;i>=0 && y<x[i];i--) x[i+1]=x[i]; x[i+1]=y; } } public void quickSort(int[] a,int lb,int ub) { int pivot,down,tmp,up,k; pivot=a[lb]; up=ub; down=lb; if(down>=up) return; while(down<up) { while(a[down]<=pivot && down<ub) down++; while(a[up]>pivot) up--; if (down<up) { tmp=a[down]; a[down]=a[up]; a[up]=tmp; } } a[lb]=a[up]; a[up]=pivot; k=up; quickSort(a,lb,k-1);

59

quickSort(a,k+1,ub); } public void disp(int[] b) { for(int i=0;i<b.length;i++) System.out.print("\t"+b[i]); } } class SortMethods { public static void main(String[] args) { Scanner in=new Scanner(System.in); Sort so=new Sort(); int a[]={11,23,4,5,22,29,56}; String ch="y"; s: do { menu(); System.out.print("\nEnter your choice :"); int test=in.nextInt(); switch(test) { case 1: so.bubbleSort(a); so.disp(a); break; case 2: so.selectionSort(a); so.disp(a); break; case 3: so.insertionSort(a); so.disp(a); break; case 4: //int lb=0; //int ub=a.length; so.quickSort(a,0,a.length-1); so.disp(a); break; case 5:System.exit(0); default: System.err.println("\nEnter Correct Choice"); continue s; } System.out.println("\nDo you want to continue Press 'y'"); ch=in.next(); System.out.flush();

60

}while(ch.equals("y")); } static void menu() { System.out.print("\n\t\t1.Bubble sort \n\t\t2.Selection sort\n\t\t3. Insertion sort\n\t\t4. Quick sort\n\t\t5. Exit"); } }// end of class Output:

61

You might also like