Anda di halaman 1dari 116

Object Oriented Programming LAB MANUAL A Helpful Hand DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CSEROCKZ Copyright cserockz08,

, 2009 www.cserockz.com Page 1

Object Oriented Programming LAB MANUAL OBJECT ORIENTED PROGRAMMING: OOP Concepts: The object oriented paradigm is built on the foundation laid by th e structured programming concepts. The fundamental change in OOP is that a progr am is designed around the data being operated upon rather upon the operations th emselves. Data and its functions are encapsulated into a single entity.OOP facil itates creating reusable code that can eventually save a lot of work. A feature called polymorphism permits to create multiple definitions for operators and fun ctions. Another feature called inheritance permits to derive new classes from ol d ones. OOP introduces many new ideas and involves a different approach to progr amming than the procedural programming. Benefits of object oriented programming: Data security is enforced. Inheritance saves time. User defined data types can be easily constructed. Inheritance emphasizes inventions of new data types. Copyright cserockz08, 2009 www.cserockz.com Page 2

Object Oriented Programming LAB MANUAL Large complexity in the software development cn be easily managed. Basic C++ Kno wledge: C++ began its life in Bell Labs, where Bjarne Stroustrup developed the l anguage in the early 1980s. C++ is a powerful and flexible programming language. Thus, with minor exceptions, C++ is a superset of the C Programming language. T he principal enhancement being the object oriented concept of a class. A Class is a user defined type that encapsulates many important mechanisms. Classes enable programmers to break an application up into small, manageable pieces, or object s. Basic concepts of Object oriented programming: Object: Objects are the basic run time entities in an object-oriented system. thy may represent a person, a pl ace, a bank account, a table of data or any item that the program has to handle. Class: The entire set of data and code of an object can be made of a user defin ed data type with the help of a class. I fact, Objects are variables of the type class. Once a class has been defined, we can create any number of objects belon ging to that class A class is thus a collection of objects of similar type. for example: mango, apple, and orange are members of the class fruit. ex: fruit mang o; will create an object mango belonging to the class fruit. Data Abstraction an d Encapsulation: The wrapping up of data and functions in to a single unit is kn own as encapsulation. Data encapsulation is the most striking feature of a class . The data is not accessible to the outside world, and only those functions whic h are wrapped in the class can access. This insulation of the data from direct a ccess by the program is called data hiding. Copyright cserockz08, 2009 www.cserockz.com Page 3

Object Oriented Programming LAB MANUAL Abstraction : Abstraction referes to the act of representing essential features without including the background details or explanations. since the classes use the concept of data abstraction ,thy are known as abstraction data type(ADT). In heritance : Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hie rarchical classification. for example: Bird Attributes: Feathers Lay eggs Flying bird Attributes: -------------------Non flying bird Attributes: --------------------Robin Attributes: _________ Swallow Attributes: _________ Penguin Attributes: _________ Kiwi Attributes: _________ The bird 'robin ' is a part of the class 'flying bird' which is agian a part of the class 'bird'. The concept of inheritance provide the idea of reusability. Copyright cserockz08, 2009 www.cserockz.com Page 4

Object Oriented Programming LAB MANUAL POLYMORPHISM: Polymorphism is another important oop concept. Polymorphism means the ability to take more than one form. an operation may exhibit different insta nces. The behavior depends upon the types of data used in the operation. The pro cess of making an operator to exhibit different behaviors in different instance is known as operator overloading. Polymorphism plays an important role in allowi ng objects having different internal structures to share the same external inter face. Polymorphism is extensively used if implementing inheritance. Shape Draw() Circle Object Draw() Box Object Draw() Triangle Object Draw() The Object-Oriented Approach The fundamental idea behind object-oriented languag es is to combine into a single program entity both data and the functions that o perate on that data. Such an entity is called an object. An object's functions, called member functions in C++ (because they belong to a particular class of obj ects), typically provide the only way to access its data. If you want to read a data item in an object, you call a member function in the object. It will read t he item and return the value to you. You can't access the data directly. The dat a is hidden, so it is safe from accidental alteration. Data and its functions ar e said to be encapsulated into a single entity. Encapsulation and data hiding ar e key terms in the description of object-oriented languages. Copyright cserockz08, 2009 www.cserockz.com Page 5

Object Oriented Programming Java History: LAB MANUAL Java is a general-purpose; object oriented programming language developed by Sun Microsystems of USA in 1991. Originally called oak by James Gosling, one of the i nventors if the language. This goal had a strong impact on the development team to make the language simple, portable, highly reliable and powerful language. Ja va also adds some new features. While C++ is a superset of C. Java is neither a superset nor a subset of C or C++. C++ C Java Copyright cserockz08, 2009 www.cserockz.com Page 6

Object Oriented Programming LAB MANUAL Process of building and running java application programs: Text Editor Java Source Code Javadoc HTML files Javac Java Class File Javah Header Files Java (only file name) Jdb (database) Java program Output The way these tools are applied to build and run application programs is create a program. We need create a source code file using a text editor. The source cod e is then compiled using the java compiler javac and executed using the java int erpreter java. The java debugger jdb is used to find errors. A complied java pro gram can be converted into a source code. Copyright cserockz08, 2009 www.cserockz.com Page 7

Object Oriented Programming LAB MANUAL JAVA PROGRAMMING LAB PROGRAMS LIST 1. 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 discriminan t b2-4ac is negative, display a message stating that there are no real solutions . 2. 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 pre ceding it. Write a Java program that uses both recursive and non-recursive funct ions to print the nth value of the Fibonacci sequence. 3. WAJP that prompts the user for an integer and then prints out all the prime numbers up to that Integer . 4. WAJP that checks whether a given string is a palindrome or not. Ex: MADAM i s a palindrome. 5. WAJP for sorting a given list of names in ascending order. 6. WAJP to multiply two given matrices. 7. WAJP that reads a line of integers and then displays each integer and the sum of all integers. (use StringTokenizer cla ss) 8. WAJP that reads on file name from the user, then displays information abo ut whether the file exists, whether the file is readable, whether the file is wr itable, the type of file and the length of the file in bytes. 9. WAJP that reads a file and displays the file on the screen, with a line number before each line . 10. WAJP that displays the number of characters, lines and words in a text. 11 . WAJP that: (a) Implements a Stack ADT Copyright cserockz08, 2009 www.cserockz.com Page 8

Object Oriented Programming (b) (c) Converts Infix expression to Postfix expression Evaluates a Postfix expr ession LAB MANUAL 12. Write an Applet that displays a simple message. 13. Write an Applet that com putes the payment of a loan based on the amount of the loan, the interest rate a nd the number of months. It takes one parameter from the browser: Monthly rate; if true, the interest rate is per month, otherwise the interest rate is annual. 14. WAJP that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the + - x / % operations. Add a text field to display th e result. 15. WAJP for handling mouse events. 16. WAJP for creating multiple thr eads. 17. WAJP that correctly implements Producer-Consumer problem using the con cept of Inter Thread Communication. 18. WAJP that lets users create Pie charts. Design your own user interface (with Swings & AWT). 19. WAJP that allows user to draw lines, rectangles and ovals. 20. WAJP that implements a simple client/serv er 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 c lient 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 t he circle. 21. WAJP that illustrates how runtime polymorphism is achieved. 22. W AJP to generate a set of random numbers. Find its sum and average. The program s hould also display * based on the random numbers generated. 23. WAJP to create an abstract class named Shape, that contains an empty method named numberOfSides(). Provide three classes named Trapezoid, Triangle and Copyright cserockz08, 2009 www.cserockz.com Page 9

