83115ii b.tech ii sem_r10_ java lab manual

40
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Prepared by B Padmaja 1 PROGRAM-1: AIM: The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it. Write A Java Program (WAJP) that uses both recursive and non-recursive functions to print the n th value of the Fibonacci sequence. CODE: import java.util.*; import java.io.*; class FiboSeq { static int rec_fibo(int n) { if(n==1||n==0) return n; else return (rec_fibo(n-1)+rec_fibo(n-2)); } static int nonrec_fibo(int n) { int term1=1,term2=1,term=1; if(n==1||n==2) return 1; else { for(int i=1;i<=n-2;i++) { term=term1+term2; term1=term2; term2=term; } } return term; } public static void main(String args[]) { int f; Scanner s=new Scanner(System.in); System.out.println("Enter the Fibonacci number to display:"); int n=s.nextInt(); System.out.println("Enter ur option:"); System.out.println("1.Recursive Fibonacci Search"); System.out.println("2.Non Recursive Fibonacci Search"); int opt=s.nextInt(); switch(opt) { case 1:

Upload: pelluri-manjunath

Post on 13-Apr-2015

68 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 1

PROGRAM-1: AIM: The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding it. Write A Java Program (WAJP) that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence. CODE: import java.util.*; import java.io.*; class FiboSeq { static int rec_fibo(int n) { if(n==1||n==0) return n; else return (rec_fibo(n-1)+rec_fibo(n-2)); } static int nonrec_fibo(int n) { int term1=1,term2=1,term=1; if(n==1||n==2) return 1; else { for(int i=1;i<=n-2;i++) { term=term1+term2; term1=term2; term2=term; } } return term; } public static void main(String args[]) { int f; Scanner s=new Scanner(System.in); System.out.println("Enter the Fibonacci number to display:"); int n=s.nextInt(); System.out.println("Enter ur option:"); System.out.println("1.Recursive Fibonacci Search"); System.out.println("2.Non Recursive Fibonacci Search"); int opt=s.nextInt();

switch(opt) { case 1:

Page 2: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 2

f=rec_fibo(n); System.out.println("N th Fibonacci number is:"+f); break; case 2: f=nonrec_fibo(n); System.out.println("N th Fibonacci number is:"+f); break; default: System.out.println("Enter any valid option"); } } } OUTPUT:

Page 3: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 3

PROGRAM-2: AIM: WAJP to demonstrate wrapper classes, and to fix the precision. CODE: import java.text.*; import java.util.*; class Precision { public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter any fraction value:"); float f=s.nextFloat(); NumberFormat nf=NumberFormat.getInstance(); nf.setMaximumFractionDigits(3);

String st=nf.format(f); System.out.println("Fraction number set to precision 3 is:"+st.toString()); } } OUTPUT:

Page 4: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 4

PROGRAM-3: AIM: WAJP that prompts the user for an integer and then prints out all the prime numbers up to that Integer CODE: import java.util.*; class Prime { public static void main(String args[]) { int i,n,j,count; Scanner p=new Scanner(System.in); System.out.println("enter the numbter :"); n=p.nextInt(); System.out.println("Prime numbers are :"); for(i=1;i<=n;i++) { count=0; for(j=1;j<=i;j++) { if(i%j==0) count++; } if(count==2) System.out.println("\t" +i); } } } OUTPUT:

Page 5: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 5

PROGRAM-4: AIM: WAJP to check whether a given string is a palindrome or not CODE: import java.util.*; class Palindrome { public static void main (String args[]) { String str1=new String(); Scanner obj=new Scanner(System.in); System.out.println("enter the string"); str1=obj.next(); StringBuffer str2=new StringBuffer(str1); str2.reverse(); String str3=str2.toString(); if(str1.equalsIgnoreCase(str3)) System.out.println("Given String is Palindrome"); else System.out.println("Given String is not Palindrome"); } } OUTPUT:

Page 6: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 6

PROGRAM-5: AIM: WAJP for sorting a given list of names in ascending order CODE:

import java.util.*; class StringSort { public static void main(String args[]) { int size,i; Scanner obj=new Scanner(System.in); System.out.println("enter the size of the array"); size=obj.nextInt(); String arr[]=new String[size]; System.out.println("enter the array of the string"); for(i=0;i<size;i++) { arr[i]=obj.next(); } System.out.println("given string array before sorting are"); for(i=0;i<size;i++) { System.out.println(" "+arr[i]); } Arrays.sort(arr); System.out.println("given string array after sorting are"); for(i=0;i<size;i++) { System.out.println(""+arr[i]); } } } OUTPUT:

Page 7: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 7

PROGRAM-6: AIM: WAJP to check the compatibility for multiplication, if compatible multiply two matrices and find its transpose. CODE: import java.util.*; class MatrMul { static void readMatrix(int a[][],int r,int c) { Scanner s=new Scanner(System.in); for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { a[i][j]=s.nextInt(); } } } static void writeMatrix(int a[][],int r,int c) { for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { System.out.print(" "+a[i][j]); } System.out.println(); } } static void mulMatrix(int a[][],int b[][],int c[][],int r1,int c1,int r2) { for(int i=0;i<r1;i++) { for(int j=0;j<c1;j++) { c[i][j]=0; for(int k=0;k<r2;k++) { c[i][j]+=a[i][k]*b[k][j]; } } } } static void transposeMatrix(int a[][],int tr[][],int r,int c) { for(int i=0;i<r;i++)

Page 8: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 8

{ for(int j=0;j<c;j++) { tr[i][j]=a[j][i]; } } } public static void main(String args[]) { Scanner s=new Scanner(System.in); int m1[][]=new int[10][10]; int m2[][]=new int[10][10]; int m3[][]=new int[10][10]; int t[][]=new int[10][10]; int m,n,p,q; System.out.println("Enter first matrix dimensions:"); m=s.nextInt(); n=s.nextInt(); System.out.println("Enter second matrix dimensions:"); p=s.nextInt(); q=s.nextInt(); if(n!=p) { System.out.println("Matrix multiplication is not possible:"); System.exit(0); } System.out.println("Enter first matrix:"); readMatrix(m1,m,n); System.out.println("Enter second matrix:"); readMatrix(m2,p,q); mulMatrix(m1,m2,m3,m,n,q); System.out.println("Multiplication of given two matrices is:"); writeMatrix(m3,m,q); transposeMatrix(m3,t,m,q); System.out.println("Transpose of matrix multiplication is:"); writeMatrix(t,m,q); } } OUTPUT:

