Oop Lab Manual
Oop Lab Manual
Oop Lab Manual
INFORMATION TECHNOLOGY
(II YEAR B.Tech II SEMESTER)
2011-2012
ANNAMACHARYA
INSTITUTE OF TECHNOLOGY & SCIENCES (AFFILIATED TO JNTUA) AN ISO 9001:2000 CERTIFIED INSTITUTION
VENKATAPURAM (VILL), TIRUPATI-517520 CHITTOOR DIST 2011-2012
Week-1
1. AIM: Write a java program to print all real roots to the Quadratic equation. PROGRAM CODE:
import java.io.*; class Quadratic { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a,b,c; float r1,r2,d; System.out.println("enter the a,b,c values"); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine()); c=Integer.parseInt(br.readLine()); if(a==0) { System.out.print("linear solution"); r1=-c/b; System.out.print("root="+r1); } d=((b*b)-(4*a*c)); if(d==0) { System.out.println("the roots are real and equal"); System.out.print(+(-b/(2*a))); } if(d>0) { System.out.println("the roots are real and different"); r1=(float)(-b+Math.sqrt(d))/(2*a); r2=(float)(-b-Math.sqrt(d))/(2*a); System.out.println(r1+" "+r2); }
rel=-b/2*a; img=((float)Math.sqrt(-d))/2*a; System.out.println("root1="+ rel + "+i"+ img); System.out.println("root2="+ rel + "-i" + img); } } }
2) AIM: Write a java program to print nth term in the fibonacci series PROGRAM CODE:
import java.io.*; class fibonacci { public static int fibor(int m) { int t=0; if((m==1)||(m==2)) { t=1; } else if(m>2) t=fibor(m-1)+fibor(m-2); return t; } public static int fibonr(int m) { int a=1,b=1,t=0; while(m>0] { a=b; b=t; t=a+b; m--; } return t; } public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the value of n:"); int n=Integer.parseInt(br.readLine()); System.out.print("The value of fibonacci series using recursivemethod is"+ fibor(n)); System.out.print(n+"The value of fibonacci series using non-recursive method is:"+fibonr(n)); } }
C:\>javac fibonacci.java C:\>java fibonacci Enter the value of n:5 The value of fibonacci series using recursivemethod is:5 The value of fibonacci series using non-recursive method is:5
EXERCISE:
1. Write a java program to find out Factorial of a given number using recursive and non recursive methods. 2. Write a java Program which performs sorting of integers using bubble sort .
Week-2
1) AIM: Write a java program that promts the user for an integer and then prints all prime
numbers upto that integer.
PROGRAM CODE:
import java.io.*; class Prime { public static void main(String[]args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter n:"); int n=Integer.parseInt(br.readLine()); int k=0; for(int i=1;i<=n;i++) { if((i==1)||(i==2)) System.out.println(i); for(int j=2;j<i;j++) { if(i%j==0) { k=0; break; } else k++; } if(k>0) System.out.println(i); } } }
{ public static void main(String args[])throws IOException { int i,j,k,m,n,p,q; int a[][],b[][],c[][]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter m,n,p,q"); m=Integer.parseInt(br.readLine()); n=Integer.parseInt(br.readLine()); p=Integer.parseInt(br.readLine()); q=Integer.parseInt(br.readLine()); a=new int[m][n]; b=new int[p][q]; c=new int[m][q]; System.out.println("entre matrix A"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { a[i][j]=Integer.parseInt(br.readLine()); } } System.out.println("entre matrix B"); for(i=0;i<p;i++) { for(j=0;j<q;j++) { b[i][j]=Integer.parseInt(br.readLine()); } } for(i=0;i<m;i++) { for(j=0;j<q;j++) { c[i][j]=0; for(k=0;k<n;k++) { c[i][j]+=a[i][k]*b[k][j]; } } } System.out.println("the multiple matrix is:"); for(i=0;i<m;i++) { for(j=0;j<q;j++) {
3) AIM: Write a java program that reads line of integers,and then displays each integer, and
sum of all the integers (using StringTokenizer class of java.util)
PROGRAM CODE:
import java.io.*; import java.util.*; class Strtok {
public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any no's giving '$' as delimeter:"); String str=br.readLine(); StringTokenizer st=new StringTokenizer(str," "); System.out.println("the count of all tokens are:"); System.out.println(st.countTokens()); int a,sum=0; String s1; System.out.println("the tokens are:"); while(st.hasMoreTokens()) { s1=st.nextToken(); System.out.println(s1); a=Integer.parseInt(s1); sum+=a; } System.out.println("the sum of all integers :"+sum); } }
EXERCISE:
1. Write a java program which accepts elements from the user and display the transpose of the matrix. 2. Write a java program which accepts the marks of student into a 1D array from keyboard and finds total marks and percentages. 3.Write a program to show serialization of objects.
Week-3
1)AIM: Write a java program that checks whether the given string is palindrome or not. PROGRAM CODE:
import java.io.*; class palin { public static void main(String args[])throws IOException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the string"); String st=br.readLine(); char ch[]=st.toCharArray(); int count=0; for(int i=0,j=ch.length-1;i<j;i++,j--) if(ch[i]!=ch[j]) { count=1; break; } if(count==0) System.out.println(st + "is palindrome"); else System.out.println(st + "not a palindrome"); } }
2) AIM: Write a java program for sorting of given list of names in ascending order.
PROGRAM CODE:
import java.io.*; class sort { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,j,n; String temp; System.out.println("enter the n value:"); n= Integer.parseInt(br.readLine()); String a[]=new String[100]; System.out.println("enter the string"); for(i=0;i<n;i++) { a[i]=br.readLine(); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if((a[i].compareTo(a[j]))>0) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.println(After sorting:); for(i=0;i<n;i++) { System.out.println(a[i]); } } }
3)AIM: Write a java program to make frequency count of words in given text. PROGRAM CODE:
import java.io.*; import java.util.*; class Frequency { public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i=0,count=0,j; System.out.print("enter the text"); String str=br.readLine(); StringTokenizer st=new StringTokenizer(str," "); String s[]=new String[100]; String temp; int n=st.countTokens(); while(st.hasMoreTokens()) { temp=st.nextToken(); temp.trim(); s[i]=temp; i++; } for(i=0;i<n;i++) { if(s[i].equals(" ")) continue; count=1; for(j=i+1;j<n;j++) { if(s[i].equals(s[j])) { count++; s[j]=" "; } } System.out.print("the word "+s[i]); System.out.println(" appears "+count+" time "); } } }
EXERCISE:
1. Write a java program to test the immutability of the strings. 2. Write a java program to read different types of data separated by space,from the keyboard using scanner class.
Week-4
1) AIM: Write a java program that reads a file from user and displays its properties. PROGRAM CODE:
import java.io.*; class FileProperties { public static void main(String [] args)throws IOException
{ String s=args[0]; File f=new File(s); if(f.createNewFile()) { if(f.exists()) { System.out.println("file"+f+"is exists"); if(f.canRead()) System.out.println("file"+f+"is readable"); if(f.canWrite()) System.out.println("file"+f+"is writable"); long l=f.length(); System.out.println("the length of the file is"+l+"bytes"); String str=f.getPath(); System.out.println("the type of file"+f+"is"+str); } else System.out.println("the file"+f+"doesn't exists"); } } }
2) AIM: Write a java program that reads a file and displays the file on the screen with a line
number before each line.
PROGRAM CODE:
import java.io.*; public class line { public static void main(String [] args)throws IOException {
FileReader fr=new FileReader("sai.txt"); BufferedReader br=new BufferedReader(fr); LineNumberReader ln=new LineNumberReader(br); ln.setLineNumber(0); while(true) { try { int line=ln.getLineNumber(); String str=ln.readLine(); if(str==null) break; System.out.println(line+"\t"+str); } catch(EOFException ex) { break; } } } }
3) AIM: Write a java program that displays the number of characters,lines and words in a text
file.
PROGRAM CODE:
import java.io.*; class word { public static void wc(InputStreamReader isr)throws IOException { int words=0,lines=0,chars=0,c=0;
boolean lastwhite=true; String whitespace="\t\n\r"; while((c=isr.read())!=-1) { chars++; if(c=='\n') ++lines; int index=whitespace.indexOf(c); if(index==-1) { if(lastwhite==true) { ++words; } } else { lastwhite=true; } } if(chars!=0) ++lines; System.out.println("lines:"+lines+"words:"+words+"characters"+ch ars); } public static void main(String [] args)throws IOException { FileReader fr=new FileReader(args[0]); wc(fr); } }
EXERCISE:
1. Write a java program to create Employee class whose objects are to be stored into a file.
2. Write a program to read the content of the input file and write them into an output file. 3. Write a program to accept a directory name and display the contents into an array.
Week-5
1) AIM: Write a java program that implements stack ADT PROGRAM CODE:
import java.io.*; class Stack { public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int top=-1,n,size; System.out.println("enter the size of the stack"); size=Integer.parseInt(br.readLine()); int a[]=new int[size]; System.out.println("STACK OPERATIONS"); do { System.out.println("1.PUSH \n 2.POP \n 3.PEEP \n 4.DISPLAY \n 5.EXIT"); System.out.println("enter your choice"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("enter the element"); int x=Integer.parseInt(br.readLine()); if(top>size) System.out.println("stack is full"); else { a[++top]=x; } break; case 2: if(top<0) System.out.println("stack is empty"); else { System.out.println("the poped element is :"+a[top]); top--; } break; case 3: if(top<0) System.out.println("stack is empty"); else { System.out.println("the element in top is:"+a[top]); } break; case 4: System.out.println("elements in the stack are:"+a[top]); for(int i=0;i<=top;i++) { System.out.println(a[i]+ "\n");
2) AIM: Write a java program that converts infix expression into postfix form. PROGRAM CODE:
import java.io.*; class InToPost { private Stack theStack; private String input; private String output=" "; public InToPost(String in)
{ input=in; int stackSize=input.length(); theStack=new Stack(stackSize); } public String doTrans() { for(int j=0;j<input.length();j++) { char ch=input.charAt(j); switch(ch) { case '+': case '-': gotOper(ch,1); break; case '*': case '/': gotOper(ch,2); break; case '(': theStack.push(ch); break; case ')': gotParen(ch); break; default: output=output+ch; break; } }
while(!theStack.isEmpty()) { output=output+theStack.pop(); } return output; } public void gotOper(char opThis,int prec1) { while(!theStack.isEmpty()) {
char opTop=theStack.pop(); if(opTop=='(') { theStack.push(opTop); break; } else { int prec2; if(opTop=='+'||opTop=='-') prec2=1; else prec2=2; if(prec2<prec1) { theStack.push(opTop); break; } else output=output+opTop; } } theStack.push(opThis); } public void gotParen(char ch) { while(!theStack.isEmpty()) { char chx=theStack.pop(); if(chx=='(') break; else output=output+chx; } } public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any infix expression"); String input=br.readLine(); String output; InToPost theTrans=new InToPost(input); output=theTrans.doTrans(); System.out.println("postfix is"+output+"\n"); }
class Stack { private int maxSize; private char[] stackArray; private int top; public Stack(int max) { maxSize=max; stackArray=new char[maxSize]; top=-1; } public void push(char j) { stackArray[++top]=j; } public char pop() { return stackArray[top--]; } public char peek() { return stackArray[top]; } public boolean isEmpty() { return (top==-1); } } }
3) AIM: Write a java program that evaluates the postfix expression. PROGRAM CODE:
import java.io.*; class Postfix { public static void main(String args[])throws IOException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter any postfix expression"); String input=br.readLine(); int length=input.length(); Stack st=new Stack(length); int result=0; for(int i=0;i<length;i++) { char ch=input.charAt(i); if(ch>='0'&&ch<='9') st.push((int)ch-'0'); else { int num2=st.pop(); int num1=st.pop(); switch(ch) { case '+': result=num1+num2; break; case '-': result=num1-num2; break; case '*': result=num1*num2; break; case '/': result=num1/num2; break; case '%': result=num1%num2; break; default: result=0; } st.push(result); } } result=st.pop(); System.out.println("the result is :"+result); } } class Stack { private int maxsize;
private int stackArray[]; private int top; public Stack(int max) { maxsize=max; stackArray=new int[maxsize]; top=-1; } public void push(int j) { stackArray[++top]=j; } public int pop() { return stackArray[top--]; } }
EXERCISE:
1. Write a java program to show the use of Linked List class. 2. Write a java program to handle a group of employee objects in an ArrayList.
Week-6
1)AIM: Develop an applet that displays a simple message. PROGRAM CODE
import java.applet.*; import java.awt.*; /*<applet code="myapplet1" height=600 width=300>
</applet> */ public class myapplet1 extends Applet { public int res; public void paint(Graphics g) { g.drawString("hello this is my first applet",30,40); } }
2) AIM: Develop an applet that receives an integer in one textfield and computes its factorial value and returns it in another text field when button named compute is clicked
PROGRAM CODE
import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="myapplet" height=600 width=300> </applet> */
public class myapplet extends Applet implements ActionListener { public Label l1,l2; public TextField t1,t2; public Button b1,b2; public void init() { makeGui(); } public void makeGui() { l1=new Label("enter any no:"); t1=new TextField(10); l1.setBounds(50,50,30,20); t1.setBounds(100,50,30,20); add(l1); add(t1); l2=new Label("Factorial:"); t2=new TextField(30); l2.setBounds(50,100,30,20); t2.setBounds(100,100,30,20); add(l2); add(t2); b1=new Button("calculate"); b2=new Button("cancel"); b1.setBounds(75,150,30,20); b2.setBounds(125,150,30,20); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b1) { double n=Double.parseDouble(t1.getText()); double result=fact(n); t2.setText(" "+ result); } else if(ae.getSource()==b2) { t1.setText(null); t2.setText(null);
EXERCISE:
1. Develop an applet to draw human face. 2. Illustare the concept of parameters passing in applets.
Week-7
AIM: write a java program that works as simple calculator. PROGRAM CODE:
import java.awt.*; import javax.swing.*; import java.awt.event.*;
public class calculator implements ActionListener { char o; int ctr=0; String value=, cv=, oBtn; Double answer, v1, v2; Double NumberConverted; Frame f; Panel p1, p2, p3, p4, p5, p6; private TextField tField; private Menu EditMenu; private MenuBar menuBar; private MenuItem fmi1, fmi2, fmi3; private Button num0, num1, num2, num3, num4, num5, num6, num7, num8, num9; private Button bAdd, bSub, bMul, bDiv, bPer, bSqrt, bFrac, bInt, bDot, bCE, equals, backspace, clear; calculator() { f = new Frame(calculator); menuBar = new MenuBar(); EditMenu = new Menu (Edit); fmi1 = new MenuItem( Copy ); fmi2 = new MenuItem( Paste ); fmi3 = new MenuItem( Quit ); EditMenu.add(fmi1); EditMenu.add(fmi2); EditMenu.addSeparator(); EditMenu.add(fmi3); p1 = new Panel(); p2 = new Panel(); p3 = new Panel(); p4 = new Panel(); p5 = new Panel(); p6 = new Panel(); tField = new TextField(35); num0 = new Button (0); num1 = new Button (1); num2 = new Button (2); num3 = new Button (3); num4 = new Button (4); num5 = new Button (5); num6 = new Button (6); num7 = new Button (7);
num8 = new Button (8); num9 = new Button (9); bAdd = new Button (+); bSub = new Button (-); bMul = new Button (x); bDiv = new Button (/); bPer = new Button (%); bSqrt = new Button (sqrt); bFrac = new Button (1/x); bInt = new Button (+/-); bDot = new Button (.); bCE = new Button (CE); equals = new Button (=); backspace = new Button (Backspace); clear = new Button (C); } public void launchFrame(){ tField.setText(0.); tField.setEnabled(false); menuBar.add(EditMenu); p2.add(backspace); p2.add(bCE); p2.add(clear); p3.add(num7); p3.add(num8); p3.add(num9); p3.add(bDiv); p3.add(bSqrt); p4.add(num4); p4.add(num5); p4.add(num6); p4.add(bMul); p4.add(bPer); p5.add(num1); p5.add(num2); p5.add(num3); p5.add(bSub); p5.add(bFrac); p6.add(num0); p6.add(bInt); p6.add(bDot); p6.add(bAdd); p6.add(equals); p2.setLayout(new GridLayout (1, 3, 2, 2) ); p3.setLayout(new GridLayout (1, 3, 2, 2) ); p4.setLayout(new GridLayout (1, 3, 2, 2) );
p5.setLayout(new GridLayout (1, 3, 2, 2) ); p6.setLayout(new GridLayout (1, 3, 2, 2) ); f.setLayout(new GridLayout (6, 1) ); f.setResizable(false); f.setSize(300,250); f.add(tField); f.add(p2); f.add(p3); f.add(p4); f.add(p5); f.add(p6); f.setVisible(true); f.setMenuBar(menuBar); f.pack(); // ACTION LISTENERS clear.addActionListener(this); bCE.addActionListener(this); num0.addActionListener(this); num1.addActionListener(this); num2.addActionListener(this); num3.addActionListener(this); num4.addActionListener(this); num5.addActionListener(this); num6.addActionListener(this); num7.addActionListener(this); num8.addActionListener(this); num9.addActionListener(this); bAdd.addActionListener(this); bSub.addActionListener(this); bMul.addActionListener(this); bDiv.addActionListener(this); bPer.addActionListener(this); bInt.addActionListener(this); bSqrt.addActionListener(this); bFrac.addActionListener(this); bDot.addActionListener(this); equals.addActionListener(this); backspace.addActionListener(this); fmi1.addActionListener(this); fmi2.addActionListener(this); fmi3.addActionListener(this); } /* |------------ START OF ACTION EVENTS ------------| */ public void actionPerformed(ActionEvent a){
try{ /* |-------- Handling Exceptions ---------| */ if(a.getSource()==num0){ value+=0; tField.setText(value); } if(a.getSource()==num1){ value+=1; tField.setText(value); } if(a.getSource()==num2){ value+=2; tField.setText(value); } if(a.getSource()==num3){ value+=3; tField.setText(value); } if(a.getSource()==num4){ value+=4; tField.setText(value); } if(a.getSource()==num5){ value+=5; tField.setText(value); } if(a.getSource()==num6){ value+=6; tField.setText(value); } if(a.getSource()==num7){ value+=7; tField.setText(value); } if(a.getSource()==num8){ value+=8; tField.setText(value); } if(a.getSource()==num9){ value+=9; tField.setText(value); } if (a.getSource() == bAdd){ v1 = Double.parseDouble( tField.getText() );
ctr=0; o = +; value=; tField.setText( +value); } if (a.getSource() == bSub){ v1 = Double.parseDouble( tField.getText() ); ctr=0; o = -; value=; tField.setText( +value); } if (a.getSource() == bMul){ v1 = Double.parseDouble( tField.getText() ); ctr=0; o = x; value=; tField.setText( +value); } if (a.getSource() == bDiv){ v1 = Double.parseDouble( tField.getText() ); ctr=0; o = /; value=; tField.setText( +value); } if (a.getSource() == bPer){ v1 = Double.parseDouble( tField.getText() ); ctr=0; value=; answer = (v1/100); tField.setText( +answer); } /* |-- EQUALS ACTION --| */ if(a.getSource()==equals){ value=; v2 = Double.parseDouble(tField.getText()); if(o==+){ ctr=0; answer = v1 + v2;
tField.setText( +answer); value=; v1=null; v2=null; } else if(o==-){ ctr=0; answer = v1 v2; tField.setText( +answer); value=; v1=null; v2=null; } else if(o==x){ ctr=0; answer = v1 * v2; tField.setText( +answer); value=; v1=null; v2=null; } else if(o==/){ ctr=0; answer = v1 / v2; tField.setText( +answer); value=; v1=null; v2=null; } else if(o==%){ ctr=0; answer = v1 % v2; tField.setText( +answer); value=; v1=null; v2=null; } else{} }
/* |-- Clear --| */ if(a.getSource()==clear){ ctr=0; v1=null; v2=null; value=; answer=0.; tField.setText(0.); }
if(a.getSource()==bCE){ ctr=0; value=; tField.setText(0.); } /* |-- Point --| */ if(a.getSource() == bDot){ if(ctr==0){ value+=.; ctr+=1; tField.setText( +value); } else{ System.out.print(); } } /* |-- Back Space --| */ if(a.getSource() == backspace){ value = value.substring(0, value.length()-1 ); tField.setText( +value); } /* |-- Square Root --| */ if(a.getSource() == bSqrt){ ctr=0; value = ; v1 = Math.sqrt( Double.parseDouble( tField.getText() ) ); tField.setText( +v1); }
/* |-- Integer --| */ if(a.getSource() == bInt){ ctr=0; NumberConverted = ( Double.parseDouble(tField.getText()) * -1 ); value = ; tField.setText( +NumberConverted); } /* |-- Reciprocal --| */ if(a.getSource() == bFrac){ ctr=0; value = ;
Double NumberContainer = ( 1 / Double.parseDouble( tField.getText() ) ); tField.setText( +NumberContainer); } // ------------ Menu Item Actions ------------ // if(a.getSource() == fmi1){ cv = tField.getText(); } if(a.getSource() == fmi2){ tField.setText( +cv); } if(a.getSource() == fmi3){ System.exit(0); } } // End of Try catch(StringIndexOutOfBoundsException str){} catch(NumberFormatException nfe){} catch(NullPointerException npe){} } // END OF ACTION EVENTS
public static void main (String args[]){ calculator s = new calculator(); s.launchFrame(); } }
EXERCISE:
1. write a java program to create a Login form. 2. create a swing application which adds a menu bar containing the items File,Edit,Window and Help.
Week-8
AIM: Write a java program for handling mouse events. PROGRAM CODE:
import java.awt.*; import java.applet.Applet;
import java.awt.event.*; /*<applet code="Mouseevents"width=200 height=100> </applet>*/ public class Mouseevents extends Applet implements MouseListener,MouseMotionListener { String msg=""; int x=0,y=0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { x=10; y=20; msg="mouse clicked"; repaint(); } public void mouseEntered(MouseEvent me) { x=10; y=20; msg="mouse entered"; repaint(); } public void mouseExited(MouseEvent me) { x=10; y=20; msg="mouse exited"; repaint(); }
public void mousePressed(MouseEvent me) { x=me.getX(); y=me.getY(); msg="down"; repaint(); } public void mouseReleased(MouseEvent me) { x=me.getX();
y=me.getY(); msg="up"; repaint(); } public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg="*"; showStatus("dragging mouse at"+x+","+y); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("moving mouse at"+me.getX()+","+me.getY()); } public void paint(Graphics g) { g.drawString(msg,x,y); } }
EXERCISE:
1. Write a java program for handling Keyboard events. 2. Write a java program that illustrates the concept of listeners.
Week-9
1) AIM: Write a java program that creates three threads and displays every message of the thread
with some time gap.
PROGRAM CODE:
import java.io.*; class MyThread1 extends Thread
{ public void run() { try { while(true) { System.out.println("Good Morning"); this.sleep(1000); } } catch(InterruptedException e) { System.out.println(e); } } } class MyThread2 extends Thread { public void run() { try { while(true) { System.out.println("Hello"); this.sleep(2000); } } catch(InterruptedException e) { System.out.println(e); } } }
System.out.println("Welcome"); this.sleep(3000); } } catch(InterruptedException e) { System.out.println(e); } } } class Demo { public static void main(String args[]) { MyThread1 m1=new MyThread1(); MyThread2 m2=new MyThread2(); MyThread3 m3=new MyThread3(); m1.start(); m2.start(); m3.start(); } }
PROGRAM CODE:
import java.io.*; import java.util.*; class Q {
int n; boolean valueSet=false; synchronized int get() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got:"+n); valueSet=false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n=n; valueSet=true; System.out.println("Put:"+n); notify(); } }
public void run() { int i=0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q=q; new Thread(this,"Consumer").start(); } public void run() { while(true) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q=new Q(); new Producer(q); new Consumer(q); System.out.println("Press control-C to stop."); } }
Put:2 Got:2 Put:3 Got:3 Put:4 Got:4 Put:5 Got:5 Put:6 Got:6 Put:7 Got:7 Put:8 Got:8 Put:9 Got:9
EXERCISE:
1 Write a program showing execution of multiple tasks with a single thread. 2 Write a program showing two threads acting upon single object.
Week-10
AIM: Write a java program that implements simple client server application. PROGRAM CODE:
/*Client Side*/ import java.net.*; import java.io.*; class NetClient { public static void main(String[] args) { try { Socket server=new Socket(localhost,9393); System.out.println(Client joined server) BuferedReader br=new BufferedReader(new InputStreamReader(server.getInputStream()); String input=br.readLine(); System.out.println(server says+input); } catch(Exception e) { System.out.println(Error+e); } } }
/*Server Side */ import java.net.*; import java.io.*; class NetServer { public static void main(Strings []args) { try { ServerSocket server=new ServerSocket(9393); System.out.println(Server mounted in 9393 and waiting for client to join); Socket client; Client=sever.accept(); System.out.println(client joined with ip+client.getInetAddress().getHostAddress()+with name+client.getInetAddress().getHostName()); PrinterWriter cout=new PrinterWriter(client.getOutPutStream(),true); cout.println(Hello client Welcome to NetServer.date is+(new java.util.Date()); System.out.println(Message sent to client); try { Thread.currentThread().join(); } Catch(Exception e) { System.out.println(Error+e); } } Catch(Exception e) { System.out.println(error+e); } } }
C:/>java NetServer Server mounted in 9393 and waiting for client to join client joined with ip127.0.0.1 with name localhost message sent to client
EXERCISE:
1. Write a program that accepts the filename and checks for its existence. When the file exists at server side, it sends it contents to client.
Week-11
1) AIM: Write a java program that simulates traffic light. PROGRAM CODE:
import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code=traffic height=500 width=500> </applet>*/ public class traffic extends Applet implements Runnable { Thread t; Font f,f1; int i=0,a=0,j=0; public void init() { setBackground(Color.lightGray); f=new Font("TimesNewRoman",f.ITALIC,28); f1=new Font("TimesNewRoman",Font.ITALIC+Font.BOLD,28); } public void start() { t=new Thread(this); t.start(); } public void run() { for(i=25;i>=0;i--)//countdown { try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); }
if(i<=25 && i>3)//red { a=1; repaint(); } else if(i<=3 && i>0)//yelloe { a=2; repaint(); } else if(i==0)//green { for(j=0;j<25;j++) { a=3; try { Thread.sleep(1000); } catch(Exception e) { System.out.println(e); } repaint(); } if(j==25)//end of green(return to red) { run(); } } } repaint(); } public void paint(Graphics g) { setBackground(Color.lightGray);//ROAD g.setColor(Color.black);//pole top g.fillArc(100,150,100,100,0,180); g.drawArc(100,150,100,100,0,180); g.setColor(Color.black);//POLE UP g.fillRect(150,150,50,150); g.drawRect(150,150,50,150);
g.setColor(Color.black);//POLE DOWN g.fillRect(165,300,20,155); g.drawRect(165,300,20,155); g.drawOval(150,150,50,50);//RED g.drawOval(150,200,50,50);//YELLOW g.drawOval(150,250,50,50);//GREEN g.setColor(Color.red);//COUNTDOWN STOP g.setFont(f); g.drawString(""+i,50,50); if(a==1)//REDSIGNAL { g.setColor(Color.red); g.fillOval(150,150,50,50); g.drawOval(150,150,50,50); g.drawString("STOP",50,150); } if(a==2)//YELLOWSIGNAL { g.setColor(Color.yellow); g.fillOval(150,200,50,50); g.drawOval(150,200,50,50); g.drawString("READY",50,200); } if(a==3)//GREENSIGNAL { g.setColor(Color.blue);//countdown g.setFont(f); g.drawString(""+j,150,50); g.setColor(Color.green); g.fillOval(150,250,50,50); g.drawOval(150,250,50,50); g.drawString("GO",50,250); } int x1[]={220,300,300,280}; int y1[]={250,150,250,150}; int n1=4; int n2=3; int x2[]={340,380,380}; int y2[]={150,100,150}; int x3[]={460,460,500}; int y3[]={150,100,150}; g.setColor(Color.black);
} }
2) AIM: Write a java program that allows user to draw lines rectangles and ovals.
PROGRAM CODE:
import java.awt.*; import java.applet.*; /* <applet code="Ellipses" width=300 height=200> </applet> */ public class Ellipses extends Applet { public void paint(Graphics g) { g.drawOval(10,10,50,50); g.fillOval(100,10,75,50); g.drawOval(190,10,90,30); g.fillOval(70,90,140,100); g.drawLine(20,150,400,40); g.drawLine(40,25,250,180); g.drawLine(0,0,100,100); g.drawRect(10,10,60,50); g.fillRect(100,10,60,50); g.drawArc(10,40,70,70,0,75); g.fillArc(100,40,70,70,0,75); } }
EXERCISE:
1. Write a java program to throw a user defined exception. 2. Write a program which tells the use of try, catch and finally block.
Week-12
AIM: Write a java program that illustrates the concept of abstract classes.. PROGRAM CODE:
import java.io.*; abstract class Shape { abstract void noofSlides(); } class Trapezoid extends Shape { void noofSlides() { System.out.print("no.of slides of Trapezoid =4"); } } class Triangle extends Shape { void noofSlides()
{ System.out.print("no.of slides ofTriangle =3"); } } class Hexagon extends Shape { void noofSlides() { System.out.print("no.of slides of Hexogon =6"); } } class Polygon { public static void main(String args[])throws IOException { Shape s; Trapezoid t=new Trapezoid(); s=t; s.noofSlides(); Triangle tr=new Triangle(); s=tr; s.noofSlides(); Hexagon h=new Hexagon(); s=h; s.noofSlides(); } }
EXERCISE:
1) Write a java program that illustrate how to achieve multiple inheritance using interfaces. 2) Write a program that illustrates the concept of creating user defined packages.