Object Oriented Programming LAB MANUAL Hexagon, such that each one of the classes contains only the method numberOfSide s(), that contains the number of sides in the given geometrical figure. 24. WAJP to implement a Queue, using user defined Exception Handling (also make use of t hrow, throws). 25. WAJP that creates 3 threads by extending Thread class. First thread displays Good Morning every 1 sec, the second thread displays Hello every 2 s econds and the third displays Welcome every 3 seconds. (Repeat the same by impleme nting Runnable) 26. WAJP that will compute the following series: (a) 1 + 1/2 + 1 /3+ .+ 1/n (b) 1 + 1/2 + 1/ 22 + 1/ 23 + + 1/ 2n (c) ex = 1 + x/1! + x2/2! + x3/3! + 27. WAJP to do the following: (a) To output the question Who is the inventor of J ava? (b) To accept an answer (c) To printout GOOD and then stop if the answer is co rrect (d) To output the message TRY AGAIN, if the answer is wrong (e) To display t he correct answer, when the answer is wrong even at the third attempt 28. WAJP t o transpose a matrix using arraycopy command. 29. Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the base class provide methods that ar e common to all Rodents and override these in the derived classes to perform dif ferent behaviors, depending on the specific type of Rodent. Create an array of R odent, fill it with different specific types of Rodents and call your base class methods. 30. WAJP to print a chessboard pattern. Copyright cserockz08, 2009 www.cserockz.com Page 10

Object Oriented Programming Program Statement : LAB MANUAL Write a Java program that prints all real solutions to the quadratic equation ax 2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b 2-4ac is negative, display a message stating that there are no real solutions. P rogram : import java.io.*; class Quadratic { public static void main(String args [])throws IOException { double x1,x2,disc,a,b,c; InputStreamReader obj=new Input StreamReader(System.in); BufferedReader br=new BufferedReader(obj); System.out.p rintln("enter a,b,c values"); a=Double.parseDouble(br.readLine()); b=Double.pars eDouble(br.readLine()); c=Double.parseDouble(br.readLine()); disc=(b*b)-(4*a*c); if(disc==0) { System.out.println("roots are real and equal "); x1=x2=-b/(2*a); System.out.println("roots are "+x1+","+x2); } else if(disc>0) { System.out.print ln("roots are real and unequal"); Copyright cserockz08, 2009 www.cserockz.com Page 11

Object Oriented Programming x1=(-b+Math.sqrt(disc))/(2*a); x2=(-b+Math.sqrt(disc))/(2*a); System.out.println ("roots are "+x1+","+x2); } else { System.out.println("roots are imaginary"); } } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 12

Object Oriented Programming Program Statement : LAB MANUAL The Fibonacci sequence is defined by the following rule. The first 2 values in t he sequence are 1, 1. Every subsequent value is the sum of the 2 values precedin g it. Write a Java program that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence. Program : /*Non Recursive Solu tion*/ import java.util.Scanner; class Fib { public static void main(String args [ ]) { Scanner input=new Scanner(System.in); int i,a=1,b=1,c=0,t; System.out.pri ntln("Enter value of t:"); t=input.nextInt(); System.out.print(a); System.out.pr int(" "+b); for(i=0;i<t-2;i++) { c=a+b; a=b; b=c; System.out.print(" "+c); } Sys tem.out.println(); System.out.print(t+"th value of the series is: "+c); } } Copyright cserockz08, 2009 www.cserockz.com Page 13

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 14

Object Oriented Programming /* Recursive Solution*/ import java.io.*; import java.lang.*; class Demo { int f ib(int n) { if(n==1) return (1); else if(n==2) return (1); else return (fib(n-1) +fib(n-2)); } } LAB MANUAL class RecFibDemo { public static void main(String args[])throws IOException { In putStreamReader obj=new InputStreamReader(System.in); BufferedReader br=new Buff eredReader(obj); System.out.println("enter last number"); int n=Integer.parseInt (br.readLine()); Demo ob=new Demo(); System.out.println("fibonacci series is as follows"); int res=0; for(int i=1;i<=n;i++) { res=ob.fib(i); System.out.println( " "+res); } System.out.println(); System.out.println(n+"th value of the series i s "+res); } } Copyright cserockz08, 2009 www.cserockz.com Page 15

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 16

Object Oriented Programming Program Statement : LAB MANUAL WAJP that prompts the user for an integer and then prints out all the prime numb ers up to that Integer. Program : Import java.util.* class Test { void check(int num) { System.out.println ("Prime numbers up to "+num+" are:"); for (int i=1;i< =num;i++) for (int j=2;j<i;j++) { if(i%j==0) break; else if((i%j!=0)&&(j==i-1)) System.out.print( +i); } } } //end of class Test class Prime { public static void main(String args[ ]) { Test obj1=new Test(); Scanner input=new Scanner(System.in ); System.out.println("Enter the value of n:"); int n=input.nextInt(); obj1.chec k(n); } } Copyright cserockz08, 2009 www.cserockz.com Page 17

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 18

Object Oriented Programming Program Statement : LAB MANUAL WAJP that checks whether a given string is a palindrome or not. Ex: MADAM is a p alindrome. Program : import java.io.*; class Palind { public static void main(St ring args[ ])throws IOException { BufferedReader br=new BufferedReader(new Input StreamReader(System.in)); System.out.println("Enter the string to check for pali ndrome:"); String s1=br.readLine(); StringBuffer sb=new StringBuffer(); sb.appen d(s1); sb.reverse(); String s2=sb.toString(); if(s1.equals(s2)) System.out.print ln("palindrome"); else System.out.println("not palindrome"); } } Copyright cserockz08, 2009 www.cserockz.com Page 19

Object Oriented Programming Input & LAB MANUAL Output Copyright cserockz08, 2009 www.cserockz.com Page 20

Object Oriented Programming Program Statement : WAJP for sorting a given list of names in ascending order. P rogram : import java.io.*; class Test { int len,i,j; String arr[ ]; Test(int n) { len=n; arr=new String[n]; } LAB MANUAL String[ ] getArray()throws IOException { BufferedReader br=new BufferedReader (n ew InputStreamReader(System.in)); System.out.println ("Enter the strings U want to sort----"); for (int i=0;i<len;i++) arr[i]=br.readLine(); return arr; } Strin g[ ] check()throws ArrayIndexOutOfBoundsException { for (i=0;i<len-1;i++) { for( int j=i+1;j<len;j++) { if ((arr[i].compareTo(arr[j]))>0) { String s1=arr[i]; arr [i]=arr[j]; arr[j]=s1; } } } return arr; } void display()throws ArrayIndexOutOfB oundsException { Copyright cserockz08, 2009 www.cserockz.com Page 21

Object Oriented Programming System.out.println ("Sorted list is---"); for (i=0;i<len;i++) System.out.println (arr[i]); } //end of the Test class LAB MANUAL } class Ascend { public static void main(String args[ ])throws IOException { Test obj1=new Test(4); obj1.getArray(); obj1.check(); obj1.display(); } } Input & Out put : Copyright cserockz08, 2009 www.cserockz.com Page 22

Object Oriented Programming Program Statement : WAJP to multiply two given matrices. Program : import java.u til.*; class Test { int r1,c1,r2,c2; Test(int r1,int c1,int r2,int c2) { this.r1 =r1; this.c1=c1; this.r2=r2; this.c2=c2; } LAB MANUAL int[ ][ ] getArray(int r,int c) { int arr[][]=new int[r][c]; System.out.println( "Enter the elements for "+r+"X"+c+" Matrix:"); Scanner input=new Scanner(System. in); for(int i=0;i<r;i++) for(int j=0;j<c;j++) arr[i][j]=input.nextInt(); return arr; } int[ ][ ] findMul(int a[ ][ ],int b[ ][ ]) { int c[][]=new int[r1][c2]; for (int i=0;i<r1;i++) for (int j=0;j<c2;j++) { c[i][j]=0; for (int k=0;k<r2;k++ ) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } return c; } void putArray(int res[ ][ ]) { Copyright cserockz08, 2009 www.cserockz.com Page 23

Object Oriented Programming LAB MANUAL System.out.println ("The resultant "+r1+"X"+c2+" Matrix is:"); for (int i=0;i<r1 ;i++) { for (int j=0;j<c2;j++) System.out.print(res[i][j]+" "); System.out.print ln(); } } } //end of Test class class MatrixMul { public static void main(String args[ ])throws IOException { Test obj1=new Test(2,3,3,2); Test obj2=new Test(2, 3,3,2); int x[ ][ ],y[ ][ ],z[ ][ ]; System.out.println("MATRIX-1:"); x=obj1.get Array(2,3); //to get the matrix from user System.out.println("MATRIX-2:"); y=obj 2.getArray(3,2); z=obj1.findMul(x,y); //to perform the multiplication obj1.putAr ray(z); // to display the resultant matrix } } Copyright cserockz08, 2009 www.cserockz.com Page 24

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 25

Object Oriented Programming Program Statement : LAB MANUAL WAJP that reads a line of integers and then displays each integer and the sum of all integers. (use StringTokenizer class) Program : // Using StringTokenizer cl ass import java.lang.*; import java.util.*; class tokendemo { public static void main(String args[ ]) { String s="10,20,30,40,50"; int sum=0; StringTokenizer a= new StringTokenizer(s,",",false); System.out.println("integers are "); while(a.h asMoreTokens()) { int b=Integer.parseInt(a.nextToken()); sum=sum+b; System.out.p rintln(" "+b); } System.out.println("sum of integers is "+sum); } } // Alternate solution using command line arguments class Arguments { public static void main (String args[ ]) { int sum=0; int n=args.length; System.out.println("length is " +n); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=Integer.parseInt(args[i]) ; System.out.println("The enterd values are:"); Copyright cserockz08, 2009 www.cserockz.com Page 26

Object Oriented Programming for(int i=0;i<n;i++) System.out.println(arr[i]); System.out.println("sum of ente rd integers is:"); for(int i=0;i<n;i++) sum=sum+arr[i]; System.out.println(sum); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 27

Object Oriented Programming Program Statement : LAB MANUAL WAJP that reads on file name from the user, then displays information about whet her the file exists, whether the file is readable, wheteher the file is writable , the type of file and the length of the file in bytes. Program : import java.io .File; class FileDemo { static void p(String s) { System.out.println(s); } publi c static void main(String args[ ]) { File f1 = new File(args[0]); p("File Name: " + f1.getName()); p("Path: " + f1.getPath()); p("Abs Path: " + f1.getAbsolutePa th()); p("Parent: " + f1.getParent()); p(f1.exists() ? "exists" : "does not exis t"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "i s readable" : "is not readable"); p("is " + (f1.isDirectory() ? "" : "not" + " a directory")); p(f1.isFile() ? "is normal file" : "might be a named pipe"); p(f1 .isAbsolute() ? "is absolute" : "is not absolute"); p("File last modified: " + f 1.lastModified()); p("File size: " + f1.length() + " Bytes"); } } Copyright cserockz08, 2009 www.cserockz.com Page 28

Object Oriented Programming Input & Output : LAB MANUAL : Copyright cserockz08, 2009 www.cserockz.com Page 29

Object Oriented Programming Program Statement : LAB MANUAL WAJP that reads a file and displays the file on the screen, with a line number b efore each line. Program : import java.io.*; class LineNum{ public static void m ain(String args[]){ String thisline; for(int i=0;i<args.length;i++) { try{ LineN umberReader br=new LineNumberReader(new FileReader(args[i])); while((thisline=br .readLine())!=null) { System.out.println(br.getLineNumber()+"."+thisline); } }ca tch(IOException e){ System.out.println("error:"+e); } } } } Copyright cserockz08, 2009 www.cserockz.com Page 30

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 31

Object Oriented Programming LAB MANUAL Program Statement : WAJP that displays the number of characters, lines and words in a text file. Program : import java.io.*; public class FileStat { public stat ic void main(String args[ ])throws IOException { long nl=0,nw=0,nc=0; String lin e; BufferedReader br=new BufferedReader(new FileReader(args[0])); while ((line=b r.readLine())!=null) { nl++; nc=nc+line.length(); int i=0; boolean pspace=true; while (i<line.length()) { char c=line.charAt(i++); boolean cspace=Character.isWh itespace(c); if (pspace&&!cspace) nw++; pspace=cspace; } } System.out.println("N umber of Characters"+nc); System.out.println("Number of Characters"+nw); System. out.println("Number of Characters"+nl); }} // Alternate solution using StringTok enizer import java.io.*; import java.util.*; public class FileStat { public stat ic void main(String args[ ])throws IOException { long nl=0,nw=0,nc=0; String lin e; BufferedReader br=new BufferedReader(new FileReader(args[0])); while ((line=b r.readLine())!=null) { nl++; Copyright cserockz08, 2009 www.cserockz.com Page 32

Object Oriented Programming nc=nc+line.length(); StringTokenizer st = new StringTokenizer(line); nw += st.co untTokens(); } System.out.println("Number of Characters"+nc); System.out.println ("Number of Characters"+nw); System.out.println("Number of Characters"+nl); }} I nput & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 33

Object Oriented Programming Program Statement : WAJP that: (a) Implements a Stack ADT (b) Converts Infix exp ression to Postfix expression (c) Evaluates a Postfix expression LAB MANUAL Program : import java.io.*; interface stack { void push(int item); int pop(); } class Stackimpl { private int stck[]; private int top; Stackimpl(int size) { stc k=new int[size]; top=-1; } void push(int item) { if(top==stck.length-1) System.o ut.println("stack is full insertion is not possible"); else stck[++top]=item; } int pop() Copyright cserockz08, 2009 www.cserockz.com Page 34

Object Oriented Programming { LAB MANUAL if(top==-1) { System.out.println("stack is empty deletion is not possible"); ret urn 0; } else return stck[top--]; } } class Stackdemo { public static void main(String args[])throws IOException { int a[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Sy stem.out.println("enter the size of the array"); int n=Integer.parseInt(br.readL ine()); Stackimpl obj1=new Stackimpl(n); a=new int[n]; System.out.println("enter numbers into the stack"); for(int i=0;i<n;i++) a[i]=Integer.parseInt(br.readLin e()); System.out.println("numbers are inserted"); for(int i=0;i<n;i++) obj1.push (a[i]); System.out.println("The following numbers are poped out."); Copyright cserockz08, 2009 www.cserockz.com Page 35

Object Oriented Programming for(int i=0;i<n;i++) System.out.println(" "+obj1.pop()); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 36

Object Oriented Programming Program Statement : Write an Applet that displays a simple message. Program : im port java.awt.*; import java.applet.*; /* <applet </applet> */ public class Hell oJava extends Applet { public void paint(Graphics g) { g.drawString(Hello Java, 10 , 100); } } Input & Output : code = HelloJava LAB MANUAL width = 200 height = 60 > Copyright cserockz08, 2009 www.cserockz.com Page 37

Object Oriented Programming LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 38

Object Oriented Programming Program Statement : LAB MANUAL Write an Applet that computes the payment of a loan based on the amount of the l oan, the interest rate and the number of months. It takes one parameter from the browser: Monthly rate; if true, the interest rate is per month, otherwise the i nterest rate is annual. Program : import java.awt.*; import java.awt.event.*; im port java.applet.*; /* <applet code = "LoanPayment" width=500 height=300 > <para m name = monthlyRate value=true> </applet> */ public class LoanPayment extends A pplet implements ActionListener { TextField amt_t, rate_t, period_t; Button comp ute = new Button("Compute"); boolean monthlyRate; public void init() { Label amt _l = new Label("Amount: "); Label rate_l = new Label("Rate: ", Label.CENTER); La bel period_l = new Label("Period: ", Label.RIGHT); amt_t = new TextField(10); rate_t = new TextField(10); period_t = new TextField( 10); add(amt_l); add(amt_t); add(rate_l); add(rate_t); add(period_l); add(period _t); Copyright cserockz08, 2009 www.cserockz.com Page 39

Object Oriented Programming add(compute); amt_t.setText("0"); rate_t.setText("0"); period_t.setText("0"); LAB MANUAL monthlyRate = Boolean.valueOf(getParameter("monthlyRate")); amt_t.addActionListe ner(this); rate_t.addActionListener(this); period_t.addActionListener(this); com pute.addActionListener(this); } public void paint(Graphics g) { double amt=0, ra te=0, period=0, payment=0; String amt_s, rate_s, period_s, payment_s; g.drawStri ng("Input the Loan Amt, Rate and Period in each box and press Compute", 50,100); try { amt_s = amt_t.getText(); amt = Double.parseDouble(amt_s); rate_s = rate_t .getText(); rate = Double.parseDouble(rate_s); period_s = period_t.getText(); pe riod = Double.parseDouble(period_s); } catch (Exception e) { } if (monthlyRate) payment = amt * period * rate * 12 / 100; else payment = amt * period * rate / 1 00; payment_s = String.valueOf(payment); g.drawString("The LOAN PAYMENT amount i s: ", 50, 150); g.drawString(payment_s, 250, 150); Copyright cserockz08, 2009 www.cserockz.com Page 40

Object Oriented Programming } public void actionPerformed(ActionEvent ae) { repaint(); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 41

Object Oriented Programming Program Statement : LAB MANUAL WAJP that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the + - x / % operations. Add atext field to display the res ult. Program : import javax.swing.*; import java.awt.*; import java.awt.event.*; //<applet code=Calculator height=300 width=200></applet> public class Calculato r extends JApplet { public void init() { CalculatorPanel calc=new CalculatorPane l(); getContentPane().add(calc); } } class CalculatorPanel extends JPanel implem ents ActionListener { JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,d ot,equal; static JTextField result=new JTextField("0",45); static String lastCom mand=null; JOptionPane p=new JOptionPane(); double preRes=0,secVal=0,res; privat e static void assign(String no) { if((result.getText()).equals("0")) result.setT ext(no); else if(lastCommand=="=") { result.setText(no); lastCommand=null; } els e result.setText(result.getText()+no); } public CalculatorPanel() { Copyright cserockz08, 2009 www.cserockz.com Page 42

Object Oriented Programming setLayout(new BorderLayout()); result.setEditable(false); result.setSize(300,200 ); add(result,BorderLayout.NORTH); JPanel panel=new JPanel(); panel.setLayout(ne w GridLayout(4,4)); n7=new JButton("7"); panel.add(n7); n7.addActionListener(thi s); n8=new JButton("8"); panel.add(n8); n8.addActionListener(this); n9=new JButt on("9"); panel.add(n9); n9.addActionListener(this); div=new JButton("/"); panel. add(div); div.addActionListener(this); n4=new JButton("4"); panel.add(n4); n4.ad dActionListener(this); n5=new JButton("5"); panel.add(n5); n5.addActionListener( this); n6=new JButton("6"); panel.add(n6); n6.addActionListener(this); mul=new J Button("*"); panel.add(mul); mul.addActionListener(this); n1=new JButton("1"); p anel.add(n1); n1.addActionListener(this); n2=new JButton("2"); panel.add(n2); n2 .addActionListener(this); Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 43

Object Oriented Programming n3=new JButton("3"); panel.add(n3); n3.addActionListener(this); minus=new JButto n("-"); panel.add(minus); minus.addActionListener(this); dot=new JButton("."); p anel.add(dot); dot.addActionListener(this); n0=new JButton("0"); panel.add(n0); n0.addActionListener(this); equal=new JButton("="); panel.add(equal); equal.addA ctionListener(this); plus=new JButton("+"); panel.add(plus); plus.addActionListe ner(this); add(panel,BorderLayout.CENTER); } public void actionPerformed(ActionE vent ae) { if(ae.getSource()==n1) assign("1"); else if(ae.getSource()==n2) assig n("2"); else if(ae.getSource()==n3) assign("3"); else if(ae.getSource()==n4) ass ign("4"); else if(ae.getSource()==n5) assign("5"); else if(ae.getSource()==n6) a ssign("6"); else if(ae.getSource()==n7) assign("7"); else if(ae.getSource()==n8) assign("8"); else if(ae.getSource()==n9) assign("9"); else if(ae.getSource()==n 0) assign("0"); else if(ae.getSource()==dot) { if(((result.getText()).indexOf(". "))==-1) result.setText(result.getText()+"."); } else if(ae.getSource()==minus) Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 44

Object Oriented Programming { preRes=Double.parseDouble(result.getText()); lastCommand="-"; result.setText(" 0"); } else if(ae.getSource()==div) { preRes=Double.parseDouble(result.getText() ); lastCommand="/"; result.setText("0"); } else if(ae.getSource()==equal) { secV al=Double.parseDouble(result.getText()); if(lastCommand.equals("/")) res=preRes/ secVal; else if(lastCommand.equals("*")) res=preRes*secVal; else if(lastCommand. equals("-")) res=preRes-secVal; else if(lastCommand.equals("+")) res=preRes+secV al; result.setText(" "+res); lastCommand="="; } else if(ae.getSource()==mul) { p reRes=Double.parseDouble(result.getText()); lastCommand="*"; result.setText("0") ; } else if(ae.getSource()==plus) { preRes=Double.parseDouble(result.getText()); lastCommand="+"; result.setText("0"); } } } Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 45

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 46

Object Oriented Programming Program Statement : WAJP for handling mouse events. Program : import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MouseEvents" wi dth=300 height=100> </applet> */ public class MouseEvents extends Applet impleme nts MouseListener, MouseMotionListener { String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); addMo useMotionListener(this); } // Handle mouse clicked. public void mouseClicked(Mou seEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked. "; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 47

Object Oriented Programming msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseEx ited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseE vent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Do wn"; repaint(); } // Handle button released. public void mouseReleased(MouseEven t me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } LAB MANUAL // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coord inates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging m ouse at " + mouseX + ", " + mouseY); repaint(); Copyright cserockz08, 2009 www.cserockz.com Page 48

Object Oriented Programming } LAB MANUAL // Handle mouse moved. public void mouseMoved(MouseEvent me) { // show status sh owStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawSt ring(msg, mouseX, mouseY); } } Input & Output : Copyright cserockz08, 2009 www.cserockz.com Page 49

Object Oriented Programming LAB MANUAL Program Statement : WAJP for creating multiple threads. Program : class NewThrea d implements Runnable { String name; // name of thread Thread t; NewThread(Strin g threadname) { name = threadname; t = new Thread(this, name); System.out.printl n("New thread: " + t); t.start(); // Start the thread } // This is the entry poi nt for thread. public void run() { try { Copyright cserockz08, 2009 www.cserockz.com Page 50

Object Oriented Programming for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1 000); } } catch (InterruptedException e) { System.out.println(name + "Interrupte d"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { publi c static void main(String args[]) { new NewThread("One"); // start threads new N ewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 51

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 52

Object Oriented Programming Program Statement : LAB MANUAL WAJP that correctly implements Producer-Consumer problem using the concept of In ter Thread Communication. Program : class Q { int n; boolean valueSet = false; s ynchronized int get() { if (!valueSet) try { wait(); } catch (InterruptedExcepti on e) { } System.out.println(Got: + n); valueSet = false; notify(); return n; } s ynchronized void put(int n) { if (valueSet) try { wait(); } catch (InterruptedEx ception e) { } this.n = n; valueSet = true; System.out.println(Put: + n); notify( ); } } class Producer implements Runnable { Q q; Copyright cserockz08, 2009 www.cserockz.com Page 53

Object Oriented Programming Producer(Q q) { this.q = q; new Thread(this, Producer).start(); } public void run( ) { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnabl e { Q q; Consumer(Q q) { this.q = q; new Thread(this, Consumer).start(); } public void run() { while(true) { q.get(); } } } class PC { public static void main (St ring args[ ]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.prin tln(Press Ctrl-C to stop); } } LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 54

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 55

Object Oriented Programming Program Statement : LAB MANUAL WAJP that lets users create Pie charts. Design your own user interface (with Swi ngs & AWT). Program : import java.awt.*; import java.applet.*; /*<applet code=Pi Chart.class width=600 height=600></applet>*/ public class PiChart extends Applet { public void paint(Graphics g) { setBackground(Color.green); g.drawString("PI CHART",200,40); g.setColor(Color.blue); g.fillOval(50,50,150,150); g.setColor(Co lor.white); g.drawString("40%",130,160); g.setColor(Color.magenta); g.fillArc(50 ,50,150,150,0,90); g.setColor(Color.white); g.drawString("25%",140,100); g.setCo lor(Color.yellow); g.fillArc(50,50,150,150,90,120); g.setColor(Color.black); g.d rawString("35%",90,100); g.setColor(Color.yellow); g.fillOval(250,50,150,150); g .setColor(Color.black); g.drawString("15%",350,150); g.setColor(Color.magenta); g.fillArc(250,50,150,150,0,30); g.setColor(Color.black); g.drawString("5%",360,1 20); g.setColor(Color.blue); Copyright cserockz08, 2009 www.cserockz.com Page 56

Object Oriented Programming g.fillArc(250,50,150,150,30,120); g.setColor(Color.white); g.drawString("30%",33 0,100); g.setColor(Color.black); g.fillArc(250,50,150,150,120,180); g.setColor(C olor.white); g.drawString("50%",280,160); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 57

Object Oriented Programming LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 58

Object Oriented Programming Program Statement : WAJP that allows user to draw lines, rectangles and ovals. P rogram : import javax.swing.*; import java.awt.Graphics; LAB MANUAL public class choice extends JApplet { int i,ch; public void init() { String inpu t; input=JOptionPane.showInputDialog("enter your rectangles,3-ovals)"); ch=Integ er.parseInt(input); } public void paint(Graphics g) { switch(ch) { case 1:{ for( i=1;i<=10;i++) { g.drawLine(10,10,250,10*i); } break; } choice(1-lines,2case 2:{ for(i=1;i<=10;i++) { g.drawRect(10*i,10*i,50+10*i,50+10*i); } break; } case 3:{ for(i=1;i<=10;i++) Copyright cserockz08, 2009 www.cserockz.com Page 59

Object Oriented Programming LAB MANUAL { g.drawOval(10*i,10*i,50+10*i,50+10*i); } break; }}}} Input & Output : Copyright cserockz08, 2009 www.cserockz.com Page 60

Object Oriented Programming LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 61

Object Oriented Programming Program Statement : LAB MANUAL WAJP that implements a simple client/server application. The client sends data t o a server. The server receives the data, uses it to produce a result and then s ends the result back to the client. The client displays the result on the consol e. For ex: The data sent from the client is the radius of a circle and the resul t produced by the server is the area of the circle. Program : // Server Program import java.io.*; import java.net.*; import java.util.*; public class Server { p ublic void static main (String args [ ] ) { try { // create a server socket Serv erSocket s = new ServerSocket(8000); // start listening for connections on srver socket Socket connectToClient = s.accept(); // create a buffered reader stream to get data from client BufferedReader isFromClient = new BufferedReader(new Inp utStreamReader (connectToClient.getInputStream())); // create a buffer reader to send result to client PrintWriter osToClient = new PrintWriter(connectToClient. getOutputStream(), true); // continuously read from client, process, send back w hile (true) { // read a line and create string tokenizer StringTokenizer st = ne w StringTokenizer(isFromClient.readLine()); //convert string to double Copyright cserockz08, 2009 www.cserockz.com Page 62

Object Oriented Programming double radius = new Double(st.nextToken()).doubleValue(); LAB MANUAL // display radius on console System.out.println(Radius received from client: + ra dius); // comput area double area = radius * radius *Math.PI; // send result to client osToClient.println(area); // print result on console System.out.println(Ar ea found: +area); } } catch (IOException e) { System.err.println(e); } } } // Client Program import java.io.*; import java.net.*; import java.util.*; publi c class Client { public void static main (String args [ ] ) { try { // create a socket to connect to server Socket connectToServer = new Socket(local host, 8000); // create a buffered input stream to get result from server BufferedReader isFr omServer = new BufferedReader(new InputStreamReader (connectToServer.getInputStr eam())); Copyright cserockz08, 2009 www.cserockz.com Page 63

Object Oriented Programming LAB MANUAL // create a buffer output stream to send data to server PrintWriter osToServer = new PrintWriter(connectToClient.getOutputStream(), true); // continuously send radius and get area while (true) { Scanner input=new Scanner(System.in); System. out.print(Please enter a radius: ); double radius =input.nextDouble(); // display radius on console osToServer.println(radius); // get area from server StringToke nizer st = new StringTokenizer(isFromServer.readLine()); // convert string to do uble Double area = new Double(st.nextToken()).doubleValue(); // print result on console System.out.println(Area received from the server is: +area); } } catch (I OException e) { System.err.println(e); } } } Copyright cserockz08, 2009 www.cserockz.com Page 64

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 65

Object Oriented Programming Program Statement : LAB MANUAL WAJP that illustrates how runtime polymorphism is achieved. Program : class Figu re { 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 A rea for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Tr iangle(double a, double b) { super(a, b); } // override area for right triangle Copyright cserockz08, 2009 www.cserockz.com Page 66

Object Oriented Programming double area() { System.out.println("Inside Area for Triangle."); return dim1 * d im2 / 2; } } class FindAreas { public static void main(String args[]) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle(9, 5); Triangle t = new Trian gle(10, 8); Figure figref; figref = r; System.out.println("Area is " + figref.ar ea()); figref = t; System.out.println("Area is " + figref.area()); figref = f; S ystem.out.println("Area is " + figref.area()); } } LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 67

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 68

Object Oriented Programming LAB MANUAL Program Statement : WAJP to generate a set of random numbers. Find its sum and a verage. The program should also display * based on the random numbers generated. P rogram : import java.util.*; class RandNum { public static void main(String ax[ ]) { int a[ ]=new int[5]; int sum=0; Random r=new Random(); for (int i=0;i<5;i++ ) { a[i]=r.nextInt(10); System.out.print(a[i]); for(int y=0;y<a[i];y++) System.o ut.print(" *"); System.out.println(""); } for(int i=0;i<5;i++) sum=sum+a[i]; Sys tem.out.println("Sum="+sum); System.out.println("Avg="+(double)sum/a.length); } } Copyright cserockz08, 2009 www.cserockz.com Page 69

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 70

Object Oriented Programming Program Statement : LAB MANUAL WAJP to create an abstract class named Shape, that contains an empty method name d numberOfSides(). Provide three classes named Trapezoid, Triangle and Hexagon, such that each one of the classes contains only the method numberOfSides(), that contains the number of sides in the given geometrical figure. Program : abstrac t class Shape { abstract void numberOfSides(); } class Trapezoid extends Shape{ void numberOfSides() { System.out.println(" Trapezoidal has four sides"); } } cl ass Triangle extends Shape { void numberOfSides() { System.out.println("Triangle has three sides"); } } class Hexagon extends Shape { void numberOfSides() { Sys tem.out.println("Hexagon has six sides"); } } class ShapeDemo { public static vo id main(String args[ ]) { Trapezoid t=new Trapezoid(); Triangle r=new Triangle() ; Hexagon h=new Hexagon(); Shape s; s=t; s.numberOfSides(); Copyright cserockz08, 2009 www.cserockz.com Page 71

Object Oriented Programming s=r; s.numberOfSides(); s=h; s.numberOfSides(); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 72

Object Oriented Programming Program Statement : LAB MANUAL WAJP to implement a Queue, using user defined Exception Handling (also make use of throw, throws). Program : import java.util.Scanner; class ExcQueue extends Ex ception { ExcQueue(String s) { super(s); } } class Queue { int front,rear; int q [ ]=new int[10]; Queue() { rear=-1; front=-1; } void enqueue(int n) throws ExcQu eue { if (rear==9) throw new ExcQueue("Queue is full"); rear++; q[rear]=n; if (f ront==-1) front=0; } int dequeue() throws ExcQueue { if (front==-1) throw new Ex cQueue("Queue is empty"); int temp=q[front]; if (front==rear) front=rear=-1; Copyright cserockz08, 2009 www.cserockz.com Page 73

Object Oriented Programming else front++; return(temp); } } class UseQueue { public static void main(String args[ ]) { Queue a=new Queue(); try { a.enqueue(5); a.enqueue(20); } catch (ExcQ ueue e) { System.out.println(e.getMessage()); } try { System.out.println(a.deque ue()); System.out.println(a.dequeue()); System.out.println(a.dequeue()); } catch (ExcQueue e) { System.out.println(e.getMessage()); } } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 74

Object Oriented Programming Program Statement : LAB MANUAL WAJP that creates 3 threads by extending Thread class. First thread displays Good Morning every 1 sec, the second thread displays Hello every 2 seconds and the thir d displays Welcome every 3 seconds. (Repeat the same by implementing Runnable) Pro gram : // Using Thread class class One extends Thread { public void run() { for ( ; ; ) { try{ sleep(1000); }catch(InterruptedException e){} System.out.println( "Good Morning"); } } } class Two extends Thread { public void run() { for ( ; ; ) { try{ sleep(2000); }catch(InterruptedException e){} System.out.println("Hello "); } } } class Three extends Thread { public void run() { for ( ; ; ) { try{ sl eep(3000); }catch(InterruptedException e){} System.out.println("Welcome"); Copyright cserockz08, 2009 www.cserockz.com Page 75

Object Oriented Programming } } } class MyThread { public static void main(String args[ ]) { Thread t = new Thread(); One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); Thread t1=new Thread(obj1); Thread t2=new Thread(obj2); Thread t3=new Thread(obj3); t1 .start(); try{ t.sleep(1000); }catch(InterruptedException e){} t2.start(); try{ t.sleep(2000); }catch(InterruptedException e){} t3.start(); try{ t.sleep(3000); }catch(InterruptedException e){} } } // Using Runnable interface class One imple ments Runnable { One( ) { new Thread(this, "One").start(); try{ Thread.sleep(100 0); }catch(InterruptedException e){} } Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 76

Object Oriented Programming public void run() { for ( ; ; ) { try{ Thread.sleep(1000); }catch(InterruptedExc eption e){} System.out.println("Good Morning"); } } } class Two implements Runna ble { Two( ) { new Thread(this, "Two").start(); try{ Thread.sleep(2000); }catch( InterruptedException e){} } public void run() { for ( ; ; ) { try{ Thread.sleep( 2000); }catch(InterruptedException e){} System.out.println("Hello"); } } } class Three implements Runnable { Three( ) { new Thread(this, "Three").start(); try{ Thread.sleep(3000); }catch(InterruptedException e){} } LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 77

Object Oriented Programming public void run() { for ( ; ; ) { try{ Thread.sleep(3000); }catch(InterruptedExc eption e){} System.out.println("Welcome"); } } } class MyThread { public static void main(String args[ ]) { One obj1=new One(); Two obj2=new Two(); Three obj3=n ew Three(); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 78

Object Oriented Programming Program Statement : WAJP that will compute the following series: (a) 1 + 1/2 + 1 /3+ .+ 1/n (b) 1 + 1/2 + 1/ 22 + 1/ 23 + + 1/ 2n (c) ex = 1 + x/1! + x2/2! + x3/3! + Program : // (a) 1 + 1/2 + 1/3+ .+ 1/n import java.util.Scanner; class Series1 { public static void main(String arg[ ]) { int n; double sum=0,i; Scanner input= new Scanner(System.in); System.out.println("enter value of n:"); n=input.nextIn t(); for(i=1;i<=n;i++) sum=sum+(double)(1/i); System.out.println("Result:"+sum); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 79

Object Oriented Programming // (b) 1 + 1/2 + 1/ 22 + 1/ 23 + + 1/ 2n import java.util.Scanner; class Series2 { public static void main(String arg[ ]) { int n; double sum=0,i; Scanner input = new Scanner(System.in); System.out.println("enter value of n:"); n=input.nextI nt(); for(i=1;i<=n;i++) sum=sum+(double)(1/Math.pow(2,i-1)); System.out.println( "Result:"+sum); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 80

Object Oriented Programming // (c) ex = 1 + x/1! + x2/2! + x3/3! + import java.util.*; class Series3{ public static void main(String arg[ ]) { int n,x; double sum=0,i,d=1; Scanner input= n ew Scanner(System.in); System.out.println("enter value of n:"); n=input.nextInt( ); System.out.println("enter value of x:"); x=input.nextInt(); for (i=1;i<=n;i++ ) { sum=sum+(double)((Math.pow(x,i-1)/d)); d=d*i; } System.out.println("Result : "+sum); } } Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 81

Object Oriented Programming Program Statement : LAB MANUAL WAJP to do the following: (a) To output the question Who is the inventor of Java? (b) To accept an answer (c) To printout GOOD and then stop if the answer is correc t (d) To output the message TRY AGAIN, if the answer is wrong (e) To display the c orrect answer, when the answer is wrong even at the third attempt Program : impo rt java.io.*; class Ask { public static void main(String a[ ])throws Exception { String str1,str2; int count=0; str1="James Gosling"; BufferedReader br=new Buff eredReader(new InputStreamReader(System.in)); System.out.println("Who is the inv entor of Java ?"); while(count!=3) { str2=br.readLine(); if(str1.equalsIgnoreCas e(str2)) { System.out.println("!!! GOOD !!!"); break; } else { if(count<2) Syste m.out.println("TRY AGAIN !"); count++; } } if(count==3) System.out.println("Corr ect Answer is : "+str1); } } Copyright cserockz08, 2009 www.cserockz.com Page 82

Object Oriented Programming Input & Output : LAB MANUAL : Copyright cserockz08, 2009 www.cserockz.com Page 83

Object Oriented Programming Program Statement : WAJP to transpose a matrix using arraycopy command. Program : class TransMatrix { public static void main(string args[ ]) { int i,j,k=0; int r ows,cols,r,c; int a[ ][ ]={{1,2,3,4},{5,6,7,8}}; rows=a.length; cols=a[0].length ; int b[ ][ ]=new int[rows*cols]; int s[ ]=new int[rows*cols]; int d[ ]=new int[ rows*cols]; for (i=0;i<rows;i++) for (j=0;j<cols;j++,k++) s[k]=a[i][j]; i=j=k=r= c=0; while(r<rows) { while(c<cols) { System.arraycopy(s,i,d,i,l); b[j++][k]=d[i+ +]; c++; } j=c=0; k++; t++; } System.out.println("a matrix:"); for (i=0;i<rows;i ++) { for(j=0;j<cols;j++) System.out.print(" "+a[i][j]); System.out.println(); } Copyright LAB MANUAL cserockz08, 2009 www.cserockz.com Page 84

Object Oriented Programming System.out.println("\nb matrix:"); for(i=0;i<cols;i++) { for(j=0;j<rows;j++) Sys tem.out.print(" "+b[i][j]); System.out.println(); } } } Input & Output : INPUT : LAB MANUAL OUTPUT : Copyright cserockz08, 2009 www.cserockz.com Page 85

Object Oriented Programming Program Statement : LAB MANUAL Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the ba se class provide methods that are common to all Rodents and override these in th e 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. Program : import java.util.Random; cla ss Rodent{ void place() {} void tail() {} void eat() {} public static Rodent ran dRodent(){ Random rr=new Random(); switch (rr.nextInt(4)) { case 0: return new M ouse(); case 1: return new Gerbil (); case 2: return new Hamster (); case 3: ret urn new Beaver (); } return new Rodent(); } } class Mouse extends Rodent { void place() { System.out.println(Mice are found all over the world); } void tail() { S ystem.out.println(Mice have long and hairless tail); } void eat() { System.out.pri ntln(Mice eat cardboards, papers, clothes); } Copyright cserockz08, 2009 www.cserockz.com Page 86

Object Oriented Programming } LAB MANUAL class Gerbil extends Rodent { void place() { System.out.println(Gerbils are found in arid parts of Africa and Asia); } void tail() { System.out.println(Gerbils hav e long tail); } void eat() { System.out.println(Gerbils eat seeds, roots, insects, parts of plants); } } class Hamster extends Rodent { void place() { System.out.p rintln(Hamsters are found in Western Europe to China Dry regions only); } void tai l() { System.out.println(Hamsters have short tail); } void eat() { System.out.prin tln(Hamsters eat cereals); } } class Beaver extends Rodent { void place() { System .out.println(Beavers are found in Northern Europe and North America); } void tail( ) { System.out.println(Beavers have broad tail); } void eat() { System.out.println (Beavers eat bark); Copyright cserockz08, 2009 www.cserockz.com Page 87

Object Oriented Programming } } public class Rodents{ public static void main(String args[ ]) { Rodent r[] = new Rodent[6]; for (int i=0; i<r.length; i++) r[i] = Rodent.randRodent(); for ( int i=0; i<r.length; i++) { r[i].place(); r[i].tail(); r[i].eat(); } } } LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 88

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 89

Object Oriented Programming Program Statement : WAJP to print a chessboard pattern. Program : import java.aw t.*; import java.applet.*; LAB MANUAL public class ChessBoard extends Applet { /* This applet draws a red-and-black ch eckerboard. It is assumed that the size of the applet is 160 by 160 pixels. */ / * <applet code="ChessBoard.class" width=200 height=160> </applet> */ public void paint(Graphics g) { int row; // Row number, from 0 to 7 int col; // Column numb er, from 0 to 7 int x,y; // Top-left corner of square for ( row = 0; row < 8; ro w++ ) { for ( col = 0; col < 8; col++) { x = col * 40; y = row * 40; if ( (row % 2) == (col % 2) ) g.setColor(Color.white); else g.setColor(Color.black); g.fill Rect(x, y, 40, 40); } } // end for row } // end paint() } // end class Copyright cserockz08, 2009 www.cserockz.com Page 90

Object Oriented Programming Input & Output : LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 91

Object Oriented Programming LAB MANUAL VIVA VOCE QUESTIONS 1) What is a method? And What is OOPS? 2) What is the signature of a method? 3) What is the difference between an instance variable and a class variable? 4) Wha t is an abstract method? 5) What is an abstract class? 6)What is an object refer ence? 7) What is an exception? 8) Why does the compiler complain about Interrupt ed Exception when I try to use Thread s sleep method? 9) Why do methods have to declare the exceptions they can throw? 10) What s the difference between a runti me exception and a plain exception-why don t you runtime exceptions have to be d eclared? 11) What is an applet? 12) . How do applets differ from applications? 1 3) . Can I write Java code that works both as an applet and as a standalone appl ication? 14). What is the difference between an application, an applet, and a se rvlet? 15) Several applet methods seem special, in that I need to define them ev en if my own code doesn t invoke them--what are the methods, and when (and by wh om) are they invoked? 16). Should applets have constructors? 17) . How can my ap plet tell when a user leaves or returns to the web page containing my applet? 18 ) . How do I read number information from my applet s parameters, given that App let s getParameter method returns a String? Copyright cserockz08, 2009 www.cserockz.com Page 92

Object Oriented Programming LAB MANUAL 19) . When I subclass Applet, why should I put setup code in the init() method? Why not just a constructor for my class? 20). Can I use an http URL to write to a file on the server from an applet? 21) . Can applets launch programs on the server? 22) . Can applets launch progra ms on the client? 23) . How do you do file I/O from an applet? 24) . How do I ac cess remote machine s file system through Java Applet? 25) What is a thread? 26) . How do I create a thread and start it running? 27) . How many threads can I c reate? 28) . How does Thread s stop method work--can I restart a stopped thread? 29) . If I create a thread, and then null out the reference to it, what happens to the thread? Does it get interrupted or what? 30) . How should I stop a threa d so that I can start a new thread later in its place? 31) .How do I specify pau se times in my program? 32) Why is thread synchronization important for multithr eaded programs? 33) . What is a monitor? 34) . How does the synchronized keyword work? 35) . What objects do static synchronized methods use for locking? 36) . How do the wait and notifyAll/notify methods enable cooperation between threads? Copyright cserockz08, 2009 www.cserockz.com Page 93

Object Oriented Programming LAB MANUAL 37) . How do I achieve the effect of condition variables if the Java platform pr ovides me with only wait and notifyAll/notify methods? 38) . How do I make one t hread wait for one or more other threads to finish? 39) . What do I use the yiel d method for? 40) . Does the Java Virtual Machine protect me against deadlocks? 41) . I have several worker threads. I want my main thread to wait for any of th em to complete, and take action as soon as any of them completes. I don t know w hich will complete soonest, so I can t just call Thread.join on that one. How do I do it? 42) How do I do keyboard (interactive) I/O in Java? 43) . Is there a w ay to read a char from the keyboard without having to type carriage-return? 44). How do I read a line of input at a time? 45) . How do I read input from the use r (or send output) analogous to using standard input and standard output in C or C++? 46) . Is there a standard way to read in int, long, float, and double valu es from a string representation? 47) . How do I read a String/int/boolean/etc fr om the keyboard? 48) . I try to use "int i = System.in.read();" to read in an in t from the standard input stream. It doesn t work. Why? 49) . I use the followin g to read an int. It does not work. Why? 50). I m trying to read in a character from a text file using the DataInputStream s readChar() method. However, when I print it out, I get?s. 51) . Why do I get garbage results when I use DataInputStr eam s readInt or readFloat methods to read in a number from an input string? 52) . How do I read data from a file? 53) . How do I write data to a file? 54). How do I append data to a file? 55). When do I need to flush an output stream? Copyright cserockz08, 2009 www.cserockz.com Page 94

Object Oriented Programming LAB MANUAL 56) . Why do I see in/ls")? 57) . Can am? 58) . How do I n an applet? 60) . no output when I run a simple process, such as r.exec("/usr/b I write objects to and read objects from a file or other stre format numbers like C s printf()? 59). How do I do file I/O i How do I do I/O to the serial port on my computer

61) . How do I do formatted I/O like printf and scanf in C/C++? 62). How do I re ad a file containing ASCII numbers? 63) . Why do I have trouble with System.out. println()? 64). How do I write to the serial port on my PC using Java? 65) . Is it possible to lock a file using Java ? 66) . How do I make the keyboard beep in Java? 67). How do I make I/O faster? My file copy program is slow. 68). How do I do formatted I/O of floating point numbers? 69). How do I read numbers in expo nential format in Java? 70) . How do I delete a directory in Java? 71). How do I tell how much disk space is free in Java? 71) . How do I get a directory listin g of the root directory C:\ on a PC? 72). I did a read from a Buffered stream, a nd I got fewer bytes than I specified 73) . How do I redirect the System.err str eam to a file? 74) . What are the values for the Unicode encoding schemes? 75) . How do I print from a Java program? 76) . What are the properties that can be u sed in a PrintJob? 77) . How do I get Java talking to a Microsoft Access databas e? 78). How do I do I/O redirection in Java using exec()? cserockz08, 2009 Copyright www.cserockz.com Page 95