Page 9: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 9

PROGRAM-7: AIM: WAJP that illustrates how runtime polymorphism is achieved CODE: class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } double area() { System.out.println("Area for Figure is undefined."); return 0; } } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); figref = f; System.out.println("Area is " + figref.area()); } }

Page 10: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 10

OUTPUT:

Page 11: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 11

PROGRAM-8: AIM: WAJP to create and demonstrate packages CODE: Protection.java: package p1; public class Protection { int n = 1; private int n_pri = 2; protected int n_pro = 3; public int n_pub = 4; public Protection() { System.out.println("base constructor"); System.out.println("n = " + n); System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); } } Derived.java: package p1; class Derived extends Protection { Derived() { System.out.println("derived constructor"); System.out.println("n = " + n); // class only // System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); } } SamePackage.java: package p1; class SamePackage { SamePackage() { Protection p = new Protection(); System.out.println("same package constructor"); System.out.println("n = " + p.n); // class only // System.out.println("n_pri = " + p.n_pri); System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub);

Page 12: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 12

} } Protection2.java: package p2; class Protection2 extends p1.Protection { Protection2() { System.out.println("derived other package constructor"); // class or package only // System.out.println("n = " + n); // class only // System.out.println("n_pri = " + n_pri); System.out.println("n_pro = " + n_pro); System.out.println("n_pub = " + n_pub); } } OtherPackage.java: package p2; class OtherPackage { OtherPackage() { p1.Protection p = new p1.Protection(); System.out.println("other package constructor"); // class or package only // System.out.println("n = " + p.n); // class only // System.out.println("n_pri = " + p.n_pri); // class, subclass or package only // System.out.println("n_pro = " + p.n_pro); System.out.println("n_pub = " + p.n_pub); } } // Demo package p1. package p1; // Instantiate the various classes in p1. public class Demo { public static void main(String args[]) { Protection ob1 = new Protection(); Derived ob2 = new Derived(); SamePackage ob3 = new SamePackage(); } }

Page 13: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 13

OUTPUT:

// Demo package p2. package p2; // Instantiate the various classes in p2. public class Demo { public static void main(String args[]) { Protection2 ob1 = new Protection2(); OtherPackage ob2 = new OtherPackage(); } } OUTPUT:

Page 14: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 14

PROGRAM-9 AIM: WAJP, using StringTokenizer class, which reads a line of integers and then displays each integer and the sum of all integers CODE: import java.util.*; import java.lang.*; class Lineint { public static void main(String args[]) { String str1=new String(); String str2=new String(); int sum=0; Scanner obj=new Scanner(System.in); System.out.println("Enter the line of Numbers"); str1=obj.nextLine(); StringTokenizer st=new StringTokenizer(str1," "); while(st.hasMoreTokens()) { sum=sum + Integer.parseInt(st.nextToken()); } System.out.println("Sum of line of Numbers is:"+ sum); } } OUTPUT:

Page 15: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 15

PROGRAM-10 AIM: WAJP that reads on file name from the user then displays information about whether the file exists, whether the file is readable/writable, the type of file and the length of file in bytes and displays the content of the file using FileInputStream class CODE: import java.io.*; import java.util.Scanner; class FileDemo { public static void main(String args[])throws IOException { String fname; Scanner obj=new Scanner(System.in); System.out.println("Enter any file name:"); fname=obj.nextLine(); File f1 = new File(fname); System.out.println("File Name: " + f1.getName()); System.out.println("Path: " + f1.getPath()); System.out.println("Abs Path: " + f1.getAbsolutePath()); System.out.println("Parent: " + f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: " + f1.lastModified()); System.out.println("File size: " + f1.length() + " Bytes"); System.out.println("Contents of given file are:"); int n=0; int s; if(f1.exists()) { FileInputStream fs=new FileInputStream(f1); BufferedInputStream br=new BufferedInputStream(fs); while((s=br.read())!=-1) { System.out.print((char)s); } } else { System.out.println("File does not exist"); } } }

Page 16: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 16

OUTPUT:

Page 17: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 17

PROGRAM-11

AIM: WAJP that displays number of characters, lines and words in a text file

CODE:

import java.io.*; import java.util.Scanner; class FileDemo { public static void main(String args[])throws IOException { String fname; Scanner obj=new Scanner(System.in); System.out.println("Enter any file name:"); fname=obj.nextLine(); File f1 = new File(fname); int s,nl=0,nc=0,nw=0; if(f1.exists()) { FileReader fs=new FileReader(f1); BufferedReader br=new BufferedReader(fs); while((s=br.read())!=-1) { if(s=='\n') nl++; else if(s==' ') nw++; else nc++;

} System.out.println("Number of lines is:"+nl); System.out.println("Number of words is:"+nw); System.out.println("Number of chars is:"+nc); } else {

System.out.println("File does not exist"); }

} } OUTPUT:

Page 18: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 18

PROGRAM-12 AIM: Write an applet that displays the content of a file CODE: AppletFile.html <applet code="AppletFile" height=300 width=400> </applet> AppletFile.java import java.awt.*; import java.applet.*; import java.io.*; import java.util.*; public class AppletFile extends Applet { String str1,str2; int x=30,y=40; public void init() { File f=new File("AppletFile.java"); if(f.exists()) { try { FileReader fr=new FileReader(f); BufferedReader br=new BufferedReader(fr); while((str1=(br.readLine()))!=null) { str2+=str1; repaint(); } } catch(Exception e){e.printStackTrace();} } else str2="File Not Found"; } public void paint(Graphics g)

{ g.drawString(str2,x,y); } } OUTPUT:

Page 19: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 19

PROGRAM-13 AIM: 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. CODE: import java.awt.*; import java.applet.*; import java.awt.event.*; public class Calculator extends Applet implements ActionListener { TextField t1; String a=" ",b; String oper="",s="",p=""; int first=0,second=0,result=0; Panel p1; Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9; Button add,sub,mul,div,mod,res,space; public void init() { Panel p2,p3; p1=new Panel(); p2=new Panel(); p3=new Panel(); t1=new TextField(a,20); p1.setLayout(new BorderLayout()); p2.add(t1); b0=new Button("0"); b1=new Button("1"); b2=new Button("2"); b3=new Button("3"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("7"); b8=new Button("8"); b9=new Button("9"); add=new Button("+"); sub=new Button("-"); mul=new Button("*"); div=new Button("/"); mod=new Button("%"); res=new Button("="); space=new Button("c"); p3.setLayout(new GridLayout(4,4)); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this);

Page 20: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 20

b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); add.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); div.addActionListener(this); mod.addActionListener(this); res.addActionListener(this); space.addActionListener(this); p3.add(b0); p3.add(b1); p3.add(b2); p3.add(b3); p3.add(b4); p3.add(b5); p3.add(b6); p3.add(b7); p3.add(b8); p3.add(b9); p3.add(add); p3.add(sub); p3.add(mul); p3.add(div); p3.add(mod); p3.add(res); p3.add(space); p1.add(p2,BorderLayout.NORTH); p1.add(p3,BorderLayout.CENTER); add(p1); } public void actionPerformed(ActionEvent ae) { a=ae.getActionCommand(); if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"|| a=="9") { t1.setText(t1.getText()+a); } if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%") { first=Integer.parseInt(t1.getText()); oper=a; t1.setText(""); } if(a=="=") { if(oper=="+") result=first+Integer.parseInt(t1.getText()); if(oper=="-") result=first-Integer.parseInt(t1.getText()); if(oper=="*")

Page 21: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 21

result=first*Integer.parseInt(t1.getText()); if(oper=="/") result=first/Integer.parseInt(t1.getText()); if(oper=="%") result=first%Integer.parseInt(t1.getText()); t1.setText(result+""); } if(a=="c") t1.setText(""); } } /*<applet code=Calculator width=200 height=200></applet>*/ OUTPUT:

Page 22: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 22

PROGRAM 14 AIM: Write a Java program for handling mouse events. CODE: import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" width=300 height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = " "; int mouseX = 0, mouseY = 0; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } public void mouseEntered(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } public void mouseExited(MouseEvent me) { mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } public void mousePressed(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } public void mouseReleased(MouseEvent me) { mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } public void mouseDragged(MouseEvent me) { mouseX = me.getX();

Page 23: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 23

mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } public void mouseMoved(MouseEvent me) { showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } OUTPUT:

Page 24: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 24

PROGRAM-15 AIM: WAJP demonstrating the life cycle of a thread CODE: class NewThread implements Runnable { Thread t; NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); System.out.println("This is the Runnable state of Thread"); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { System.out.println("This is the Running state of a thread"); try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); System.out.println("This is the Blocking state of Thread"); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("The Thread is going to dead state"); } } class ThreadDemo { public static void main(String args[]) { System.out.println("This is the new state of thread"); new NewThread(); // create a new thread } } OUTPUT:

Page 25: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 25

PROGRAM-16 AIM: Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. CODE: import java.lang.*; import java.lang.Thread; class Q { int n; boolean valueSet=false; synchronized int get() { if(!valueSet) try{ wait(); } catch(InterruptedException e) { System.out.println("InterruptedException catch"); } 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 catch"); } this.n=n; valueSet=true; System.out.println("put:"+n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q=q; new Thread(this,"producer").start(); } public void run()

Page 26: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 26

{ 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); } } OUTPUT:

Page 27: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 27

PROGRAM-17 AIM: WAJP that allows user to draw Lines, rectangles and ovals CODE: import java.awt.*; import java.applet.*; public class Draw extends Applet { public void paint(Graphics g) { g.setColor(Color.BLUE); g.drawLine(3,4,10,23); g.drawOval(195,100,90,55); g.drawRect(100,40,90,5); g.drawRoundRect(140,30,90,90,60,30); } } /*<applet code="Draw.class" width=300 height=300></applet>*/ OUTPUT:

Page 28: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 28

PROGRAM-18 AIM: 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) Client.java CODE: import java.io.*; import java.net.*; class Client { public static void main(String ar[])throws Exception { Socket s=new Socket(InetAddress.getLocalHost(),10000); System.out.println("enter the radius of the circle "); DataInputStream dis=new DataInputStream(System.in); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(n); DataInputStream dis1=new DataInputStream(s.getInputStream()); System.out.println("area of the circle from server:"+dis1.readLine()); } } Server.java CODE: import java.io.*; import java.net.*; class Server { public static void main(String ar[])throws Exception { ServerSocket ss=new ServerSocket(10000); Socket s=ss.accept(); DataInputStream dis=new DataInputStream(s.getInputStream()); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(3.14*n*n); } }

Page 29: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 29

OUTPUT:

Page 30: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 30

PROGRAM-19 AIM: 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. CODE: import java.lang.*; abstract class Shape { abstract void numberOfSides(); } class Traingle extends Shape { public void numberOfSides() { System.out.println("three"); } } class Trapezoid extends Shape { public void numberOfSides() { System.out.println("four"); } } class Hexagon extends Shape { public void numberOfSides() { System.out.println("six"); } } public class Sides { public static void main(String arg[]) { Traingle T=new Traingle(); Trapezoid Ta=new Trapezoid(); Hexagon H=new Hexagon(); T.numberOfSides(); Ta.numberOfSides(); H.numberOfSides(); } }

Page 31: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 31

OUTPUT:

Page 32: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 32

PROGRAM-20: AIM: WAJP that lets users create Pie charts. Design your own user interface (with Swings&AWT) CODE: import java.awt.*; import javax.swing.*; import java.awt.event.*; public class PieChart extends JFrame { private Font font; public PieChart () { super( "Hardware Store Sales: August" ); setSize( 600, 400 ); setLocation( 70, 70 ) ; show(); } public void paint( Graphics g ) { font = new Font("Sanserif", Font.BOLD, 14); // start at 0 and sweep 360 degrees g.setColor( Color.black ); g.fillArc( 110, 80, 300, 300, 0, 36 ); g.drawString("Hand Tool Sales: 10%", 420, 80); g.setColor( Color.red ); g.fillArc( 110, 80, 300, 300, 36, 120 ); g.drawString("Power Tool Sales: 33%", 420, 100); g.setColor( Color.blue ); g.fillArc( 110, 80, 300, 300, 156, 80 ); g.drawString("Lawn Mower Sales: 22%", 420, 120); g.setColor( Color.green ); g.fillArc( 110, 80, 300, 300, 236, 80 ); g.drawString("Bench Tools Sales: 22%", 420, 140); g.setColor( Color.white ); g.fillArc( 110, 80, 300, 300, 316, 44 ); g.drawString("Tool Accessories Sales: 12%", 420, 160); g.setColor( Color.black ); g.drawArc( 110, 80, 300, 300, 0, 360 ); }

Page 33: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 33

public static void main( String args[] ) { PieChart app = new PieChart (); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } } OUTPUT:

Page 34: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 34

PROGRAM-21: AIM: Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the base class provide methods that are common to all Rodents and override these in the derived classes to perform different behaviors, depending on the specific type of Rodent. Create an array of Rodent, fill it with different specific types of Rodents and call your base class methods. CODE: class Rodent { void eat() { } } class Mouse extends Rodent { void eat() { System.out.println("Mouse is eating"); } } class Gerbil extends Rodent { void eat() { System.out.println("Gerbil is eating"); } } class Hamster extends Rodent { void eat() { System.out.println("Hamster is eating"); } } public class Test1 { public static void main(String args[]) { Rodent r[]=new Rodent[3]; r[0]=new Mouse(); r[1]=new Gerbil(); r[2]=new Hamster(); r[0].eat(); r[1].eat(); r[2].eat(); } } OUTPUT:

Page 35: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 35

PROGRAM-22 AIM: WAJP to generate a set of random numbers between two numbers x1 and x2, and x1>0. CODE: import java.util.Random; public class Exercise { public static void main(String[] args) { Random rndNumbers = new Random(); int rndNumber = 0; for (int nbr = 1; nbr < 9; nbr++) { rndNumber = rndNumbers.nextInt(20); System.out.println("Number: " + rndNumber); } } } OUTPUT:

Page 36: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 36

PROGRAM-23: AIM: 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. CODE: class First implements Runnable { Thread t; First() { t=new Thread(this); System.out.println("Good Morning"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("Good Morning"+i); try{ t.sleep(1000); } catch(Exception e) { System.out.println(e); } } } } class sec implements Runnable { Thread t; sec() { t=new Thread(this); System.out.println("hello"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("hello"+i); try{ t.sleep(2000); } catch(Exception e) { System.out.println(e); }

Page 37: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 37

} } } class third implements Runnable { Thread t; third() { t=new Thread(this); System.out.println("welcome"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("welcome"+i); try{ t.sleep(3000); } catch(Exception e) { System.out.println(e); } } } } public class Multithread { public static void main(String arg[]) { new First(); new sec(); new third(); } } OUTPUT:

Page 38: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 38

PROGRAM-24 AIM: WAJP to implement a Queue using user defined Exception Handling (also makes use of throw,throws) CODE: import java.util.*; class QueueOverFlowsException extends Exception { QueueOverFlowsException(String msg) { super(msg); } } class QueueUnderFlowsException extends Exception { QueueUnderFlowsException(String msg) { super(msg); } } class ArrayQueue { int a[]=new int[5],front,rear; ArrayQueue() { front=-1; rear=-1; } void enqueue(int x)throws QueueOverFlowsException { if(rear==4) throw new QueueOverFlowsException("QueueOverFlows"); else { rear++; a[rear]=x; } } int dequeue()throws QueueUnderFlowsException { int x; if(front==-1) throw new QueueUnderFlowsException("QueueUnderFlows"); else { x=a[front]; front++; } return x;

Page 39: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 39

} void display() { for(int i=0;i<=rear;i++) { System.out.print("\t"+a[i]); } } } class QueueDemo { public static void main(String args[])throws QueueUnderFlowsException,QueueOverFlowsException { ArrayQueue as=new ArrayQueue(); int opt; while(true) { System.out.println("1.Enqueue"); System.out.println("2.Dequeue"); System.out.println("3.Display"); System.out.println("4.Exit"); System.out.println("Enter ur option:"); Scanner s=new Scanner(System.in); opt=s.nextInt(); switch(opt) { case 1: System.out.println("Enter the element to insert:"); int n=s.nextInt(); as.enqueue(n); System.out.println("Element is inserted"); break; case 2: int x=as.dequeue(); System.out.println("Element"+x+"is deleted"); break; case 3: as.display(); break; case 4: System.exit(0); } } } }

Page 40: 83115II B.tech II Sem_R10_ Java Lab Manual

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Prepared by B Padmaja 40

OUTPUT: