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 the structured programming concepts. The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves. Data and its functions are encapsulated into a single entity.OOP facilitates creating reusable code that can eventually save a lot of work. A feature called polymorphism permits to create multiple definitions for operators and functions. Another feature called inheritance permits to derive new classes from old ones. OOP introduces many new ideas and involves a different approach to programming 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++ Knowledge: C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language 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. The 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 objects. 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 place, 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 defined 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 belonging 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 mango; will create an object mango belonging to the class fruit. Data Abstraction and Encapsulation: The wrapping up of data and functions in to a single unit is known 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 which are wrapped in the class can access. This insulation of the data from direct access 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). Inheritance : Inheritance is the process by which objects of one class acquire the properties of objects of another class. Inheritance supports the concept of hierarchical classification. for example: Bird Attributes: Feathers Lay eggs
Flying bird
Non flying bird
Attributes: --------------------
Attributes: ---------------------
Robin
Swallow
Attributes: _________
Attributes: _________
Penguin
Kiwi
Attributes: _________
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 instances. The behavior depends upon the types of data used in the operation. The process of making an operator to exhibit different behaviors in different instance is known as operator overloading. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used if implementing inheritance. Shape Draw()
Circle Object
Box Object
Triangle Object
Draw()
Draw()
Draw()
The Object-Oriented Approach The fundamental idea behind object-oriented languages is to combine into a single program entity both data and the functions that operate 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 objects), 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 the item and return the value to you. You can't access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are said to be encapsulated into a single entity. Encapsulation and data hiding are key terms in the description of object-oriented languages.
© Copyright
cserockz08, 2009
www.cserockz.com
Page 5
Object Oriented Programming
LAB MANUAL
Java History: 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 inventors if the language. This goal had a strong impact on the development team to make the language simple, portable, highly reliable and powerful language. Java 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++
Java C
© 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
HTML files
Javadoc
Javac
Java Class File
Java (only file name)
Javah
Header Files
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 code is then compiled using the java compiler javac and executed using the java interpreter java. The java debugger jdb is used to find errors. A complied java program 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 discriminant 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 preceding it. Write a Java program that uses both recursive and non-recursive functions 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 is 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 class) 8. WAJP that reads on file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes. 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)
LAB MANUAL
Converts Infix expression to Postfix expression Evaluates a Postfix expression
12. Write an Applet that displays a simple message. 13. Write an Applet that computes the payment of a loan based on the amount of the loan, 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 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 the result. 15. WAJP for handling mouse events. 16. WAJP for creating multiple threads. 17. WAJP that correctly implements Producer-Consumer problem using the concept 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/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. 21. WAJP that illustrates how runtime polymorphism is achieved. 22. WAJP to generate a set of random numbers. Find its sum and average. The program should 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 numberOfSides(), 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 throw, 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 seconds and the third displays “Welcome” every 3 seconds. (Repeat the same by implementing 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 Java?” (b) To accept an answer (c) To printout “GOOD” and then stop if the answer is correct (d) To output the message “TRY AGAIN”, if the answer is wrong (e) To display the correct answer, when the answer is wrong even at the third attempt 28. WAJP to transpose a matrix using ‘arraycopy’ command. 29. 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. 30. WAJP to print a chessboard pattern.
© Copyright
cserockz08, 2009
www.cserockz.com
Page 10
Object Oriented Programming
LAB MANUAL
Program Statement : Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2-4ac is negative, display a message stating that there are no real solutions. Program : import java.io.*; class Quadratic { public static void main(String args[])throws IOException { double x1,x2,disc,a,b,c; InputStreamReader obj=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(obj); System.out.println("enter a,b,c values"); a=Double.parseDouble(br.readLine()); b=Double.parseDouble(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.println("roots are real and unequal");
© Copyright
cserockz08, 2009
www.cserockz.com
Page 11
Object Oriented Programming
LAB MANUAL
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 :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 12
Object Oriented Programming
LAB MANUAL
Program Statement : 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 that uses both recursive and non-recursive functions to print the nth value of the Fibonacci sequence. Program : /*Non Recursive Solution*/ 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.println("Enter value of t:"); t=input.nextInt(); System.out.print(a); System.out.print(" "+b); for(i=0;i
© Copyright
cserockz08, 2009
www.cserockz.com
Page 13
Object Oriented Programming
LAB MANUAL
Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 14
Object Oriented Programming
LAB MANUAL
/* Recursive Solution*/ import java.io.*; import java.lang.*; class Demo { int fib(int n) { if(n==1) return (1); else if(n==2) return (1); else return (fib(n-1)+fib(n-2)); } } class RecFibDemo { public static void main(String args[])throws IOException { InputStreamReader obj=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(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 is "+res); } } © Copyright
cserockz08, 2009
www.cserockz.com
Page 15
Object Oriented Programming
LAB MANUAL
Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 16
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that prompts the user for an integer and then prints out all the prime numbers 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
© Copyright
cserockz08, 2009
www.cserockz.com
Page 17
Object Oriented Programming
LAB MANUAL
Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 18
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. Program : import java.io.*; class Palind { public static void main(String args[ ])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the string to check for palindrome:"); String s1=br.readLine(); StringBuffer sb=new StringBuffer(); sb.append(s1); sb.reverse(); String s2=sb.toString(); if(s1.equals(s2)) System.out.println("palindrome"); else System.out.println("not palindrome"); } }
© Copyright
cserockz08, 2009
www.cserockz.com
Page 19
Object Oriented Programming
LAB MANUAL
Input &
Output
© Copyright
cserockz08, 2009
www.cserockz.com
Page 20
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP for sorting a given list of names in ascending order. Program : import java.io.*; class Test { int len,i,j; String arr[ ]; Test(int n) { len=n; arr=new String[n]; } String[ ] getArray()throws IOException { BufferedReader br=new BufferedReader (new InputStreamReader(System.in)); System.out.println ("Enter the strings U want to sort----"); for (int i=0;i
0) { String s1=arr[i]; arr[i]=arr[j]; arr[j]=s1; } } } return arr; } void display()throws ArrayIndexOutOfBoundsException { © Copyright
cserockz08, 2009
www.cserockz.com
Page 21
Object Oriented Programming
}
LAB MANUAL
System.out.println ("Sorted list is---"); for (i=0;i
class Ascend { public static void main(String args[ ])throws IOException { Test obj1=new Test(4); obj1.getArray(); obj1.check(); obj1.display(); } } Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 22
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP to multiply two given matrices. Program : import java.util.*; 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; } 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
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
© Copyright
cserockz08, 2009
www.cserockz.com
Page 24
Object Oriented Programming
LAB MANUAL
Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 25
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that reads a line of integers and then displays each integer and the sum of all integers. (use StringTokenizer class) Program : // Using StringTokenizer class 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.hasMoreTokens()) { int b=Integer.parseInt(a.nextToken()); sum=sum+b; System.out.println(" "+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
cserockz08, 2009
www.cserockz.com
Page 26
Object Oriented Programming
LAB MANUAL
for(int i=0;i
© Copyright
cserockz08, 2009
www.cserockz.com
Page 27
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that reads on file name from the user, then displays information about whether 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); } public static void main(String args[ ]) { File f1 = new File(args[0]); p("File Name: " + f1.getName()); p("Path: " + f1.getPath()); p("Abs Path: " + f1.getAbsolutePath()); p("Parent: " + f1.getParent()); p(f1.exists() ? "exists" : "does not exist"); p(f1.canWrite() ? "is writeable" : "is not writeable"); p(f1.canRead() ? "is 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: " + f1.lastModified()); p("File size: " + f1.length() + " Bytes"); } }
© Copyright
cserockz08, 2009
www.cserockz.com
Page 28
Object Oriented Programming
LAB MANUAL
Input & Output :
:
© Copyright
cserockz08, 2009
www.cserockz.com
Page 29
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that reads a file and displays the file on the screen, with a line number before each line. Program : import java.io.*; class LineNum{ public static void main(String args[]){ String thisline; for(int i=0;i<args.length;i++) { try{ LineNumberReader br=new LineNumberReader(new FileReader(args[i])); while((thisline=br.readLine())!=null) { System.out.println(br.getLineNumber()+"."+thisline); } }catch(IOException e){ System.out.println("error:"+e); } } } }
© Copyright
cserockz08, 2009
www.cserockz.com
Page 30
Object Oriented Programming
LAB MANUAL
Input & Output :
© 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 static void main(String args[ ])throws IOException { long nl=0,nw=0,nc=0; String line; BufferedReader br=new BufferedReader(new FileReader(args[0])); while ((line=br.readLine())!=null) { nl++; nc=nc+line.length(); int i=0; boolean pspace=true; while (i
cserockz08, 2009
www.cserockz.com
Page 32
Object Oriented Programming
LAB MANUAL
nc=nc+line.length(); StringTokenizer st = new StringTokenizer(line); nw += st.countTokens(); } System.out.println("Number of Characters"+nc); System.out.println("Number of Characters"+nw); System.out.println("Number of Characters"+nl); }} Input & Output :
© Copyright
cserockz08, 2009
www.cserockz.com
Page 33
Object Oriented Programming
LAB MANUAL
Program Statement : WAJP that: (a) Implements a Stack ADT (b) Converts Infix expression to Postfix expression (c) Evaluates a Postfix expression
Program : import java.io.*; interface stack { void push(int item); int pop(); } class Stackimpl { private int stck[]; private int top; Stackimpl(int size) { stck=new int[size]; top=-1; } void push(int item) { if(top==stck.length-1) System.out.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"); return 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)); System.out.println("enter the size of the array"); int n=Integer.parseInt(br.readLine()); Stackimpl obj1=new Stackimpl(n); a=new int[n]; System.out.println("enter numbers into the stack"); for(int i=0;i
cserockz08, 2009
www.cserockz.com
Page 35
Object Oriented Programming
LAB MANUAL
for(int i=0;i
© Copyright
cserockz08, 2009
www.cserockz.com
Page 36
Object Oriented Programming
LAB MANUAL
Program Statement : Write an Applet that displays a simple message. Program : import java.awt.*; import java.applet.*; /*