Object Oriented Programming 79) What is the signature of a method? LAB MANUAL 81) How do I create an instance of a class? 82) . Why do I get the java.lang.Uns atisfiedLinkError when I run my Java program containing Native Method invocation s? 83) Given a method that doesn t declare any exceptions, can I override that m ethod in a subclass to throw an exception? 84) What s the difference between a r untime exception and a plain exception-why don t runtime exceptions have to be d eclared? 85) Why do methods have to declare the exceptions they can throw? 86) W hy does the compiler complain about Interrupted Exception when I try to use Thre ad s sleep method? 87) What is an exception? 88) I can t seem to change the valu e of an Integer object once created. 89) How can I safely store particular types in general containers? 90) Why is the String class final? I often want to overr ide it. 91) . How do static methods interact with inheritance? 92) Where can I f ind examples of the use of the Java class libraries? 93) How can I find the form at of a .class file/any file? 94) What are "class literals"? 95) What is an obje ct reference? 96) What does it mean that a method or class is abstract? 97) What is an abstract class? 98) What is an abstract method? 99) How do I create an in stance of a class? 100) What is an object reference? 101) What are "class litera ls"? 102) What are the values for the Unicode encoding schemes? 103) How do I pr int from a Java program? 104) How do I get a directory listing of the root direc tory C:\ on a PC? Copyright cserockz08, 2009 www.cserockz.com Page 96

Object Oriented Programming 105) How do I delete a directory in Java? LAB MANUAL 106) How do I read numbers in exponential format in Java? 107) How do I do forma tted I/O of floating point numbers? 108) How do I make I/O faster? My file copy program is slow. 109) Is it possible to lock a file using Java ? 110) How do I w rite to the serial port on my PC using Java? . 111) 112) 113) 114) 115) Why do I have trouble with System.out.println()? How do I read a file containing ASCII n umbers? How do I do formatted I/O like printf and scanf in C/C++? How do I do I/ O to the serial port on my computer? How do I do file I/O in an applet? 116) Can I write objects to and read objects from a file or other stream? 117) W hy do I see no output when I run a simple process, such as r.exec("/usr/bin/ls") ? 118) When do I need to flush an output stream? 119) How do I append data to a file? 120) How do I write data to a file? 121) How do I read data from a file? 1 22) Explain the Polymorphism principle. 123) Why do methods have to declare the exceptions they can throw? 124) Explain the different forms of Polymorphism. 125 ) Describe the principles of OOPS 126) What is the difference between encapsulat ion datahiding.explain with example 127) What is the use/advantage of function o verloading 128) Explain the Inheritance Principle 129) Can we inherit private me mbers of class ? 130) Why do you need abstraction? Copyright and cserockz08, 2009 www.cserockz.com Page 97

Object Oriented Programming 131) How macro execution is faster than function ? LAB MANUAL 132) What is size of class having no variable & 1 function which returns int 133 ) Difference between object-oriented programming and procedure oriented programm ing 134) What do you mean by realization in oops, what is presistent,transient o bject. 135)What is the use of procedure overriding 136) What are enumerators? and what are in-line functions? giv ans with eg. 137) Is it possible to change the address of an array? 138) What is the race conditi on? 139) What are the advantages of Object Oriented Modeling? Copyright cserockz08, 2009 www.cserockz.com Page 98

Object Oriented Programming REFERENCES: BOOKS: 1. Thinking in Java Bruce Eckel 2. Beginning Java 2- Ivbor ho rton 3. Just Java 1.2- Peter van der linder 4. Big Java 2-Cay Horstmann 5. Intro duction to java programming-Y.Daniel Liang LAB MANUAL WEBSITES: 1. www.java.com 2. www.java.sun.com 3. www.roseindia.net 4. www.javalobby.org 5. www.javabeat.net Copyright cserockz08, 2009 www.cserockz.com Page 99

Object Oriented Programming LAB MANUAL PROCEDURE FOR INSTALLING JAVA 1.5/1.6 VERSION STEP 1: First install the java ver sion (1.5/1.6) Ur having..! STEP 2: GO TO MY COMPUTER Copyright cserockz08, 2009 www.cserockz.com Page 100

Object Oriented Programming LAB MANUAL THEN go to the drive where u have installed java For e.g.: 1. Go to c:drive Copyright cserockz08, 2009 www.cserockz.com Page 101

Object Oriented Programming LAB MANUAL 2. In PROGRAM FILES 3. GO TO JAVA Copyright cserockz08, 2009 www.cserockz.com Page 102

Object Oriented Programming LAB MANUAL 4. GO tojdk (1.5/1.6).0_01 Copyright cserockz08, 2009 www.cserockz.com Page 103

Object Oriented Programming LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 104

Object Oriented Programming LAB MANUAL 5. Go to bin. 6. Go to lib. STEP 3: My computer--- Properties Copyright cserockz08, 2009 www.cserockz.com Page 105

Object Oriented Programming LAB MANUAL Properties--- Advanced Copyright cserockz08, 2009 www.cserockz.com Page 106

Object Oriented Programming LAB MANUAL Advanced--- Environmental variables Copyright cserockz08, 2009 www.cserockz.com Page 107

Object Oriented Programming LAB MANUAL Environmental variables--- System variables--- NEW Copyright cserockz08, 2009 www.cserockz.com Page 108

Object Oriented Programming LAB MANUAL Variable name: PATH Variable value: C:\Program Files\Java\jdk1.6.0_01\bin; **NOT E: For this go to step 2:-- 5th step! Copyright cserockz08, 2009 www.cserockz.com Page 109

Object Oriented Programming LAB MANUAL Environmental variables--- System variables--- NEW Copyright cserockz08, 2009 www.cserockz.com Page 110

Object Oriented Programming LAB MANUAL Variable name: CLASSPATH Variable value: C:\Program Files\Java\jdk1.6.0_01\lib\r t.jre; **NOTE: For this go to step 2:-- 6th step! ****//THE RED COLOURED PATH SHOULD BE ADDED.***// Copyright cserockz08, 2009 www.cserockz.com Page 111

Object Oriented Programming LAB MANUAL Then click OK..! Copyright cserockz08, 2009 www.cserockz.com Page 112

Object Oriented Programming LAB MANUAL JAVA INSTALLATION IS FINISHED..! Copyright cserockz08, 2009 www.cserockz.com Page 113

Object Oriented Programming LAB MANUAL EMAIL: cserockz08@gmail.com srinivas30k@gmail.com www.cserockz.com Keep Watching for Regular Updates.!! Copyright cserockz08, 2009 www.cserockz.com Page 114

Object Oriented Programming LAB MANUAL Copyright cserockz08, 2009 www.cserockz.com Page 115

Anda mungkin juga menyukai